• 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 with
1206 	 * snapshot creation.
1207 	 */
1208 	lockdep_assert_held_write(&fs_info->subvol_sem);
1209 
1210 	/*
1211 	 * Lock the cleaner mutex to prevent races with concurrent relocation,
1212 	 * because relocation may be building backrefs for blocks of the quota
1213 	 * root while we are deleting the root. This is like dropping fs roots
1214 	 * of deleted snapshots/subvolumes, we need the same protection.
1215 	 *
1216 	 * This also prevents races between concurrent tasks trying to disable
1217 	 * quotas, because we will unlock and relock qgroup_ioctl_lock across
1218 	 * BTRFS_FS_QUOTA_ENABLED changes.
1219 	 */
1220 	mutex_lock(&fs_info->cleaner_mutex);
1221 
1222 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1223 	if (!fs_info->quota_root)
1224 		goto out;
1225 
1226 	/*
1227 	 * Unlock the qgroup_ioctl_lock mutex before waiting for the rescan worker to
1228 	 * complete. Otherwise we can deadlock because btrfs_remove_qgroup() needs
1229 	 * to lock that mutex while holding a transaction handle and the rescan
1230 	 * worker needs to commit a transaction.
1231 	 */
1232 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1233 
1234 	/*
1235 	 * Request qgroup rescan worker to complete and wait for it. This wait
1236 	 * must be done before transaction start for quota disable since it may
1237 	 * deadlock with transaction by the qgroup rescan worker.
1238 	 */
1239 	clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1240 	btrfs_qgroup_wait_for_completion(fs_info, false);
1241 
1242 	/*
1243 	 * 1 For the root item
1244 	 *
1245 	 * We should also reserve enough items for the quota tree deletion in
1246 	 * btrfs_clean_quota_tree but this is not done.
1247 	 *
1248 	 * Also, we must always start a transaction without holding the mutex
1249 	 * qgroup_ioctl_lock, see btrfs_quota_enable().
1250 	 */
1251 	trans = btrfs_start_transaction(fs_info->tree_root, 1);
1252 
1253 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1254 	if (IS_ERR(trans)) {
1255 		ret = PTR_ERR(trans);
1256 		trans = NULL;
1257 		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1258 		goto out;
1259 	}
1260 
1261 	if (!fs_info->quota_root)
1262 		goto out;
1263 
1264 	spin_lock(&fs_info->qgroup_lock);
1265 	quota_root = fs_info->quota_root;
1266 	fs_info->quota_root = NULL;
1267 	fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1268 	spin_unlock(&fs_info->qgroup_lock);
1269 
1270 	btrfs_free_qgroup_config(fs_info);
1271 
1272 	ret = btrfs_clean_quota_tree(trans, quota_root);
1273 	if (ret) {
1274 		btrfs_abort_transaction(trans, ret);
1275 		goto out;
1276 	}
1277 
1278 	ret = btrfs_del_root(trans, &quota_root->root_key);
1279 	if (ret) {
1280 		btrfs_abort_transaction(trans, ret);
1281 		goto out;
1282 	}
1283 
1284 	spin_lock(&fs_info->trans_lock);
1285 	list_del(&quota_root->dirty_list);
1286 	spin_unlock(&fs_info->trans_lock);
1287 
1288 	btrfs_tree_lock(quota_root->node);
1289 	btrfs_clean_tree_block(quota_root->node);
1290 	btrfs_tree_unlock(quota_root->node);
1291 	btrfs_free_tree_block(trans, quota_root, quota_root->node, 0, 1);
1292 
1293 	btrfs_put_root(quota_root);
1294 
1295 out:
1296 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1297 	if (ret && trans)
1298 		btrfs_end_transaction(trans);
1299 	else if (trans)
1300 		ret = btrfs_end_transaction(trans);
1301 	mutex_unlock(&fs_info->cleaner_mutex);
1302 
1303 	return ret;
1304 }
1305 
qgroup_dirty(struct btrfs_fs_info * fs_info,struct btrfs_qgroup * qgroup)1306 static void qgroup_dirty(struct btrfs_fs_info *fs_info,
1307 			 struct btrfs_qgroup *qgroup)
1308 {
1309 	if (list_empty(&qgroup->dirty))
1310 		list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1311 }
1312 
1313 /*
1314  * The easy accounting, we're updating qgroup relationship whose child qgroup
1315  * only has exclusive extents.
1316  *
1317  * In this case, all exclusive extents will also be exclusive for parent, so
1318  * excl/rfer just get added/removed.
1319  *
1320  * So is qgroup reservation space, which should also be added/removed to
1321  * parent.
1322  * Or when child tries to release reservation space, parent will underflow its
1323  * reservation (for relationship adding case).
1324  *
1325  * Caller should hold fs_info->qgroup_lock.
1326  */
__qgroup_excl_accounting(struct btrfs_fs_info * fs_info,struct ulist * tmp,u64 ref_root,struct btrfs_qgroup * src,int sign)1327 static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
1328 				    struct ulist *tmp, u64 ref_root,
1329 				    struct btrfs_qgroup *src, int sign)
1330 {
1331 	struct btrfs_qgroup *qgroup;
1332 	struct btrfs_qgroup_list *glist;
1333 	struct ulist_node *unode;
1334 	struct ulist_iterator uiter;
1335 	u64 num_bytes = src->excl;
1336 	int ret = 0;
1337 
1338 	qgroup = find_qgroup_rb(fs_info, ref_root);
1339 	if (!qgroup)
1340 		goto out;
1341 
1342 	qgroup->rfer += sign * num_bytes;
1343 	qgroup->rfer_cmpr += sign * num_bytes;
1344 
1345 	WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1346 	qgroup->excl += sign * num_bytes;
1347 	qgroup->excl_cmpr += sign * num_bytes;
1348 
1349 	if (sign > 0)
1350 		qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1351 	else
1352 		qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1353 
1354 	qgroup_dirty(fs_info, qgroup);
1355 
1356 	/* Get all of the parent groups that contain this qgroup */
1357 	list_for_each_entry(glist, &qgroup->groups, next_group) {
1358 		ret = ulist_add(tmp, glist->group->qgroupid,
1359 				qgroup_to_aux(glist->group), GFP_ATOMIC);
1360 		if (ret < 0)
1361 			goto out;
1362 	}
1363 
1364 	/* Iterate all of the parents and adjust their reference counts */
1365 	ULIST_ITER_INIT(&uiter);
1366 	while ((unode = ulist_next(tmp, &uiter))) {
1367 		qgroup = unode_aux_to_qgroup(unode);
1368 		qgroup->rfer += sign * num_bytes;
1369 		qgroup->rfer_cmpr += sign * num_bytes;
1370 		WARN_ON(sign < 0 && qgroup->excl < num_bytes);
1371 		qgroup->excl += sign * num_bytes;
1372 		if (sign > 0)
1373 			qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1374 		else
1375 			qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1376 		qgroup->excl_cmpr += sign * num_bytes;
1377 		qgroup_dirty(fs_info, qgroup);
1378 
1379 		/* Add any parents of the parents */
1380 		list_for_each_entry(glist, &qgroup->groups, next_group) {
1381 			ret = ulist_add(tmp, glist->group->qgroupid,
1382 					qgroup_to_aux(glist->group), GFP_ATOMIC);
1383 			if (ret < 0)
1384 				goto out;
1385 		}
1386 	}
1387 	ret = 0;
1388 out:
1389 	return ret;
1390 }
1391 
1392 
1393 /*
1394  * Quick path for updating qgroup with only excl refs.
1395  *
1396  * In that case, just update all parent will be enough.
1397  * Or we needs to do a full rescan.
1398  * Caller should also hold fs_info->qgroup_lock.
1399  *
1400  * Return 0 for quick update, return >0 for need to full rescan
1401  * and mark INCONSISTENT flag.
1402  * Return < 0 for other error.
1403  */
quick_update_accounting(struct btrfs_fs_info * fs_info,struct ulist * tmp,u64 src,u64 dst,int sign)1404 static int quick_update_accounting(struct btrfs_fs_info *fs_info,
1405 				   struct ulist *tmp, u64 src, u64 dst,
1406 				   int sign)
1407 {
1408 	struct btrfs_qgroup *qgroup;
1409 	int ret = 1;
1410 	int err = 0;
1411 
1412 	qgroup = find_qgroup_rb(fs_info, src);
1413 	if (!qgroup)
1414 		goto out;
1415 	if (qgroup->excl == qgroup->rfer) {
1416 		ret = 0;
1417 		err = __qgroup_excl_accounting(fs_info, tmp, dst,
1418 					       qgroup, sign);
1419 		if (err < 0) {
1420 			ret = err;
1421 			goto out;
1422 		}
1423 	}
1424 out:
1425 	if (ret)
1426 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1427 	return ret;
1428 }
1429 
btrfs_add_qgroup_relation(struct btrfs_trans_handle * trans,u64 src,u64 dst)1430 int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1431 			      u64 dst)
1432 {
1433 	struct btrfs_fs_info *fs_info = trans->fs_info;
1434 	struct btrfs_qgroup *parent;
1435 	struct btrfs_qgroup *member;
1436 	struct btrfs_qgroup_list *list;
1437 	struct ulist *tmp;
1438 	unsigned int nofs_flag;
1439 	int ret = 0;
1440 
1441 	/* Check the level of src and dst first */
1442 	if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
1443 		return -EINVAL;
1444 
1445 	/* We hold a transaction handle open, must do a NOFS allocation. */
1446 	nofs_flag = memalloc_nofs_save();
1447 	tmp = ulist_alloc(GFP_KERNEL);
1448 	memalloc_nofs_restore(nofs_flag);
1449 	if (!tmp)
1450 		return -ENOMEM;
1451 
1452 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1453 	if (!fs_info->quota_root) {
1454 		ret = -ENOTCONN;
1455 		goto out;
1456 	}
1457 	member = find_qgroup_rb(fs_info, src);
1458 	parent = find_qgroup_rb(fs_info, dst);
1459 	if (!member || !parent) {
1460 		ret = -EINVAL;
1461 		goto out;
1462 	}
1463 
1464 	/* check if such qgroup relation exist firstly */
1465 	list_for_each_entry(list, &member->groups, next_group) {
1466 		if (list->group == parent) {
1467 			ret = -EEXIST;
1468 			goto out;
1469 		}
1470 	}
1471 
1472 	ret = add_qgroup_relation_item(trans, src, dst);
1473 	if (ret)
1474 		goto out;
1475 
1476 	ret = add_qgroup_relation_item(trans, dst, src);
1477 	if (ret) {
1478 		del_qgroup_relation_item(trans, src, dst);
1479 		goto out;
1480 	}
1481 
1482 	spin_lock(&fs_info->qgroup_lock);
1483 	ret = add_relation_rb(fs_info, src, dst);
1484 	if (ret < 0) {
1485 		spin_unlock(&fs_info->qgroup_lock);
1486 		goto out;
1487 	}
1488 	ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1489 	spin_unlock(&fs_info->qgroup_lock);
1490 out:
1491 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1492 	ulist_free(tmp);
1493 	return ret;
1494 }
1495 
__del_qgroup_relation(struct btrfs_trans_handle * trans,u64 src,u64 dst)1496 static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1497 				 u64 dst)
1498 {
1499 	struct btrfs_fs_info *fs_info = trans->fs_info;
1500 	struct btrfs_qgroup *parent;
1501 	struct btrfs_qgroup *member;
1502 	struct btrfs_qgroup_list *list;
1503 	struct ulist *tmp;
1504 	bool found = false;
1505 	unsigned int nofs_flag;
1506 	int ret = 0;
1507 	int ret2;
1508 
1509 	/* We hold a transaction handle open, must do a NOFS allocation. */
1510 	nofs_flag = memalloc_nofs_save();
1511 	tmp = ulist_alloc(GFP_KERNEL);
1512 	memalloc_nofs_restore(nofs_flag);
1513 	if (!tmp)
1514 		return -ENOMEM;
1515 
1516 	if (!fs_info->quota_root) {
1517 		ret = -ENOTCONN;
1518 		goto out;
1519 	}
1520 
1521 	member = find_qgroup_rb(fs_info, src);
1522 	parent = find_qgroup_rb(fs_info, dst);
1523 	/*
1524 	 * The parent/member pair doesn't exist, then try to delete the dead
1525 	 * relation items only.
1526 	 */
1527 	if (!member || !parent)
1528 		goto delete_item;
1529 
1530 	/* check if such qgroup relation exist firstly */
1531 	list_for_each_entry(list, &member->groups, next_group) {
1532 		if (list->group == parent) {
1533 			found = true;
1534 			break;
1535 		}
1536 	}
1537 
1538 delete_item:
1539 	ret = del_qgroup_relation_item(trans, src, dst);
1540 	if (ret < 0 && ret != -ENOENT)
1541 		goto out;
1542 	ret2 = del_qgroup_relation_item(trans, dst, src);
1543 	if (ret2 < 0 && ret2 != -ENOENT)
1544 		goto out;
1545 
1546 	/* At least one deletion succeeded, return 0 */
1547 	if (!ret || !ret2)
1548 		ret = 0;
1549 
1550 	if (found) {
1551 		spin_lock(&fs_info->qgroup_lock);
1552 		del_relation_rb(fs_info, src, dst);
1553 		ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1554 		spin_unlock(&fs_info->qgroup_lock);
1555 	}
1556 out:
1557 	ulist_free(tmp);
1558 	return ret;
1559 }
1560 
btrfs_del_qgroup_relation(struct btrfs_trans_handle * trans,u64 src,u64 dst)1561 int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
1562 			      u64 dst)
1563 {
1564 	struct btrfs_fs_info *fs_info = trans->fs_info;
1565 	int ret = 0;
1566 
1567 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1568 	ret = __del_qgroup_relation(trans, src, dst);
1569 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1570 
1571 	return ret;
1572 }
1573 
btrfs_create_qgroup(struct btrfs_trans_handle * trans,u64 qgroupid)1574 int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1575 {
1576 	struct btrfs_fs_info *fs_info = trans->fs_info;
1577 	struct btrfs_root *quota_root;
1578 	struct btrfs_qgroup *qgroup;
1579 	int ret = 0;
1580 
1581 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1582 	if (!fs_info->quota_root) {
1583 		ret = -ENOTCONN;
1584 		goto out;
1585 	}
1586 	quota_root = fs_info->quota_root;
1587 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1588 	if (qgroup) {
1589 		ret = -EEXIST;
1590 		goto out;
1591 	}
1592 
1593 	ret = add_qgroup_item(trans, quota_root, qgroupid);
1594 	if (ret)
1595 		goto out;
1596 
1597 	spin_lock(&fs_info->qgroup_lock);
1598 	qgroup = add_qgroup_rb(fs_info, qgroupid);
1599 	spin_unlock(&fs_info->qgroup_lock);
1600 
1601 	if (IS_ERR(qgroup)) {
1602 		ret = PTR_ERR(qgroup);
1603 		goto out;
1604 	}
1605 	ret = btrfs_sysfs_add_one_qgroup(fs_info, qgroup);
1606 out:
1607 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1608 	return ret;
1609 }
1610 
btrfs_remove_qgroup(struct btrfs_trans_handle * trans,u64 qgroupid)1611 int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1612 {
1613 	struct btrfs_fs_info *fs_info = trans->fs_info;
1614 	struct btrfs_qgroup *qgroup;
1615 	struct btrfs_qgroup_list *list;
1616 	int ret = 0;
1617 
1618 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1619 	if (!fs_info->quota_root) {
1620 		ret = -ENOTCONN;
1621 		goto out;
1622 	}
1623 
1624 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1625 	if (!qgroup) {
1626 		ret = -ENOENT;
1627 		goto out;
1628 	}
1629 
1630 	/* Check if there are no children of this qgroup */
1631 	if (!list_empty(&qgroup->members)) {
1632 		ret = -EBUSY;
1633 		goto out;
1634 	}
1635 
1636 	ret = del_qgroup_item(trans, qgroupid);
1637 	if (ret && ret != -ENOENT)
1638 		goto out;
1639 
1640 	while (!list_empty(&qgroup->groups)) {
1641 		list = list_first_entry(&qgroup->groups,
1642 					struct btrfs_qgroup_list, next_group);
1643 		ret = __del_qgroup_relation(trans, qgroupid,
1644 					    list->group->qgroupid);
1645 		if (ret)
1646 			goto out;
1647 	}
1648 
1649 	spin_lock(&fs_info->qgroup_lock);
1650 	del_qgroup_rb(fs_info, qgroupid);
1651 	spin_unlock(&fs_info->qgroup_lock);
1652 
1653 	/*
1654 	 * Remove the qgroup from sysfs now without holding the qgroup_lock
1655 	 * spinlock, since the sysfs_remove_group() function needs to take
1656 	 * the mutex kernfs_mutex through kernfs_remove_by_name_ns().
1657 	 */
1658 	btrfs_sysfs_del_one_qgroup(fs_info, qgroup);
1659 	kfree(qgroup);
1660 out:
1661 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1662 	return ret;
1663 }
1664 
btrfs_limit_qgroup(struct btrfs_trans_handle * trans,u64 qgroupid,struct btrfs_qgroup_limit * limit)1665 int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1666 		       struct btrfs_qgroup_limit *limit)
1667 {
1668 	struct btrfs_fs_info *fs_info = trans->fs_info;
1669 	struct btrfs_qgroup *qgroup;
1670 	int ret = 0;
1671 	/* Sometimes we would want to clear the limit on this qgroup.
1672 	 * To meet this requirement, we treat the -1 as a special value
1673 	 * which tell kernel to clear the limit on this qgroup.
1674 	 */
1675 	const u64 CLEAR_VALUE = -1;
1676 
1677 	mutex_lock(&fs_info->qgroup_ioctl_lock);
1678 	if (!fs_info->quota_root) {
1679 		ret = -ENOTCONN;
1680 		goto out;
1681 	}
1682 
1683 	qgroup = find_qgroup_rb(fs_info, qgroupid);
1684 	if (!qgroup) {
1685 		ret = -ENOENT;
1686 		goto out;
1687 	}
1688 
1689 	spin_lock(&fs_info->qgroup_lock);
1690 	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
1691 		if (limit->max_rfer == CLEAR_VALUE) {
1692 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1693 			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
1694 			qgroup->max_rfer = 0;
1695 		} else {
1696 			qgroup->max_rfer = limit->max_rfer;
1697 		}
1698 	}
1699 	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
1700 		if (limit->max_excl == CLEAR_VALUE) {
1701 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1702 			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
1703 			qgroup->max_excl = 0;
1704 		} else {
1705 			qgroup->max_excl = limit->max_excl;
1706 		}
1707 	}
1708 	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
1709 		if (limit->rsv_rfer == CLEAR_VALUE) {
1710 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1711 			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
1712 			qgroup->rsv_rfer = 0;
1713 		} else {
1714 			qgroup->rsv_rfer = limit->rsv_rfer;
1715 		}
1716 	}
1717 	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
1718 		if (limit->rsv_excl == CLEAR_VALUE) {
1719 			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1720 			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
1721 			qgroup->rsv_excl = 0;
1722 		} else {
1723 			qgroup->rsv_excl = limit->rsv_excl;
1724 		}
1725 	}
1726 	qgroup->lim_flags |= limit->flags;
1727 
1728 	spin_unlock(&fs_info->qgroup_lock);
1729 
1730 	ret = update_qgroup_limit_item(trans, qgroup);
1731 	if (ret) {
1732 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1733 		btrfs_info(fs_info, "unable to update quota limit for %llu",
1734 		       qgroupid);
1735 	}
1736 
1737 out:
1738 	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1739 	return ret;
1740 }
1741 
btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info * fs_info,struct btrfs_delayed_ref_root * delayed_refs,struct btrfs_qgroup_extent_record * record)1742 int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1743 				struct btrfs_delayed_ref_root *delayed_refs,
1744 				struct btrfs_qgroup_extent_record *record)
1745 {
1746 	struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
1747 	struct rb_node *parent_node = NULL;
1748 	struct btrfs_qgroup_extent_record *entry;
1749 	u64 bytenr = record->bytenr;
1750 
1751 	lockdep_assert_held(&delayed_refs->lock);
1752 	trace_btrfs_qgroup_trace_extent(fs_info, record);
1753 
1754 	while (*p) {
1755 		parent_node = *p;
1756 		entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
1757 				 node);
1758 		if (bytenr < entry->bytenr) {
1759 			p = &(*p)->rb_left;
1760 		} else if (bytenr > entry->bytenr) {
1761 			p = &(*p)->rb_right;
1762 		} else {
1763 			if (record->data_rsv && !entry->data_rsv) {
1764 				entry->data_rsv = record->data_rsv;
1765 				entry->data_rsv_refroot =
1766 					record->data_rsv_refroot;
1767 			}
1768 			return 1;
1769 		}
1770 	}
1771 
1772 	rb_link_node(&record->node, parent_node, p);
1773 	rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1774 	return 0;
1775 }
1776 
btrfs_qgroup_trace_extent_post(struct btrfs_fs_info * fs_info,struct btrfs_qgroup_extent_record * qrecord)1777 int btrfs_qgroup_trace_extent_post(struct btrfs_fs_info *fs_info,
1778 				   struct btrfs_qgroup_extent_record *qrecord)
1779 {
1780 	struct ulist *old_root;
1781 	u64 bytenr = qrecord->bytenr;
1782 	int ret;
1783 
1784 	ret = btrfs_find_all_roots(NULL, fs_info, bytenr, 0, &old_root, false);
1785 	if (ret < 0) {
1786 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
1787 		btrfs_warn(fs_info,
1788 "error accounting new delayed refs extent (err code: %d), quota inconsistent",
1789 			ret);
1790 		return 0;
1791 	}
1792 
1793 	/*
1794 	 * Here we don't need to get the lock of
1795 	 * trans->transaction->delayed_refs, since inserted qrecord won't
1796 	 * be deleted, only qrecord->node may be modified (new qrecord insert)
1797 	 *
1798 	 * So modifying qrecord->old_roots is safe here
1799 	 */
1800 	qrecord->old_roots = old_root;
1801 	return 0;
1802 }
1803 
btrfs_qgroup_trace_extent(struct btrfs_trans_handle * trans,u64 bytenr,u64 num_bytes,gfp_t gfp_flag)1804 int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
1805 			      u64 num_bytes, gfp_t gfp_flag)
1806 {
1807 	struct btrfs_fs_info *fs_info = trans->fs_info;
1808 	struct btrfs_qgroup_extent_record *record;
1809 	struct btrfs_delayed_ref_root *delayed_refs;
1810 	int ret;
1811 
1812 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
1813 	    || bytenr == 0 || num_bytes == 0)
1814 		return 0;
1815 	record = kzalloc(sizeof(*record), gfp_flag);
1816 	if (!record)
1817 		return -ENOMEM;
1818 
1819 	delayed_refs = &trans->transaction->delayed_refs;
1820 	record->bytenr = bytenr;
1821 	record->num_bytes = num_bytes;
1822 	record->old_roots = NULL;
1823 
1824 	spin_lock(&delayed_refs->lock);
1825 	ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1826 	spin_unlock(&delayed_refs->lock);
1827 	if (ret > 0) {
1828 		kfree(record);
1829 		return 0;
1830 	}
1831 	return btrfs_qgroup_trace_extent_post(fs_info, record);
1832 }
1833 
btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle * trans,struct extent_buffer * eb)1834 int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1835 				  struct extent_buffer *eb)
1836 {
1837 	struct btrfs_fs_info *fs_info = trans->fs_info;
1838 	int nr = btrfs_header_nritems(eb);
1839 	int i, extent_type, ret;
1840 	struct btrfs_key key;
1841 	struct btrfs_file_extent_item *fi;
1842 	u64 bytenr, num_bytes;
1843 
1844 	/* We can be called directly from walk_up_proc() */
1845 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1846 		return 0;
1847 
1848 	for (i = 0; i < nr; i++) {
1849 		btrfs_item_key_to_cpu(eb, &key, i);
1850 
1851 		if (key.type != BTRFS_EXTENT_DATA_KEY)
1852 			continue;
1853 
1854 		fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
1855 		/* filter out non qgroup-accountable extents  */
1856 		extent_type = btrfs_file_extent_type(eb, fi);
1857 
1858 		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1859 			continue;
1860 
1861 		bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
1862 		if (!bytenr)
1863 			continue;
1864 
1865 		num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1866 
1867 		ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
1868 						GFP_NOFS);
1869 		if (ret)
1870 			return ret;
1871 	}
1872 	cond_resched();
1873 	return 0;
1874 }
1875 
1876 /*
1877  * Walk up the tree from the bottom, freeing leaves and any interior
1878  * nodes which have had all slots visited. If a node (leaf or
1879  * interior) is freed, the node above it will have it's slot
1880  * incremented. The root node will never be freed.
1881  *
1882  * At the end of this function, we should have a path which has all
1883  * slots incremented to the next position for a search. If we need to
1884  * read a new node it will be NULL and the node above it will have the
1885  * correct slot selected for a later read.
1886  *
1887  * If we increment the root nodes slot counter past the number of
1888  * elements, 1 is returned to signal completion of the search.
1889  */
adjust_slots_upwards(struct btrfs_path * path,int root_level)1890 static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1891 {
1892 	int level = 0;
1893 	int nr, slot;
1894 	struct extent_buffer *eb;
1895 
1896 	if (root_level == 0)
1897 		return 1;
1898 
1899 	while (level <= root_level) {
1900 		eb = path->nodes[level];
1901 		nr = btrfs_header_nritems(eb);
1902 		path->slots[level]++;
1903 		slot = path->slots[level];
1904 		if (slot >= nr || level == 0) {
1905 			/*
1906 			 * Don't free the root -  we will detect this
1907 			 * condition after our loop and return a
1908 			 * positive value for caller to stop walking the tree.
1909 			 */
1910 			if (level != root_level) {
1911 				btrfs_tree_unlock_rw(eb, path->locks[level]);
1912 				path->locks[level] = 0;
1913 
1914 				free_extent_buffer(eb);
1915 				path->nodes[level] = NULL;
1916 				path->slots[level] = 0;
1917 			}
1918 		} else {
1919 			/*
1920 			 * We have a valid slot to walk back down
1921 			 * from. Stop here so caller can process these
1922 			 * new nodes.
1923 			 */
1924 			break;
1925 		}
1926 
1927 		level++;
1928 	}
1929 
1930 	eb = path->nodes[root_level];
1931 	if (path->slots[root_level] >= btrfs_header_nritems(eb))
1932 		return 1;
1933 
1934 	return 0;
1935 }
1936 
1937 /*
1938  * Helper function to trace a subtree tree block swap.
1939  *
1940  * The swap will happen in highest tree block, but there may be a lot of
1941  * tree blocks involved.
1942  *
1943  * For example:
1944  *  OO = Old tree blocks
1945  *  NN = New tree blocks allocated during balance
1946  *
1947  *           File tree (257)                  Reloc tree for 257
1948  * L2              OO                                NN
1949  *               /    \                            /    \
1950  * L1          OO      OO (a)                    OO      NN (a)
1951  *            / \     / \                       / \     / \
1952  * L0       OO   OO OO   OO                   OO   OO NN   NN
1953  *                  (b)  (c)                          (b)  (c)
1954  *
1955  * When calling qgroup_trace_extent_swap(), we will pass:
1956  * @src_eb = OO(a)
1957  * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
1958  * @dst_level = 0
1959  * @root_level = 1
1960  *
1961  * In that case, qgroup_trace_extent_swap() will search from OO(a) to
1962  * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
1963  *
1964  * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
1965  *
1966  * 1) Tree search from @src_eb
1967  *    It should acts as a simplified btrfs_search_slot().
1968  *    The key for search can be extracted from @dst_path->nodes[dst_level]
1969  *    (first key).
1970  *
1971  * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
1972  *    NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
1973  *    They should be marked during previous (@dst_level = 1) iteration.
1974  *
1975  * 3) Mark file extents in leaves dirty
1976  *    We don't have good way to pick out new file extents only.
1977  *    So we still follow the old method by scanning all file extents in
1978  *    the leave.
1979  *
1980  * This function can free us from keeping two paths, thus later we only need
1981  * to care about how to iterate all new tree blocks in reloc tree.
1982  */
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)1983 static int qgroup_trace_extent_swap(struct btrfs_trans_handle* trans,
1984 				    struct extent_buffer *src_eb,
1985 				    struct btrfs_path *dst_path,
1986 				    int dst_level, int root_level,
1987 				    bool trace_leaf)
1988 {
1989 	struct btrfs_key key;
1990 	struct btrfs_path *src_path;
1991 	struct btrfs_fs_info *fs_info = trans->fs_info;
1992 	u32 nodesize = fs_info->nodesize;
1993 	int cur_level = root_level;
1994 	int ret;
1995 
1996 	BUG_ON(dst_level > root_level);
1997 	/* Level mismatch */
1998 	if (btrfs_header_level(src_eb) != root_level)
1999 		return -EINVAL;
2000 
2001 	src_path = btrfs_alloc_path();
2002 	if (!src_path) {
2003 		ret = -ENOMEM;
2004 		goto out;
2005 	}
2006 
2007 	if (dst_level)
2008 		btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2009 	else
2010 		btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
2011 
2012 	/* For src_path */
2013 	atomic_inc(&src_eb->refs);
2014 	src_path->nodes[root_level] = src_eb;
2015 	src_path->slots[root_level] = dst_path->slots[root_level];
2016 	src_path->locks[root_level] = 0;
2017 
2018 	/* A simplified version of btrfs_search_slot() */
2019 	while (cur_level >= dst_level) {
2020 		struct btrfs_key src_key;
2021 		struct btrfs_key dst_key;
2022 
2023 		if (src_path->nodes[cur_level] == NULL) {
2024 			struct btrfs_key first_key;
2025 			struct extent_buffer *eb;
2026 			int parent_slot;
2027 			u64 child_gen;
2028 			u64 child_bytenr;
2029 
2030 			eb = src_path->nodes[cur_level + 1];
2031 			parent_slot = src_path->slots[cur_level + 1];
2032 			child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2033 			child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2034 			btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2035 
2036 			eb = read_tree_block(fs_info, child_bytenr, child_gen,
2037 					     cur_level, &first_key);
2038 			if (IS_ERR(eb)) {
2039 				ret = PTR_ERR(eb);
2040 				goto out;
2041 			} else if (!extent_buffer_uptodate(eb)) {
2042 				free_extent_buffer(eb);
2043 				ret = -EIO;
2044 				goto out;
2045 			}
2046 
2047 			src_path->nodes[cur_level] = eb;
2048 
2049 			btrfs_tree_read_lock(eb);
2050 			btrfs_set_lock_blocking_read(eb);
2051 			src_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
2052 		}
2053 
2054 		src_path->slots[cur_level] = dst_path->slots[cur_level];
2055 		if (cur_level) {
2056 			btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
2057 					&dst_key, dst_path->slots[cur_level]);
2058 			btrfs_node_key_to_cpu(src_path->nodes[cur_level],
2059 					&src_key, src_path->slots[cur_level]);
2060 		} else {
2061 			btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
2062 					&dst_key, dst_path->slots[cur_level]);
2063 			btrfs_item_key_to_cpu(src_path->nodes[cur_level],
2064 					&src_key, src_path->slots[cur_level]);
2065 		}
2066 		/* Content mismatch, something went wrong */
2067 		if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
2068 			ret = -ENOENT;
2069 			goto out;
2070 		}
2071 		cur_level--;
2072 	}
2073 
2074 	/*
2075 	 * Now both @dst_path and @src_path have been populated, record the tree
2076 	 * blocks for qgroup accounting.
2077 	 */
2078 	ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
2079 			nodesize, GFP_NOFS);
2080 	if (ret < 0)
2081 		goto out;
2082 	ret = btrfs_qgroup_trace_extent(trans,
2083 			dst_path->nodes[dst_level]->start,
2084 			nodesize, GFP_NOFS);
2085 	if (ret < 0)
2086 		goto out;
2087 
2088 	/* Record leaf file extents */
2089 	if (dst_level == 0 && trace_leaf) {
2090 		ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
2091 		if (ret < 0)
2092 			goto out;
2093 		ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
2094 	}
2095 out:
2096 	btrfs_free_path(src_path);
2097 	return ret;
2098 }
2099 
2100 /*
2101  * Helper function to do recursive generation-aware depth-first search, to
2102  * locate all new tree blocks in a subtree of reloc tree.
2103  *
2104  * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
2105  *         reloc tree
2106  * L2         NN (a)
2107  *          /    \
2108  * L1    OO        NN (b)
2109  *      /  \      /  \
2110  * L0  OO  OO    OO  NN
2111  *               (c) (d)
2112  * If we pass:
2113  * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
2114  * @cur_level = 1
2115  * @root_level = 1
2116  *
2117  * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
2118  * above tree blocks along with their counter parts in file tree.
2119  * While during search, old tree blocks OO(c) will be skipped as tree block swap
2120  * won't affect OO(c).
2121  */
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)2122 static int qgroup_trace_new_subtree_blocks(struct btrfs_trans_handle* trans,
2123 					   struct extent_buffer *src_eb,
2124 					   struct btrfs_path *dst_path,
2125 					   int cur_level, int root_level,
2126 					   u64 last_snapshot, bool trace_leaf)
2127 {
2128 	struct btrfs_fs_info *fs_info = trans->fs_info;
2129 	struct extent_buffer *eb;
2130 	bool need_cleanup = false;
2131 	int ret = 0;
2132 	int i;
2133 
2134 	/* Level sanity check */
2135 	if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL - 1 ||
2136 	    root_level < 0 || root_level >= BTRFS_MAX_LEVEL - 1 ||
2137 	    root_level < cur_level) {
2138 		btrfs_err_rl(fs_info,
2139 			"%s: bad levels, cur_level=%d root_level=%d",
2140 			__func__, cur_level, root_level);
2141 		return -EUCLEAN;
2142 	}
2143 
2144 	/* Read the tree block if needed */
2145 	if (dst_path->nodes[cur_level] == NULL) {
2146 		struct btrfs_key first_key;
2147 		int parent_slot;
2148 		u64 child_gen;
2149 		u64 child_bytenr;
2150 
2151 		/*
2152 		 * dst_path->nodes[root_level] must be initialized before
2153 		 * calling this function.
2154 		 */
2155 		if (cur_level == root_level) {
2156 			btrfs_err_rl(fs_info,
2157 	"%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
2158 				__func__, root_level, root_level, cur_level);
2159 			return -EUCLEAN;
2160 		}
2161 
2162 		/*
2163 		 * We need to get child blockptr/gen from parent before we can
2164 		 * read it.
2165 		  */
2166 		eb = dst_path->nodes[cur_level + 1];
2167 		parent_slot = dst_path->slots[cur_level + 1];
2168 		child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2169 		child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2170 		btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2171 
2172 		/* This node is old, no need to trace */
2173 		if (child_gen < last_snapshot)
2174 			goto out;
2175 
2176 		eb = read_tree_block(fs_info, child_bytenr, child_gen,
2177 				     cur_level, &first_key);
2178 		if (IS_ERR(eb)) {
2179 			ret = PTR_ERR(eb);
2180 			goto out;
2181 		} else if (!extent_buffer_uptodate(eb)) {
2182 			free_extent_buffer(eb);
2183 			ret = -EIO;
2184 			goto out;
2185 		}
2186 
2187 		dst_path->nodes[cur_level] = eb;
2188 		dst_path->slots[cur_level] = 0;
2189 
2190 		btrfs_tree_read_lock(eb);
2191 		btrfs_set_lock_blocking_read(eb);
2192 		dst_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
2193 		need_cleanup = true;
2194 	}
2195 
2196 	/* Now record this tree block and its counter part for qgroups */
2197 	ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
2198 				       root_level, trace_leaf);
2199 	if (ret < 0)
2200 		goto cleanup;
2201 
2202 	eb = dst_path->nodes[cur_level];
2203 
2204 	if (cur_level > 0) {
2205 		/* Iterate all child tree blocks */
2206 		for (i = 0; i < btrfs_header_nritems(eb); i++) {
2207 			/* Skip old tree blocks as they won't be swapped */
2208 			if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
2209 				continue;
2210 			dst_path->slots[cur_level] = i;
2211 
2212 			/* Recursive call (at most 7 times) */
2213 			ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
2214 					dst_path, cur_level - 1, root_level,
2215 					last_snapshot, trace_leaf);
2216 			if (ret < 0)
2217 				goto cleanup;
2218 		}
2219 	}
2220 
2221 cleanup:
2222 	if (need_cleanup) {
2223 		/* Clean up */
2224 		btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
2225 				     dst_path->locks[cur_level]);
2226 		free_extent_buffer(dst_path->nodes[cur_level]);
2227 		dst_path->nodes[cur_level] = NULL;
2228 		dst_path->slots[cur_level] = 0;
2229 		dst_path->locks[cur_level] = 0;
2230 	}
2231 out:
2232 	return ret;
2233 }
2234 
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)2235 static int qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
2236 				struct extent_buffer *src_eb,
2237 				struct extent_buffer *dst_eb,
2238 				u64 last_snapshot, bool trace_leaf)
2239 {
2240 	struct btrfs_fs_info *fs_info = trans->fs_info;
2241 	struct btrfs_path *dst_path = NULL;
2242 	int level;
2243 	int ret;
2244 
2245 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2246 		return 0;
2247 
2248 	/* Wrong parameter order */
2249 	if (btrfs_header_generation(src_eb) > btrfs_header_generation(dst_eb)) {
2250 		btrfs_err_rl(fs_info,
2251 		"%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
2252 			     btrfs_header_generation(src_eb),
2253 			     btrfs_header_generation(dst_eb));
2254 		return -EUCLEAN;
2255 	}
2256 
2257 	if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
2258 		ret = -EIO;
2259 		goto out;
2260 	}
2261 
2262 	level = btrfs_header_level(dst_eb);
2263 	dst_path = btrfs_alloc_path();
2264 	if (!dst_path) {
2265 		ret = -ENOMEM;
2266 		goto out;
2267 	}
2268 	/* For dst_path */
2269 	atomic_inc(&dst_eb->refs);
2270 	dst_path->nodes[level] = dst_eb;
2271 	dst_path->slots[level] = 0;
2272 	dst_path->locks[level] = 0;
2273 
2274 	/* Do the generation aware breadth-first search */
2275 	ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
2276 					      level, last_snapshot, trace_leaf);
2277 	if (ret < 0)
2278 		goto out;
2279 	ret = 0;
2280 
2281 out:
2282 	btrfs_free_path(dst_path);
2283 	if (ret < 0)
2284 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2285 	return ret;
2286 }
2287 
btrfs_qgroup_trace_subtree(struct btrfs_trans_handle * trans,struct extent_buffer * root_eb,u64 root_gen,int root_level)2288 int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
2289 			       struct extent_buffer *root_eb,
2290 			       u64 root_gen, int root_level)
2291 {
2292 	struct btrfs_fs_info *fs_info = trans->fs_info;
2293 	int ret = 0;
2294 	int level;
2295 	struct extent_buffer *eb = root_eb;
2296 	struct btrfs_path *path = NULL;
2297 
2298 	BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2299 	BUG_ON(root_eb == NULL);
2300 
2301 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2302 		return 0;
2303 
2304 	if (!extent_buffer_uptodate(root_eb)) {
2305 		ret = btrfs_read_buffer(root_eb, root_gen, root_level, NULL);
2306 		if (ret)
2307 			goto out;
2308 	}
2309 
2310 	if (root_level == 0) {
2311 		ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2312 		goto out;
2313 	}
2314 
2315 	path = btrfs_alloc_path();
2316 	if (!path)
2317 		return -ENOMEM;
2318 
2319 	/*
2320 	 * Walk down the tree.  Missing extent blocks are filled in as
2321 	 * we go. Metadata is accounted every time we read a new
2322 	 * extent block.
2323 	 *
2324 	 * When we reach a leaf, we account for file extent items in it,
2325 	 * walk back up the tree (adjusting slot pointers as we go)
2326 	 * and restart the search process.
2327 	 */
2328 	atomic_inc(&root_eb->refs);	/* For path */
2329 	path->nodes[root_level] = root_eb;
2330 	path->slots[root_level] = 0;
2331 	path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
2332 walk_down:
2333 	level = root_level;
2334 	while (level >= 0) {
2335 		if (path->nodes[level] == NULL) {
2336 			struct btrfs_key first_key;
2337 			int parent_slot;
2338 			u64 child_gen;
2339 			u64 child_bytenr;
2340 
2341 			/*
2342 			 * We need to get child blockptr/gen from parent before
2343 			 * we can read it.
2344 			  */
2345 			eb = path->nodes[level + 1];
2346 			parent_slot = path->slots[level + 1];
2347 			child_bytenr = btrfs_node_blockptr(eb, parent_slot);
2348 			child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2349 			btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2350 
2351 			eb = read_tree_block(fs_info, child_bytenr, child_gen,
2352 					     level, &first_key);
2353 			if (IS_ERR(eb)) {
2354 				ret = PTR_ERR(eb);
2355 				goto out;
2356 			} else if (!extent_buffer_uptodate(eb)) {
2357 				free_extent_buffer(eb);
2358 				ret = -EIO;
2359 				goto out;
2360 			}
2361 
2362 			path->nodes[level] = eb;
2363 			path->slots[level] = 0;
2364 
2365 			btrfs_tree_read_lock(eb);
2366 			btrfs_set_lock_blocking_read(eb);
2367 			path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
2368 
2369 			ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2370 							fs_info->nodesize,
2371 							GFP_NOFS);
2372 			if (ret)
2373 				goto out;
2374 		}
2375 
2376 		if (level == 0) {
2377 			ret = btrfs_qgroup_trace_leaf_items(trans,
2378 							    path->nodes[level]);
2379 			if (ret)
2380 				goto out;
2381 
2382 			/* Nonzero return here means we completed our search */
2383 			ret = adjust_slots_upwards(path, root_level);
2384 			if (ret)
2385 				break;
2386 
2387 			/* Restart search with new slots */
2388 			goto walk_down;
2389 		}
2390 
2391 		level--;
2392 	}
2393 
2394 	ret = 0;
2395 out:
2396 	btrfs_free_path(path);
2397 
2398 	return ret;
2399 }
2400 
2401 #define UPDATE_NEW	0
2402 #define UPDATE_OLD	1
2403 /*
2404  * Walk all of the roots that points to the bytenr and adjust their refcnts.
2405  */
qgroup_update_refcnt(struct btrfs_fs_info * fs_info,struct ulist * roots,struct ulist * tmp,struct ulist * qgroups,u64 seq,int update_old)2406 static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
2407 				struct ulist *roots, struct ulist *tmp,
2408 				struct ulist *qgroups, u64 seq, int update_old)
2409 {
2410 	struct ulist_node *unode;
2411 	struct ulist_iterator uiter;
2412 	struct ulist_node *tmp_unode;
2413 	struct ulist_iterator tmp_uiter;
2414 	struct btrfs_qgroup *qg;
2415 	int ret = 0;
2416 
2417 	if (!roots)
2418 		return 0;
2419 	ULIST_ITER_INIT(&uiter);
2420 	while ((unode = ulist_next(roots, &uiter))) {
2421 		qg = find_qgroup_rb(fs_info, unode->val);
2422 		if (!qg)
2423 			continue;
2424 
2425 		ulist_reinit(tmp);
2426 		ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2427 				GFP_ATOMIC);
2428 		if (ret < 0)
2429 			return ret;
2430 		ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2431 		if (ret < 0)
2432 			return ret;
2433 		ULIST_ITER_INIT(&tmp_uiter);
2434 		while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
2435 			struct btrfs_qgroup_list *glist;
2436 
2437 			qg = unode_aux_to_qgroup(tmp_unode);
2438 			if (update_old)
2439 				btrfs_qgroup_update_old_refcnt(qg, seq, 1);
2440 			else
2441 				btrfs_qgroup_update_new_refcnt(qg, seq, 1);
2442 			list_for_each_entry(glist, &qg->groups, next_group) {
2443 				ret = ulist_add(qgroups, glist->group->qgroupid,
2444 						qgroup_to_aux(glist->group),
2445 						GFP_ATOMIC);
2446 				if (ret < 0)
2447 					return ret;
2448 				ret = ulist_add(tmp, glist->group->qgroupid,
2449 						qgroup_to_aux(glist->group),
2450 						GFP_ATOMIC);
2451 				if (ret < 0)
2452 					return ret;
2453 			}
2454 		}
2455 	}
2456 	return 0;
2457 }
2458 
2459 /*
2460  * Update qgroup rfer/excl counters.
2461  * Rfer update is easy, codes can explain themselves.
2462  *
2463  * Excl update is tricky, the update is split into 2 parts.
2464  * Part 1: Possible exclusive <-> sharing detect:
2465  *	|	A	|	!A	|
2466  *  -------------------------------------
2467  *  B	|	*	|	-	|
2468  *  -------------------------------------
2469  *  !B	|	+	|	**	|
2470  *  -------------------------------------
2471  *
2472  * Conditions:
2473  * A:	cur_old_roots < nr_old_roots	(not exclusive before)
2474  * !A:	cur_old_roots == nr_old_roots	(possible exclusive before)
2475  * B:	cur_new_roots < nr_new_roots	(not exclusive now)
2476  * !B:	cur_new_roots == nr_new_roots	(possible exclusive now)
2477  *
2478  * Results:
2479  * +: Possible sharing -> exclusive	-: Possible exclusive -> sharing
2480  * *: Definitely not changed.		**: Possible unchanged.
2481  *
2482  * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
2483  *
2484  * To make the logic clear, we first use condition A and B to split
2485  * combination into 4 results.
2486  *
2487  * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
2488  * only on variant maybe 0.
2489  *
2490  * Lastly, check result **, since there are 2 variants maybe 0, split them
2491  * again(2x2).
2492  * But this time we don't need to consider other things, the codes and logic
2493  * is easy to understand now.
2494  */
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)2495 static int qgroup_update_counters(struct btrfs_fs_info *fs_info,
2496 				  struct ulist *qgroups,
2497 				  u64 nr_old_roots,
2498 				  u64 nr_new_roots,
2499 				  u64 num_bytes, u64 seq)
2500 {
2501 	struct ulist_node *unode;
2502 	struct ulist_iterator uiter;
2503 	struct btrfs_qgroup *qg;
2504 	u64 cur_new_count, cur_old_count;
2505 
2506 	ULIST_ITER_INIT(&uiter);
2507 	while ((unode = ulist_next(qgroups, &uiter))) {
2508 		bool dirty = false;
2509 
2510 		qg = unode_aux_to_qgroup(unode);
2511 		cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
2512 		cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);
2513 
2514 		trace_qgroup_update_counters(fs_info, qg, cur_old_count,
2515 					     cur_new_count);
2516 
2517 		/* Rfer update part */
2518 		if (cur_old_count == 0 && cur_new_count > 0) {
2519 			qg->rfer += num_bytes;
2520 			qg->rfer_cmpr += num_bytes;
2521 			dirty = true;
2522 		}
2523 		if (cur_old_count > 0 && cur_new_count == 0) {
2524 			qg->rfer -= num_bytes;
2525 			qg->rfer_cmpr -= num_bytes;
2526 			dirty = true;
2527 		}
2528 
2529 		/* Excl update part */
2530 		/* Exclusive/none -> shared case */
2531 		if (cur_old_count == nr_old_roots &&
2532 		    cur_new_count < nr_new_roots) {
2533 			/* Exclusive -> shared */
2534 			if (cur_old_count != 0) {
2535 				qg->excl -= num_bytes;
2536 				qg->excl_cmpr -= num_bytes;
2537 				dirty = true;
2538 			}
2539 		}
2540 
2541 		/* Shared -> exclusive/none case */
2542 		if (cur_old_count < nr_old_roots &&
2543 		    cur_new_count == nr_new_roots) {
2544 			/* Shared->exclusive */
2545 			if (cur_new_count != 0) {
2546 				qg->excl += num_bytes;
2547 				qg->excl_cmpr += num_bytes;
2548 				dirty = true;
2549 			}
2550 		}
2551 
2552 		/* Exclusive/none -> exclusive/none case */
2553 		if (cur_old_count == nr_old_roots &&
2554 		    cur_new_count == nr_new_roots) {
2555 			if (cur_old_count == 0) {
2556 				/* None -> exclusive/none */
2557 
2558 				if (cur_new_count != 0) {
2559 					/* None -> exclusive */
2560 					qg->excl += num_bytes;
2561 					qg->excl_cmpr += num_bytes;
2562 					dirty = true;
2563 				}
2564 				/* None -> none, nothing changed */
2565 			} else {
2566 				/* Exclusive -> exclusive/none */
2567 
2568 				if (cur_new_count == 0) {
2569 					/* Exclusive -> none */
2570 					qg->excl -= num_bytes;
2571 					qg->excl_cmpr -= num_bytes;
2572 					dirty = true;
2573 				}
2574 				/* Exclusive -> exclusive, nothing changed */
2575 			}
2576 		}
2577 
2578 		if (dirty)
2579 			qgroup_dirty(fs_info, qg);
2580 	}
2581 	return 0;
2582 }
2583 
2584 /*
2585  * Check if the @roots potentially is a list of fs tree roots
2586  *
2587  * Return 0 for definitely not a fs/subvol tree roots ulist
2588  * Return 1 for possible fs/subvol tree roots in the list (considering an empty
2589  *          one as well)
2590  */
maybe_fs_roots(struct ulist * roots)2591 static int maybe_fs_roots(struct ulist *roots)
2592 {
2593 	struct ulist_node *unode;
2594 	struct ulist_iterator uiter;
2595 
2596 	/* Empty one, still possible for fs roots */
2597 	if (!roots || roots->nnodes == 0)
2598 		return 1;
2599 
2600 	ULIST_ITER_INIT(&uiter);
2601 	unode = ulist_next(roots, &uiter);
2602 	if (!unode)
2603 		return 1;
2604 
2605 	/*
2606 	 * If it contains fs tree roots, then it must belong to fs/subvol
2607 	 * trees.
2608 	 * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
2609 	 */
2610 	return is_fstree(unode->val);
2611 }
2612 
btrfs_qgroup_account_extent(struct btrfs_trans_handle * trans,u64 bytenr,u64 num_bytes,struct ulist * old_roots,struct ulist * new_roots)2613 int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
2614 				u64 num_bytes, struct ulist *old_roots,
2615 				struct ulist *new_roots)
2616 {
2617 	struct btrfs_fs_info *fs_info = trans->fs_info;
2618 	struct ulist *qgroups = NULL;
2619 	struct ulist *tmp = NULL;
2620 	u64 seq;
2621 	u64 nr_new_roots = 0;
2622 	u64 nr_old_roots = 0;
2623 	int ret = 0;
2624 
2625 	/*
2626 	 * If quotas get disabled meanwhile, the resouces need to be freed and
2627 	 * we can't just exit here.
2628 	 */
2629 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2630 		goto out_free;
2631 
2632 	if (new_roots) {
2633 		if (!maybe_fs_roots(new_roots))
2634 			goto out_free;
2635 		nr_new_roots = new_roots->nnodes;
2636 	}
2637 	if (old_roots) {
2638 		if (!maybe_fs_roots(old_roots))
2639 			goto out_free;
2640 		nr_old_roots = old_roots->nnodes;
2641 	}
2642 
2643 	/* Quick exit, either not fs tree roots, or won't affect any qgroup */
2644 	if (nr_old_roots == 0 && nr_new_roots == 0)
2645 		goto out_free;
2646 
2647 	BUG_ON(!fs_info->quota_root);
2648 
2649 	trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
2650 					num_bytes, nr_old_roots, nr_new_roots);
2651 
2652 	qgroups = ulist_alloc(GFP_NOFS);
2653 	if (!qgroups) {
2654 		ret = -ENOMEM;
2655 		goto out_free;
2656 	}
2657 	tmp = ulist_alloc(GFP_NOFS);
2658 	if (!tmp) {
2659 		ret = -ENOMEM;
2660 		goto out_free;
2661 	}
2662 
2663 	mutex_lock(&fs_info->qgroup_rescan_lock);
2664 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
2665 		if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
2666 			mutex_unlock(&fs_info->qgroup_rescan_lock);
2667 			ret = 0;
2668 			goto out_free;
2669 		}
2670 	}
2671 	mutex_unlock(&fs_info->qgroup_rescan_lock);
2672 
2673 	spin_lock(&fs_info->qgroup_lock);
2674 	seq = fs_info->qgroup_seq;
2675 
2676 	/* Update old refcnts using old_roots */
2677 	ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
2678 				   UPDATE_OLD);
2679 	if (ret < 0)
2680 		goto out;
2681 
2682 	/* Update new refcnts using new_roots */
2683 	ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
2684 				   UPDATE_NEW);
2685 	if (ret < 0)
2686 		goto out;
2687 
2688 	qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
2689 			       num_bytes, seq);
2690 
2691 	/*
2692 	 * Bump qgroup_seq to avoid seq overlap
2693 	 */
2694 	fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
2695 out:
2696 	spin_unlock(&fs_info->qgroup_lock);
2697 out_free:
2698 	ulist_free(tmp);
2699 	ulist_free(qgroups);
2700 	ulist_free(old_roots);
2701 	ulist_free(new_roots);
2702 	return ret;
2703 }
2704 
btrfs_qgroup_account_extents(struct btrfs_trans_handle * trans)2705 int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2706 {
2707 	struct btrfs_fs_info *fs_info = trans->fs_info;
2708 	struct btrfs_qgroup_extent_record *record;
2709 	struct btrfs_delayed_ref_root *delayed_refs;
2710 	struct ulist *new_roots = NULL;
2711 	struct rb_node *node;
2712 	u64 num_dirty_extents = 0;
2713 	u64 qgroup_to_skip;
2714 	int ret = 0;
2715 
2716 	delayed_refs = &trans->transaction->delayed_refs;
2717 	qgroup_to_skip = delayed_refs->qgroup_to_skip;
2718 	while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
2719 		record = rb_entry(node, struct btrfs_qgroup_extent_record,
2720 				  node);
2721 
2722 		num_dirty_extents++;
2723 		trace_btrfs_qgroup_account_extents(fs_info, record);
2724 
2725 		if (!ret) {
2726 			/*
2727 			 * Old roots should be searched when inserting qgroup
2728 			 * extent record
2729 			 */
2730 			if (WARN_ON(!record->old_roots)) {
2731 				/* Search commit root to find old_roots */
2732 				ret = btrfs_find_all_roots(NULL, fs_info,
2733 						record->bytenr, 0,
2734 						&record->old_roots, false);
2735 				if (ret < 0)
2736 					goto cleanup;
2737 			}
2738 
2739 			/* Free the reserved data space */
2740 			btrfs_qgroup_free_refroot(fs_info,
2741 					record->data_rsv_refroot,
2742 					record->data_rsv,
2743 					BTRFS_QGROUP_RSV_DATA);
2744 			/*
2745 			 * Use SEQ_LAST as time_seq to do special search, which
2746 			 * doesn't lock tree or delayed_refs and search current
2747 			 * root. It's safe inside commit_transaction().
2748 			 */
2749 			ret = btrfs_find_all_roots(trans, fs_info,
2750 				record->bytenr, SEQ_LAST, &new_roots, false);
2751 			if (ret < 0)
2752 				goto cleanup;
2753 			if (qgroup_to_skip) {
2754 				ulist_del(new_roots, qgroup_to_skip, 0);
2755 				ulist_del(record->old_roots, qgroup_to_skip,
2756 					  0);
2757 			}
2758 			ret = btrfs_qgroup_account_extent(trans, record->bytenr,
2759 							  record->num_bytes,
2760 							  record->old_roots,
2761 							  new_roots);
2762 			record->old_roots = NULL;
2763 			new_roots = NULL;
2764 		}
2765 cleanup:
2766 		ulist_free(record->old_roots);
2767 		ulist_free(new_roots);
2768 		new_roots = NULL;
2769 		rb_erase(node, &delayed_refs->dirty_extent_root);
2770 		kfree(record);
2771 
2772 	}
2773 	trace_qgroup_num_dirty_extents(fs_info, trans->transid,
2774 				       num_dirty_extents);
2775 	return ret;
2776 }
2777 
2778 /*
2779  * Writes all changed qgroups to disk.
2780  * Called by the transaction commit path and the qgroup assign ioctl.
2781  */
btrfs_run_qgroups(struct btrfs_trans_handle * trans)2782 int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2783 {
2784 	struct btrfs_fs_info *fs_info = trans->fs_info;
2785 	int ret = 0;
2786 
2787 	/*
2788 	 * In case we are called from the qgroup assign ioctl, assert that we
2789 	 * are holding the qgroup_ioctl_lock, otherwise we can race with a quota
2790 	 * disable operation (ioctl) and access a freed quota root.
2791 	 */
2792 	if (trans->transaction->state != TRANS_STATE_COMMIT_DOING)
2793 		lockdep_assert_held(&fs_info->qgroup_ioctl_lock);
2794 
2795 	if (!fs_info->quota_root)
2796 		return ret;
2797 
2798 	spin_lock(&fs_info->qgroup_lock);
2799 	while (!list_empty(&fs_info->dirty_qgroups)) {
2800 		struct btrfs_qgroup *qgroup;
2801 		qgroup = list_first_entry(&fs_info->dirty_qgroups,
2802 					  struct btrfs_qgroup, dirty);
2803 		list_del_init(&qgroup->dirty);
2804 		spin_unlock(&fs_info->qgroup_lock);
2805 		ret = update_qgroup_info_item(trans, qgroup);
2806 		if (ret)
2807 			fs_info->qgroup_flags |=
2808 					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2809 		ret = update_qgroup_limit_item(trans, qgroup);
2810 		if (ret)
2811 			fs_info->qgroup_flags |=
2812 					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2813 		spin_lock(&fs_info->qgroup_lock);
2814 	}
2815 	if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2816 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
2817 	else
2818 		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
2819 	spin_unlock(&fs_info->qgroup_lock);
2820 
2821 	ret = update_qgroup_status_item(trans);
2822 	if (ret)
2823 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2824 
2825 	return ret;
2826 }
2827 
2828 /*
2829  * Copy the accounting information between qgroups. This is necessary
2830  * when a snapshot or a subvolume is created. Throwing an error will
2831  * cause a transaction abort so we take extra care here to only error
2832  * when a readonly fs is a reasonable outcome.
2833  */
btrfs_qgroup_inherit(struct btrfs_trans_handle * trans,u64 srcid,u64 objectid,struct btrfs_qgroup_inherit * inherit)2834 int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
2835 			 u64 objectid, struct btrfs_qgroup_inherit *inherit)
2836 {
2837 	int ret = 0;
2838 	int i;
2839 	u64 *i_qgroups;
2840 	bool committing = false;
2841 	struct btrfs_fs_info *fs_info = trans->fs_info;
2842 	struct btrfs_root *quota_root;
2843 	struct btrfs_qgroup *srcgroup;
2844 	struct btrfs_qgroup *dstgroup;
2845 	bool need_rescan = false;
2846 	u32 level_size = 0;
2847 	u64 nums;
2848 
2849 	/*
2850 	 * There are only two callers of this function.
2851 	 *
2852 	 * One in create_subvol() in the ioctl context, which needs to hold
2853 	 * the qgroup_ioctl_lock.
2854 	 *
2855 	 * The other one in create_pending_snapshot() where no other qgroup
2856 	 * code can modify the fs as they all need to either start a new trans
2857 	 * or hold a trans handler, thus we don't need to hold
2858 	 * qgroup_ioctl_lock.
2859 	 * This would avoid long and complex lock chain and make lockdep happy.
2860 	 */
2861 	spin_lock(&fs_info->trans_lock);
2862 	if (trans->transaction->state == TRANS_STATE_COMMIT_DOING)
2863 		committing = true;
2864 	spin_unlock(&fs_info->trans_lock);
2865 
2866 	if (!committing)
2867 		mutex_lock(&fs_info->qgroup_ioctl_lock);
2868 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2869 		goto out;
2870 
2871 	quota_root = fs_info->quota_root;
2872 	if (!quota_root) {
2873 		ret = -EINVAL;
2874 		goto out;
2875 	}
2876 
2877 	if (inherit) {
2878 		i_qgroups = (u64 *)(inherit + 1);
2879 		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
2880 		       2 * inherit->num_excl_copies;
2881 		for (i = 0; i < nums; ++i) {
2882 			srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2883 
2884 			/*
2885 			 * Zero out invalid groups so we can ignore
2886 			 * them later.
2887 			 */
2888 			if (!srcgroup ||
2889 			    ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
2890 				*i_qgroups = 0ULL;
2891 
2892 			++i_qgroups;
2893 		}
2894 	}
2895 
2896 	/*
2897 	 * create a tracking group for the subvol itself
2898 	 */
2899 	ret = add_qgroup_item(trans, quota_root, objectid);
2900 	if (ret)
2901 		goto out;
2902 
2903 	/*
2904 	 * add qgroup to all inherited groups
2905 	 */
2906 	if (inherit) {
2907 		i_qgroups = (u64 *)(inherit + 1);
2908 		for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
2909 			if (*i_qgroups == 0)
2910 				continue;
2911 			ret = add_qgroup_relation_item(trans, objectid,
2912 						       *i_qgroups);
2913 			if (ret && ret != -EEXIST)
2914 				goto out;
2915 			ret = add_qgroup_relation_item(trans, *i_qgroups,
2916 						       objectid);
2917 			if (ret && ret != -EEXIST)
2918 				goto out;
2919 		}
2920 		ret = 0;
2921 	}
2922 
2923 
2924 	spin_lock(&fs_info->qgroup_lock);
2925 
2926 	dstgroup = add_qgroup_rb(fs_info, objectid);
2927 	if (IS_ERR(dstgroup)) {
2928 		ret = PTR_ERR(dstgroup);
2929 		goto unlock;
2930 	}
2931 
2932 	if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
2933 		dstgroup->lim_flags = inherit->lim.flags;
2934 		dstgroup->max_rfer = inherit->lim.max_rfer;
2935 		dstgroup->max_excl = inherit->lim.max_excl;
2936 		dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
2937 		dstgroup->rsv_excl = inherit->lim.rsv_excl;
2938 
2939 		qgroup_dirty(fs_info, dstgroup);
2940 	}
2941 
2942 	if (srcid) {
2943 		srcgroup = find_qgroup_rb(fs_info, srcid);
2944 		if (!srcgroup)
2945 			goto unlock;
2946 
2947 		/*
2948 		 * We call inherit after we clone the root in order to make sure
2949 		 * our counts don't go crazy, so at this point the only
2950 		 * difference between the two roots should be the root node.
2951 		 */
2952 		level_size = fs_info->nodesize;
2953 		dstgroup->rfer = srcgroup->rfer;
2954 		dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
2955 		dstgroup->excl = level_size;
2956 		dstgroup->excl_cmpr = level_size;
2957 		srcgroup->excl = level_size;
2958 		srcgroup->excl_cmpr = level_size;
2959 
2960 		/* inherit the limit info */
2961 		dstgroup->lim_flags = srcgroup->lim_flags;
2962 		dstgroup->max_rfer = srcgroup->max_rfer;
2963 		dstgroup->max_excl = srcgroup->max_excl;
2964 		dstgroup->rsv_rfer = srcgroup->rsv_rfer;
2965 		dstgroup->rsv_excl = srcgroup->rsv_excl;
2966 
2967 		qgroup_dirty(fs_info, dstgroup);
2968 		qgroup_dirty(fs_info, srcgroup);
2969 	}
2970 
2971 	if (!inherit)
2972 		goto unlock;
2973 
2974 	i_qgroups = (u64 *)(inherit + 1);
2975 	for (i = 0; i < inherit->num_qgroups; ++i) {
2976 		if (*i_qgroups) {
2977 			ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2978 			if (ret)
2979 				goto unlock;
2980 		}
2981 		++i_qgroups;
2982 
2983 		/*
2984 		 * If we're doing a snapshot, and adding the snapshot to a new
2985 		 * qgroup, the numbers are guaranteed to be incorrect.
2986 		 */
2987 		if (srcid)
2988 			need_rescan = true;
2989 	}
2990 
2991 	for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
2992 		struct btrfs_qgroup *src;
2993 		struct btrfs_qgroup *dst;
2994 
2995 		if (!i_qgroups[0] || !i_qgroups[1])
2996 			continue;
2997 
2998 		src = find_qgroup_rb(fs_info, i_qgroups[0]);
2999 		dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3000 
3001 		if (!src || !dst) {
3002 			ret = -EINVAL;
3003 			goto unlock;
3004 		}
3005 
3006 		dst->rfer = src->rfer - level_size;
3007 		dst->rfer_cmpr = src->rfer_cmpr - level_size;
3008 
3009 		/* Manually tweaking numbers certainly needs a rescan */
3010 		need_rescan = true;
3011 	}
3012 	for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
3013 		struct btrfs_qgroup *src;
3014 		struct btrfs_qgroup *dst;
3015 
3016 		if (!i_qgroups[0] || !i_qgroups[1])
3017 			continue;
3018 
3019 		src = find_qgroup_rb(fs_info, i_qgroups[0]);
3020 		dst = find_qgroup_rb(fs_info, i_qgroups[1]);
3021 
3022 		if (!src || !dst) {
3023 			ret = -EINVAL;
3024 			goto unlock;
3025 		}
3026 
3027 		dst->excl = src->excl + level_size;
3028 		dst->excl_cmpr = src->excl_cmpr + level_size;
3029 		need_rescan = true;
3030 	}
3031 
3032 unlock:
3033 	spin_unlock(&fs_info->qgroup_lock);
3034 	if (!ret)
3035 		ret = btrfs_sysfs_add_one_qgroup(fs_info, dstgroup);
3036 out:
3037 	if (!committing)
3038 		mutex_unlock(&fs_info->qgroup_ioctl_lock);
3039 	if (need_rescan)
3040 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3041 	return ret;
3042 }
3043 
qgroup_check_limits(const struct btrfs_qgroup * qg,u64 num_bytes)3044 static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
3045 {
3046 	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
3047 	    qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
3048 		return false;
3049 
3050 	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
3051 	    qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
3052 		return false;
3053 
3054 	return true;
3055 }
3056 
qgroup_reserve(struct btrfs_root * root,u64 num_bytes,bool enforce,enum btrfs_qgroup_rsv_type type)3057 static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
3058 			  enum btrfs_qgroup_rsv_type type)
3059 {
3060 	struct btrfs_qgroup *qgroup;
3061 	struct btrfs_fs_info *fs_info = root->fs_info;
3062 	u64 ref_root = root->root_key.objectid;
3063 	int ret = 0;
3064 	struct ulist_node *unode;
3065 	struct ulist_iterator uiter;
3066 
3067 	if (!is_fstree(ref_root))
3068 		return 0;
3069 
3070 	if (num_bytes == 0)
3071 		return 0;
3072 
3073 	if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
3074 	    capable(CAP_SYS_RESOURCE))
3075 		enforce = false;
3076 
3077 	spin_lock(&fs_info->qgroup_lock);
3078 	if (!fs_info->quota_root)
3079 		goto out;
3080 
3081 	qgroup = find_qgroup_rb(fs_info, ref_root);
3082 	if (!qgroup)
3083 		goto out;
3084 
3085 	/*
3086 	 * in a first step, we check all affected qgroups if any limits would
3087 	 * be exceeded
3088 	 */
3089 	ulist_reinit(fs_info->qgroup_ulist);
3090 	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3091 			qgroup_to_aux(qgroup), GFP_ATOMIC);
3092 	if (ret < 0)
3093 		goto out;
3094 	ULIST_ITER_INIT(&uiter);
3095 	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3096 		struct btrfs_qgroup *qg;
3097 		struct btrfs_qgroup_list *glist;
3098 
3099 		qg = unode_aux_to_qgroup(unode);
3100 
3101 		if (enforce && !qgroup_check_limits(qg, num_bytes)) {
3102 			ret = -EDQUOT;
3103 			goto out;
3104 		}
3105 
3106 		list_for_each_entry(glist, &qg->groups, next_group) {
3107 			ret = ulist_add(fs_info->qgroup_ulist,
3108 					glist->group->qgroupid,
3109 					qgroup_to_aux(glist->group), GFP_ATOMIC);
3110 			if (ret < 0)
3111 				goto out;
3112 		}
3113 	}
3114 	ret = 0;
3115 	/*
3116 	 * no limits exceeded, now record the reservation into all qgroups
3117 	 */
3118 	ULIST_ITER_INIT(&uiter);
3119 	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3120 		struct btrfs_qgroup *qg;
3121 
3122 		qg = unode_aux_to_qgroup(unode);
3123 
3124 		qgroup_rsv_add(fs_info, qg, num_bytes, type);
3125 	}
3126 
3127 out:
3128 	spin_unlock(&fs_info->qgroup_lock);
3129 	return ret;
3130 }
3131 
3132 /*
3133  * Free @num_bytes of reserved space with @type for qgroup.  (Normally level 0
3134  * qgroup).
3135  *
3136  * Will handle all higher level qgroup too.
3137  *
3138  * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
3139  * This special case is only used for META_PERTRANS type.
3140  */
btrfs_qgroup_free_refroot(struct btrfs_fs_info * fs_info,u64 ref_root,u64 num_bytes,enum btrfs_qgroup_rsv_type type)3141 void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
3142 			       u64 ref_root, u64 num_bytes,
3143 			       enum btrfs_qgroup_rsv_type type)
3144 {
3145 	struct btrfs_qgroup *qgroup;
3146 	struct ulist_node *unode;
3147 	struct ulist_iterator uiter;
3148 	int ret = 0;
3149 
3150 	if (!is_fstree(ref_root))
3151 		return;
3152 
3153 	if (num_bytes == 0)
3154 		return;
3155 
3156 	if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
3157 		WARN(1, "%s: Invalid type to free", __func__);
3158 		return;
3159 	}
3160 	spin_lock(&fs_info->qgroup_lock);
3161 
3162 	if (!fs_info->quota_root)
3163 		goto out;
3164 
3165 	qgroup = find_qgroup_rb(fs_info, ref_root);
3166 	if (!qgroup)
3167 		goto out;
3168 
3169 	if (num_bytes == (u64)-1)
3170 		/*
3171 		 * We're freeing all pertrans rsv, get reserved value from
3172 		 * level 0 qgroup as real num_bytes to free.
3173 		 */
3174 		num_bytes = qgroup->rsv.values[type];
3175 
3176 	ulist_reinit(fs_info->qgroup_ulist);
3177 	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3178 			qgroup_to_aux(qgroup), GFP_ATOMIC);
3179 	if (ret < 0)
3180 		goto out;
3181 	ULIST_ITER_INIT(&uiter);
3182 	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3183 		struct btrfs_qgroup *qg;
3184 		struct btrfs_qgroup_list *glist;
3185 
3186 		qg = unode_aux_to_qgroup(unode);
3187 
3188 		qgroup_rsv_release(fs_info, qg, num_bytes, type);
3189 
3190 		list_for_each_entry(glist, &qg->groups, next_group) {
3191 			ret = ulist_add(fs_info->qgroup_ulist,
3192 					glist->group->qgroupid,
3193 					qgroup_to_aux(glist->group), GFP_ATOMIC);
3194 			if (ret < 0)
3195 				goto out;
3196 		}
3197 	}
3198 
3199 out:
3200 	spin_unlock(&fs_info->qgroup_lock);
3201 }
3202 
3203 /*
3204  * Check if the leaf is the last leaf. Which means all node pointers
3205  * are at their last position.
3206  */
is_last_leaf(struct btrfs_path * path)3207 static bool is_last_leaf(struct btrfs_path *path)
3208 {
3209 	int i;
3210 
3211 	for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
3212 		if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
3213 			return false;
3214 	}
3215 	return true;
3216 }
3217 
3218 /*
3219  * returns < 0 on error, 0 when more leafs are to be scanned.
3220  * returns 1 when done.
3221  */
qgroup_rescan_leaf(struct btrfs_trans_handle * trans,struct btrfs_path * path)3222 static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
3223 			      struct btrfs_path *path)
3224 {
3225 	struct btrfs_fs_info *fs_info = trans->fs_info;
3226 	struct btrfs_key found;
3227 	struct extent_buffer *scratch_leaf = NULL;
3228 	struct ulist *roots = NULL;
3229 	u64 num_bytes;
3230 	bool done;
3231 	int slot;
3232 	int ret;
3233 
3234 	mutex_lock(&fs_info->qgroup_rescan_lock);
3235 	ret = btrfs_search_slot_for_read(fs_info->extent_root,
3236 					 &fs_info->qgroup_rescan_progress,
3237 					 path, 1, 0);
3238 
3239 	btrfs_debug(fs_info,
3240 		"current progress key (%llu %u %llu), search_slot ret %d",
3241 		fs_info->qgroup_rescan_progress.objectid,
3242 		fs_info->qgroup_rescan_progress.type,
3243 		fs_info->qgroup_rescan_progress.offset, ret);
3244 
3245 	if (ret) {
3246 		/*
3247 		 * The rescan is about to end, we will not be scanning any
3248 		 * further blocks. We cannot unset the RESCAN flag here, because
3249 		 * we want to commit the transaction if everything went well.
3250 		 * To make the live accounting work in this phase, we set our
3251 		 * scan progress pointer such that every real extent objectid
3252 		 * will be smaller.
3253 		 */
3254 		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3255 		btrfs_release_path(path);
3256 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3257 		return ret;
3258 	}
3259 	done = is_last_leaf(path);
3260 
3261 	btrfs_item_key_to_cpu(path->nodes[0], &found,
3262 			      btrfs_header_nritems(path->nodes[0]) - 1);
3263 	fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;
3264 
3265 	scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
3266 	if (!scratch_leaf) {
3267 		ret = -ENOMEM;
3268 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3269 		goto out;
3270 	}
3271 	slot = path->slots[0];
3272 	btrfs_release_path(path);
3273 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3274 
3275 	for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
3276 		btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3277 		if (found.type != BTRFS_EXTENT_ITEM_KEY &&
3278 		    found.type != BTRFS_METADATA_ITEM_KEY)
3279 			continue;
3280 		if (found.type == BTRFS_METADATA_ITEM_KEY)
3281 			num_bytes = fs_info->nodesize;
3282 		else
3283 			num_bytes = found.offset;
3284 
3285 		ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3286 					   &roots, false);
3287 		if (ret < 0)
3288 			goto out;
3289 		/* For rescan, just pass old_roots as NULL */
3290 		ret = btrfs_qgroup_account_extent(trans, found.objectid,
3291 						  num_bytes, NULL, roots);
3292 		if (ret < 0)
3293 			goto out;
3294 	}
3295 out:
3296 	if (scratch_leaf)
3297 		free_extent_buffer(scratch_leaf);
3298 
3299 	if (done && !ret) {
3300 		ret = 1;
3301 		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
3302 	}
3303 	return ret;
3304 }
3305 
rescan_should_stop(struct btrfs_fs_info * fs_info)3306 static bool rescan_should_stop(struct btrfs_fs_info *fs_info)
3307 {
3308 	return btrfs_fs_closing(fs_info) ||
3309 		test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state) ||
3310 		!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
3311 }
3312 
btrfs_qgroup_rescan_worker(struct btrfs_work * work)3313 static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
3314 {
3315 	struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
3316 						     qgroup_rescan_work);
3317 	struct btrfs_path *path;
3318 	struct btrfs_trans_handle *trans = NULL;
3319 	int err = -ENOMEM;
3320 	int ret = 0;
3321 	bool stopped = false;
3322 	bool did_leaf_rescans = false;
3323 
3324 	path = btrfs_alloc_path();
3325 	if (!path)
3326 		goto out;
3327 	/*
3328 	 * Rescan should only search for commit root, and any later difference
3329 	 * should be recorded by qgroup
3330 	 */
3331 	path->search_commit_root = 1;
3332 	path->skip_locking = 1;
3333 
3334 	err = 0;
3335 	while (!err && !(stopped = rescan_should_stop(fs_info))) {
3336 		trans = btrfs_start_transaction(fs_info->fs_root, 0);
3337 		if (IS_ERR(trans)) {
3338 			err = PTR_ERR(trans);
3339 			break;
3340 		}
3341 
3342 		err = qgroup_rescan_leaf(trans, path);
3343 		did_leaf_rescans = true;
3344 
3345 		if (err > 0)
3346 			btrfs_commit_transaction(trans);
3347 		else
3348 			btrfs_end_transaction(trans);
3349 	}
3350 
3351 out:
3352 	btrfs_free_path(path);
3353 
3354 	mutex_lock(&fs_info->qgroup_rescan_lock);
3355 	if (err > 0 &&
3356 	    fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
3357 		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3358 	} else if (err < 0 || stopped) {
3359 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
3360 	}
3361 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3362 
3363 	/*
3364 	 * Only update status, since the previous part has already updated the
3365 	 * qgroup info, and only if we did any actual work. This also prevents
3366 	 * race with a concurrent quota disable, which has already set
3367 	 * fs_info->quota_root to NULL and cleared BTRFS_FS_QUOTA_ENABLED at
3368 	 * btrfs_quota_disable().
3369 	 */
3370 	if (did_leaf_rescans) {
3371 		trans = btrfs_start_transaction(fs_info->quota_root, 1);
3372 		if (IS_ERR(trans)) {
3373 			err = PTR_ERR(trans);
3374 			trans = NULL;
3375 			btrfs_err(fs_info,
3376 				  "fail to start transaction for status update: %d",
3377 				  err);
3378 		}
3379 	} else {
3380 		trans = NULL;
3381 	}
3382 
3383 	mutex_lock(&fs_info->qgroup_rescan_lock);
3384 	if (!stopped)
3385 		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3386 	if (trans) {
3387 		ret = update_qgroup_status_item(trans);
3388 		if (ret < 0) {
3389 			err = ret;
3390 			btrfs_err(fs_info, "fail to update qgroup status: %d",
3391 				  err);
3392 		}
3393 	}
3394 	fs_info->qgroup_rescan_running = false;
3395 	complete_all(&fs_info->qgroup_rescan_completion);
3396 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3397 
3398 	if (!trans)
3399 		return;
3400 
3401 	btrfs_end_transaction(trans);
3402 
3403 	if (stopped) {
3404 		btrfs_info(fs_info, "qgroup scan paused");
3405 	} else if (err >= 0) {
3406 		btrfs_info(fs_info, "qgroup scan completed%s",
3407 			err > 0 ? " (inconsistency flag cleared)" : "");
3408 	} else {
3409 		btrfs_err(fs_info, "qgroup scan failed with %d", err);
3410 	}
3411 }
3412 
3413 /*
3414  * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
3415  * memory required for the rescan context.
3416  */
3417 static int
qgroup_rescan_init(struct btrfs_fs_info * fs_info,u64 progress_objectid,int init_flags)3418 qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
3419 		   int init_flags)
3420 {
3421 	int ret = 0;
3422 
3423 	if (!init_flags) {
3424 		/* we're resuming qgroup rescan at mount time */
3425 		if (!(fs_info->qgroup_flags &
3426 		      BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3427 			btrfs_warn(fs_info,
3428 			"qgroup rescan init failed, qgroup rescan is not queued");
3429 			ret = -EINVAL;
3430 		} else if (!(fs_info->qgroup_flags &
3431 			     BTRFS_QGROUP_STATUS_FLAG_ON)) {
3432 			btrfs_warn(fs_info,
3433 			"qgroup rescan init failed, qgroup is not enabled");
3434 			ret = -EINVAL;
3435 		}
3436 
3437 		if (ret)
3438 			return ret;
3439 	}
3440 
3441 	mutex_lock(&fs_info->qgroup_rescan_lock);
3442 
3443 	if (init_flags) {
3444 		if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3445 			btrfs_warn(fs_info,
3446 				   "qgroup rescan is already in progress");
3447 			ret = -EINPROGRESS;
3448 		} else if (!(fs_info->qgroup_flags &
3449 			     BTRFS_QGROUP_STATUS_FLAG_ON)) {
3450 			btrfs_warn(fs_info,
3451 			"qgroup rescan init failed, qgroup is not enabled");
3452 			ret = -EINVAL;
3453 		} else if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
3454 			/* Quota disable is in progress */
3455 			ret = -EBUSY;
3456 		}
3457 
3458 		if (ret) {
3459 			mutex_unlock(&fs_info->qgroup_rescan_lock);
3460 			return ret;
3461 		}
3462 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3463 	}
3464 
3465 	memset(&fs_info->qgroup_rescan_progress, 0,
3466 		sizeof(fs_info->qgroup_rescan_progress));
3467 	fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3468 	init_completion(&fs_info->qgroup_rescan_completion);
3469 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3470 
3471 	btrfs_init_work(&fs_info->qgroup_rescan_work,
3472 			btrfs_qgroup_rescan_worker, NULL, NULL);
3473 	return 0;
3474 }
3475 
3476 static void
qgroup_rescan_zero_tracking(struct btrfs_fs_info * fs_info)3477 qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
3478 {
3479 	struct rb_node *n;
3480 	struct btrfs_qgroup *qgroup;
3481 
3482 	spin_lock(&fs_info->qgroup_lock);
3483 	/* clear all current qgroup tracking information */
3484 	for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
3485 		qgroup = rb_entry(n, struct btrfs_qgroup, node);
3486 		qgroup->rfer = 0;
3487 		qgroup->rfer_cmpr = 0;
3488 		qgroup->excl = 0;
3489 		qgroup->excl_cmpr = 0;
3490 		qgroup_dirty(fs_info, qgroup);
3491 	}
3492 	spin_unlock(&fs_info->qgroup_lock);
3493 }
3494 
3495 int
btrfs_qgroup_rescan(struct btrfs_fs_info * fs_info)3496 btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
3497 {
3498 	int ret = 0;
3499 	struct btrfs_trans_handle *trans;
3500 
3501 	ret = qgroup_rescan_init(fs_info, 0, 1);
3502 	if (ret)
3503 		return ret;
3504 
3505 	/*
3506 	 * We have set the rescan_progress to 0, which means no more
3507 	 * delayed refs will be accounted by btrfs_qgroup_account_ref.
3508 	 * However, btrfs_qgroup_account_ref may be right after its call
3509 	 * to btrfs_find_all_roots, in which case it would still do the
3510 	 * accounting.
3511 	 * To solve this, we're committing the transaction, which will
3512 	 * ensure we run all delayed refs and only after that, we are
3513 	 * going to clear all tracking information for a clean start.
3514 	 */
3515 
3516 	trans = btrfs_join_transaction(fs_info->fs_root);
3517 	if (IS_ERR(trans)) {
3518 		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3519 		return PTR_ERR(trans);
3520 	}
3521 	ret = btrfs_commit_transaction(trans);
3522 	if (ret) {
3523 		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
3524 		return ret;
3525 	}
3526 
3527 	qgroup_rescan_zero_tracking(fs_info);
3528 
3529 	mutex_lock(&fs_info->qgroup_rescan_lock);
3530 	fs_info->qgroup_rescan_running = true;
3531 	btrfs_queue_work(fs_info->qgroup_rescan_workers,
3532 			 &fs_info->qgroup_rescan_work);
3533 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3534 
3535 	return 0;
3536 }
3537 
btrfs_qgroup_wait_for_completion(struct btrfs_fs_info * fs_info,bool interruptible)3538 int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
3539 				     bool interruptible)
3540 {
3541 	int running;
3542 	int ret = 0;
3543 
3544 	mutex_lock(&fs_info->qgroup_rescan_lock);
3545 	running = fs_info->qgroup_rescan_running;
3546 	mutex_unlock(&fs_info->qgroup_rescan_lock);
3547 
3548 	if (!running)
3549 		return 0;
3550 
3551 	if (interruptible)
3552 		ret = wait_for_completion_interruptible(
3553 					&fs_info->qgroup_rescan_completion);
3554 	else
3555 		wait_for_completion(&fs_info->qgroup_rescan_completion);
3556 
3557 	return ret;
3558 }
3559 
3560 /*
3561  * this is only called from open_ctree where we're still single threaded, thus
3562  * locking is omitted here.
3563  */
3564 void
btrfs_qgroup_rescan_resume(struct btrfs_fs_info * fs_info)3565 btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
3566 {
3567 	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
3568 		mutex_lock(&fs_info->qgroup_rescan_lock);
3569 		fs_info->qgroup_rescan_running = true;
3570 		btrfs_queue_work(fs_info->qgroup_rescan_workers,
3571 				 &fs_info->qgroup_rescan_work);
3572 		mutex_unlock(&fs_info->qgroup_rescan_lock);
3573 	}
3574 }
3575 
3576 #define rbtree_iterate_from_safe(node, next, start)				\
3577        for (node = start; node && ({ next = rb_next(node); 1;}); node = next)
3578 
qgroup_unreserve_range(struct btrfs_inode * inode,struct extent_changeset * reserved,u64 start,u64 len)3579 static int qgroup_unreserve_range(struct btrfs_inode *inode,
3580 				  struct extent_changeset *reserved, u64 start,
3581 				  u64 len)
3582 {
3583 	struct rb_node *node;
3584 	struct rb_node *next;
3585 	struct ulist_node *entry;
3586 	int ret = 0;
3587 
3588 	node = reserved->range_changed.root.rb_node;
3589 	if (!node)
3590 		return 0;
3591 	while (node) {
3592 		entry = rb_entry(node, struct ulist_node, rb_node);
3593 		if (entry->val < start)
3594 			node = node->rb_right;
3595 		else
3596 			node = node->rb_left;
3597 	}
3598 
3599 	if (entry->val > start && rb_prev(&entry->rb_node))
3600 		entry = rb_entry(rb_prev(&entry->rb_node), struct ulist_node,
3601 				 rb_node);
3602 
3603 	rbtree_iterate_from_safe(node, next, &entry->rb_node) {
3604 		u64 entry_start;
3605 		u64 entry_end;
3606 		u64 entry_len;
3607 		int clear_ret;
3608 
3609 		entry = rb_entry(node, struct ulist_node, rb_node);
3610 		entry_start = entry->val;
3611 		entry_end = entry->aux;
3612 		entry_len = entry_end - entry_start + 1;
3613 
3614 		if (entry_start >= start + len)
3615 			break;
3616 		if (entry_start + entry_len <= start)
3617 			continue;
3618 		/*
3619 		 * Now the entry is in [start, start + len), revert the
3620 		 * EXTENT_QGROUP_RESERVED bit.
3621 		 */
3622 		clear_ret = clear_extent_bits(&inode->io_tree, entry_start,
3623 					      entry_end, EXTENT_QGROUP_RESERVED);
3624 		if (!ret && clear_ret < 0)
3625 			ret = clear_ret;
3626 
3627 		ulist_del(&reserved->range_changed, entry->val, entry->aux);
3628 		if (likely(reserved->bytes_changed >= entry_len)) {
3629 			reserved->bytes_changed -= entry_len;
3630 		} else {
3631 			WARN_ON(1);
3632 			reserved->bytes_changed = 0;
3633 		}
3634 	}
3635 
3636 	return ret;
3637 }
3638 
3639 /*
3640  * Try to free some space for qgroup.
3641  *
3642  * For qgroup, there are only 3 ways to free qgroup space:
3643  * - Flush nodatacow write
3644  *   Any nodatacow write will free its reserved data space at run_delalloc_range().
3645  *   In theory, we should only flush nodatacow inodes, but it's not yet
3646  *   possible, so we need to flush the whole root.
3647  *
3648  * - Wait for ordered extents
3649  *   When ordered extents are finished, their reserved metadata is finally
3650  *   converted to per_trans status, which can be freed by later commit
3651  *   transaction.
3652  *
3653  * - Commit transaction
3654  *   This would free the meta_per_trans space.
3655  *   In theory this shouldn't provide much space, but any more qgroup space
3656  *   is needed.
3657  */
try_flush_qgroup(struct btrfs_root * root)3658 static int try_flush_qgroup(struct btrfs_root *root)
3659 {
3660 	struct btrfs_trans_handle *trans;
3661 	int ret;
3662 	bool can_commit = true;
3663 
3664 	/*
3665 	 * If current process holds a transaction, we shouldn't flush, as we
3666 	 * assume all space reservation happens before a transaction handle is
3667 	 * held.
3668 	 *
3669 	 * But there are cases like btrfs_delayed_item_reserve_metadata() where
3670 	 * we try to reserve space with one transction handle already held.
3671 	 * In that case we can't commit transaction, but at least try to end it
3672 	 * and hope the started data writes can free some space.
3673 	 */
3674 	if (current->journal_info &&
3675 	    current->journal_info != BTRFS_SEND_TRANS_STUB)
3676 		can_commit = false;
3677 
3678 	/*
3679 	 * We don't want to run flush again and again, so if there is a running
3680 	 * one, we won't try to start a new flush, but exit directly.
3681 	 */
3682 	if (test_and_set_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state)) {
3683 		/*
3684 		 * We are already holding a transaction, thus we can block other
3685 		 * threads from flushing.  So exit right now. This increases
3686 		 * the chance of EDQUOT for heavy load and near limit cases.
3687 		 * But we can argue that if we're already near limit, EDQUOT is
3688 		 * unavoidable anyway.
3689 		 */
3690 		if (!can_commit)
3691 			return 0;
3692 
3693 		wait_event(root->qgroup_flush_wait,
3694 			!test_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state));
3695 		return 0;
3696 	}
3697 
3698 	ret = btrfs_start_delalloc_snapshot(root);
3699 	if (ret < 0)
3700 		goto out;
3701 	btrfs_wait_ordered_extents(root, U64_MAX, 0, (u64)-1);
3702 
3703 	trans = btrfs_join_transaction(root);
3704 	if (IS_ERR(trans)) {
3705 		ret = PTR_ERR(trans);
3706 		goto out;
3707 	}
3708 
3709 	if (can_commit)
3710 		ret = btrfs_commit_transaction(trans);
3711 	else
3712 		ret = btrfs_end_transaction(trans);
3713 out:
3714 	clear_bit(BTRFS_ROOT_QGROUP_FLUSHING, &root->state);
3715 	wake_up(&root->qgroup_flush_wait);
3716 	return ret;
3717 }
3718 
qgroup_reserve_data(struct btrfs_inode * inode,struct extent_changeset ** reserved_ret,u64 start,u64 len)3719 static int qgroup_reserve_data(struct btrfs_inode *inode,
3720 			struct extent_changeset **reserved_ret, u64 start,
3721 			u64 len)
3722 {
3723 	struct btrfs_root *root = inode->root;
3724 	struct extent_changeset *reserved;
3725 	bool new_reserved = false;
3726 	u64 orig_reserved;
3727 	u64 to_reserve;
3728 	int ret;
3729 
3730 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3731 	    !is_fstree(root->root_key.objectid) || len == 0)
3732 		return 0;
3733 
3734 	/* @reserved parameter is mandatory for qgroup */
3735 	if (WARN_ON(!reserved_ret))
3736 		return -EINVAL;
3737 	if (!*reserved_ret) {
3738 		new_reserved = true;
3739 		*reserved_ret = extent_changeset_alloc();
3740 		if (!*reserved_ret)
3741 			return -ENOMEM;
3742 	}
3743 	reserved = *reserved_ret;
3744 	/* Record already reserved space */
3745 	orig_reserved = reserved->bytes_changed;
3746 	ret = set_record_extent_bits(&inode->io_tree, start,
3747 			start + len -1, EXTENT_QGROUP_RESERVED, reserved);
3748 
3749 	/* Newly reserved space */
3750 	to_reserve = reserved->bytes_changed - orig_reserved;
3751 	trace_btrfs_qgroup_reserve_data(&inode->vfs_inode, start, len,
3752 					to_reserve, QGROUP_RESERVE);
3753 	if (ret < 0)
3754 		goto out;
3755 	ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3756 	if (ret < 0)
3757 		goto cleanup;
3758 
3759 	return ret;
3760 
3761 cleanup:
3762 	qgroup_unreserve_range(inode, reserved, start, len);
3763 out:
3764 	if (new_reserved) {
3765 		extent_changeset_release(reserved);
3766 		kfree(reserved);
3767 		*reserved_ret = NULL;
3768 	}
3769 	return ret;
3770 }
3771 
3772 /*
3773  * Reserve qgroup space for range [start, start + len).
3774  *
3775  * This function will either reserve space from related qgroups or do nothing
3776  * if the range is already reserved.
3777  *
3778  * Return 0 for successful reservation
3779  * Return <0 for error (including -EQUOT)
3780  *
3781  * NOTE: This function may sleep for memory allocation, dirty page flushing and
3782  *	 commit transaction. So caller should not hold any dirty page locked.
3783  */
btrfs_qgroup_reserve_data(struct btrfs_inode * inode,struct extent_changeset ** reserved_ret,u64 start,u64 len)3784 int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
3785 			struct extent_changeset **reserved_ret, u64 start,
3786 			u64 len)
3787 {
3788 	int ret;
3789 
3790 	ret = qgroup_reserve_data(inode, reserved_ret, start, len);
3791 	if (ret <= 0 && ret != -EDQUOT)
3792 		return ret;
3793 
3794 	ret = try_flush_qgroup(inode->root);
3795 	if (ret < 0)
3796 		return ret;
3797 	return qgroup_reserve_data(inode, reserved_ret, start, len);
3798 }
3799 
3800 /* 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)3801 static int qgroup_free_reserved_data(struct btrfs_inode *inode,
3802 			struct extent_changeset *reserved, u64 start, u64 len)
3803 {
3804 	struct btrfs_root *root = inode->root;
3805 	struct ulist_node *unode;
3806 	struct ulist_iterator uiter;
3807 	struct extent_changeset changeset;
3808 	int freed = 0;
3809 	int ret;
3810 
3811 	extent_changeset_init(&changeset);
3812 	len = round_up(start + len, root->fs_info->sectorsize);
3813 	start = round_down(start, root->fs_info->sectorsize);
3814 
3815 	ULIST_ITER_INIT(&uiter);
3816 	while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
3817 		u64 range_start = unode->val;
3818 		/* unode->aux is the inclusive end */
3819 		u64 range_len = unode->aux - range_start + 1;
3820 		u64 free_start;
3821 		u64 free_len;
3822 
3823 		extent_changeset_release(&changeset);
3824 
3825 		/* Only free range in range [start, start + len) */
3826 		if (range_start >= start + len ||
3827 		    range_start + range_len <= start)
3828 			continue;
3829 		free_start = max(range_start, start);
3830 		free_len = min(start + len, range_start + range_len) -
3831 			   free_start;
3832 		/*
3833 		 * TODO: To also modify reserved->ranges_reserved to reflect
3834 		 * the modification.
3835 		 *
3836 		 * However as long as we free qgroup reserved according to
3837 		 * EXTENT_QGROUP_RESERVED, we won't double free.
3838 		 * So not need to rush.
3839 		 */
3840 		ret = clear_record_extent_bits(&inode->io_tree, free_start,
3841 				free_start + free_len - 1,
3842 				EXTENT_QGROUP_RESERVED, &changeset);
3843 		if (ret < 0)
3844 			goto out;
3845 		freed += changeset.bytes_changed;
3846 	}
3847 	btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3848 				  BTRFS_QGROUP_RSV_DATA);
3849 	ret = freed;
3850 out:
3851 	extent_changeset_release(&changeset);
3852 	return ret;
3853 }
3854 
__btrfs_qgroup_release_data(struct btrfs_inode * inode,struct extent_changeset * reserved,u64 start,u64 len,int free)3855 static int __btrfs_qgroup_release_data(struct btrfs_inode *inode,
3856 			struct extent_changeset *reserved, u64 start, u64 len,
3857 			int free)
3858 {
3859 	struct extent_changeset changeset;
3860 	int trace_op = QGROUP_RELEASE;
3861 	int ret;
3862 
3863 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &inode->root->fs_info->flags))
3864 		return 0;
3865 
3866 	/* In release case, we shouldn't have @reserved */
3867 	WARN_ON(!free && reserved);
3868 	if (free && reserved)
3869 		return qgroup_free_reserved_data(inode, reserved, start, len);
3870 	extent_changeset_init(&changeset);
3871 	ret = clear_record_extent_bits(&inode->io_tree, start, start + len -1,
3872 				       EXTENT_QGROUP_RESERVED, &changeset);
3873 	if (ret < 0)
3874 		goto out;
3875 
3876 	if (free)
3877 		trace_op = QGROUP_FREE;
3878 	trace_btrfs_qgroup_release_data(&inode->vfs_inode, start, len,
3879 					changeset.bytes_changed, trace_op);
3880 	if (free)
3881 		btrfs_qgroup_free_refroot(inode->root->fs_info,
3882 				inode->root->root_key.objectid,
3883 				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3884 	ret = changeset.bytes_changed;
3885 out:
3886 	extent_changeset_release(&changeset);
3887 	return ret;
3888 }
3889 
3890 /*
3891  * Free a reserved space range from io_tree and related qgroups
3892  *
3893  * Should be called when a range of pages get invalidated before reaching disk.
3894  * Or for error cleanup case.
3895  * if @reserved is given, only reserved range in [@start, @start + @len) will
3896  * be freed.
3897  *
3898  * For data written to disk, use btrfs_qgroup_release_data().
3899  *
3900  * NOTE: This function may sleep for memory allocation.
3901  */
btrfs_qgroup_free_data(struct btrfs_inode * inode,struct extent_changeset * reserved,u64 start,u64 len)3902 int btrfs_qgroup_free_data(struct btrfs_inode *inode,
3903 			struct extent_changeset *reserved, u64 start, u64 len)
3904 {
3905 	return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3906 }
3907 
3908 /*
3909  * Release a reserved space range from io_tree only.
3910  *
3911  * Should be called when a range of pages get written to disk and corresponding
3912  * FILE_EXTENT is inserted into corresponding root.
3913  *
3914  * Since new qgroup accounting framework will only update qgroup numbers at
3915  * commit_transaction() time, its reserved space shouldn't be freed from
3916  * related qgroups.
3917  *
3918  * But we should release the range from io_tree, to allow further write to be
3919  * COWed.
3920  *
3921  * NOTE: This function may sleep for memory allocation.
3922  */
btrfs_qgroup_release_data(struct btrfs_inode * inode,u64 start,u64 len)3923 int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len)
3924 {
3925 	return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3926 }
3927 
add_root_meta_rsv(struct btrfs_root * root,int num_bytes,enum btrfs_qgroup_rsv_type type)3928 static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3929 			      enum btrfs_qgroup_rsv_type type)
3930 {
3931 	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3932 	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
3933 		return;
3934 	if (num_bytes == 0)
3935 		return;
3936 
3937 	spin_lock(&root->qgroup_meta_rsv_lock);
3938 	if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
3939 		root->qgroup_meta_rsv_prealloc += num_bytes;
3940 	else
3941 		root->qgroup_meta_rsv_pertrans += num_bytes;
3942 	spin_unlock(&root->qgroup_meta_rsv_lock);
3943 }
3944 
sub_root_meta_rsv(struct btrfs_root * root,int num_bytes,enum btrfs_qgroup_rsv_type type)3945 static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
3946 			     enum btrfs_qgroup_rsv_type type)
3947 {
3948 	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
3949 	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
3950 		return 0;
3951 	if (num_bytes == 0)
3952 		return 0;
3953 
3954 	spin_lock(&root->qgroup_meta_rsv_lock);
3955 	if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
3956 		num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
3957 				  num_bytes);
3958 		root->qgroup_meta_rsv_prealloc -= num_bytes;
3959 	} else {
3960 		num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
3961 				  num_bytes);
3962 		root->qgroup_meta_rsv_pertrans -= num_bytes;
3963 	}
3964 	spin_unlock(&root->qgroup_meta_rsv_lock);
3965 	return num_bytes;
3966 }
3967 
btrfs_qgroup_reserve_meta(struct btrfs_root * root,int num_bytes,enum btrfs_qgroup_rsv_type type,bool enforce)3968 int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3969 			      enum btrfs_qgroup_rsv_type type, bool enforce)
3970 {
3971 	struct btrfs_fs_info *fs_info = root->fs_info;
3972 	int ret;
3973 
3974 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3975 	    !is_fstree(root->root_key.objectid) || num_bytes == 0)
3976 		return 0;
3977 
3978 	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3979 	trace_qgroup_meta_reserve(root, (s64)num_bytes, type);
3980 	ret = qgroup_reserve(root, num_bytes, enforce, type);
3981 	if (ret < 0)
3982 		return ret;
3983 	/*
3984 	 * Record what we have reserved into root.
3985 	 *
3986 	 * To avoid quota disabled->enabled underflow.
3987 	 * In that case, we may try to free space we haven't reserved
3988 	 * (since quota was disabled), so record what we reserved into root.
3989 	 * And ensure later release won't underflow this number.
3990 	 */
3991 	add_root_meta_rsv(root, num_bytes, type);
3992 	return ret;
3993 }
3994 
__btrfs_qgroup_reserve_meta(struct btrfs_root * root,int num_bytes,enum btrfs_qgroup_rsv_type type,bool enforce)3995 int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
3996 				enum btrfs_qgroup_rsv_type type, bool enforce)
3997 {
3998 	int ret;
3999 
4000 	ret = btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4001 	if (ret <= 0 && ret != -EDQUOT)
4002 		return ret;
4003 
4004 	ret = try_flush_qgroup(root);
4005 	if (ret < 0)
4006 		return ret;
4007 	return btrfs_qgroup_reserve_meta(root, num_bytes, type, enforce);
4008 }
4009 
btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root * root)4010 void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
4011 {
4012 	struct btrfs_fs_info *fs_info = root->fs_info;
4013 
4014 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4015 	    !is_fstree(root->root_key.objectid))
4016 		return;
4017 
4018 	/* TODO: Update trace point to handle such free */
4019 	trace_qgroup_meta_free_all_pertrans(root);
4020 	/* Special value -1 means to free all reserved space */
4021 	btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
4022 				  BTRFS_QGROUP_RSV_META_PERTRANS);
4023 }
4024 
__btrfs_qgroup_free_meta(struct btrfs_root * root,int num_bytes,enum btrfs_qgroup_rsv_type type)4025 void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
4026 			      enum btrfs_qgroup_rsv_type type)
4027 {
4028 	struct btrfs_fs_info *fs_info = root->fs_info;
4029 
4030 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4031 	    !is_fstree(root->root_key.objectid))
4032 		return;
4033 
4034 	/*
4035 	 * reservation for META_PREALLOC can happen before quota is enabled,
4036 	 * which can lead to underflow.
4037 	 * Here ensure we will only free what we really have reserved.
4038 	 */
4039 	num_bytes = sub_root_meta_rsv(root, num_bytes, type);
4040 	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
4041 	trace_qgroup_meta_reserve(root, -(s64)num_bytes, type);
4042 	btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
4043 				  num_bytes, type);
4044 }
4045 
qgroup_convert_meta(struct btrfs_fs_info * fs_info,u64 ref_root,int num_bytes)4046 static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
4047 				int num_bytes)
4048 {
4049 	struct btrfs_qgroup *qgroup;
4050 	struct ulist_node *unode;
4051 	struct ulist_iterator uiter;
4052 	int ret = 0;
4053 
4054 	if (num_bytes == 0)
4055 		return;
4056 	if (!fs_info->quota_root)
4057 		return;
4058 
4059 	spin_lock(&fs_info->qgroup_lock);
4060 	qgroup = find_qgroup_rb(fs_info, ref_root);
4061 	if (!qgroup)
4062 		goto out;
4063 	ulist_reinit(fs_info->qgroup_ulist);
4064 	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
4065 		       qgroup_to_aux(qgroup), GFP_ATOMIC);
4066 	if (ret < 0)
4067 		goto out;
4068 	ULIST_ITER_INIT(&uiter);
4069 	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
4070 		struct btrfs_qgroup *qg;
4071 		struct btrfs_qgroup_list *glist;
4072 
4073 		qg = unode_aux_to_qgroup(unode);
4074 
4075 		qgroup_rsv_release(fs_info, qg, num_bytes,
4076 				BTRFS_QGROUP_RSV_META_PREALLOC);
4077 		qgroup_rsv_add(fs_info, qg, num_bytes,
4078 				BTRFS_QGROUP_RSV_META_PERTRANS);
4079 		list_for_each_entry(glist, &qg->groups, next_group) {
4080 			ret = ulist_add(fs_info->qgroup_ulist,
4081 					glist->group->qgroupid,
4082 					qgroup_to_aux(glist->group), GFP_ATOMIC);
4083 			if (ret < 0)
4084 				goto out;
4085 		}
4086 	}
4087 out:
4088 	spin_unlock(&fs_info->qgroup_lock);
4089 }
4090 
btrfs_qgroup_convert_reserved_meta(struct btrfs_root * root,int num_bytes)4091 void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
4092 {
4093 	struct btrfs_fs_info *fs_info = root->fs_info;
4094 
4095 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
4096 	    !is_fstree(root->root_key.objectid))
4097 		return;
4098 	/* Same as btrfs_qgroup_free_meta_prealloc() */
4099 	num_bytes = sub_root_meta_rsv(root, num_bytes,
4100 				      BTRFS_QGROUP_RSV_META_PREALLOC);
4101 	trace_qgroup_meta_convert(root, num_bytes);
4102 	qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
4103 }
4104 
4105 /*
4106  * Check qgroup reserved space leaking, normally at destroy inode
4107  * time
4108  */
btrfs_qgroup_check_reserved_leak(struct btrfs_inode * inode)4109 void btrfs_qgroup_check_reserved_leak(struct btrfs_inode *inode)
4110 {
4111 	struct extent_changeset changeset;
4112 	struct ulist_node *unode;
4113 	struct ulist_iterator iter;
4114 	int ret;
4115 
4116 	extent_changeset_init(&changeset);
4117 	ret = clear_record_extent_bits(&inode->io_tree, 0, (u64)-1,
4118 			EXTENT_QGROUP_RESERVED, &changeset);
4119 
4120 	WARN_ON(ret < 0);
4121 	if (WARN_ON(changeset.bytes_changed)) {
4122 		ULIST_ITER_INIT(&iter);
4123 		while ((unode = ulist_next(&changeset.range_changed, &iter))) {
4124 			btrfs_warn(inode->root->fs_info,
4125 		"leaking qgroup reserved space, ino: %llu, start: %llu, end: %llu",
4126 				btrfs_ino(inode), unode->val, unode->aux);
4127 		}
4128 		btrfs_qgroup_free_refroot(inode->root->fs_info,
4129 				inode->root->root_key.objectid,
4130 				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
4131 
4132 	}
4133 	extent_changeset_release(&changeset);
4134 }
4135 
btrfs_qgroup_init_swapped_blocks(struct btrfs_qgroup_swapped_blocks * swapped_blocks)4136 void btrfs_qgroup_init_swapped_blocks(
4137 	struct btrfs_qgroup_swapped_blocks *swapped_blocks)
4138 {
4139 	int i;
4140 
4141 	spin_lock_init(&swapped_blocks->lock);
4142 	for (i = 0; i < BTRFS_MAX_LEVEL; i++)
4143 		swapped_blocks->blocks[i] = RB_ROOT;
4144 	swapped_blocks->swapped = false;
4145 }
4146 
4147 /*
4148  * Delete all swapped blocks record of @root.
4149  * Every record here means we skipped a full subtree scan for qgroup.
4150  *
4151  * Gets called when committing one transaction.
4152  */
btrfs_qgroup_clean_swapped_blocks(struct btrfs_root * root)4153 void btrfs_qgroup_clean_swapped_blocks(struct btrfs_root *root)
4154 {
4155 	struct btrfs_qgroup_swapped_blocks *swapped_blocks;
4156 	int i;
4157 
4158 	swapped_blocks = &root->swapped_blocks;
4159 
4160 	spin_lock(&swapped_blocks->lock);
4161 	if (!swapped_blocks->swapped)
4162 		goto out;
4163 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4164 		struct rb_root *cur_root = &swapped_blocks->blocks[i];
4165 		struct btrfs_qgroup_swapped_block *entry;
4166 		struct btrfs_qgroup_swapped_block *next;
4167 
4168 		rbtree_postorder_for_each_entry_safe(entry, next, cur_root,
4169 						     node)
4170 			kfree(entry);
4171 		swapped_blocks->blocks[i] = RB_ROOT;
4172 	}
4173 	swapped_blocks->swapped = false;
4174 out:
4175 	spin_unlock(&swapped_blocks->lock);
4176 }
4177 
4178 /*
4179  * Add subtree roots record into @subvol_root.
4180  *
4181  * @subvol_root:	tree root of the subvolume tree get swapped
4182  * @bg:			block group under balance
4183  * @subvol_parent/slot:	pointer to the subtree root in subvolume tree
4184  * @reloc_parent/slot:	pointer to the subtree root in reloc tree
4185  *			BOTH POINTERS ARE BEFORE TREE SWAP
4186  * @last_snapshot:	last snapshot generation of the subvolume tree
4187  */
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)4188 int btrfs_qgroup_add_swapped_blocks(struct btrfs_trans_handle *trans,
4189 		struct btrfs_root *subvol_root,
4190 		struct btrfs_block_group *bg,
4191 		struct extent_buffer *subvol_parent, int subvol_slot,
4192 		struct extent_buffer *reloc_parent, int reloc_slot,
4193 		u64 last_snapshot)
4194 {
4195 	struct btrfs_fs_info *fs_info = subvol_root->fs_info;
4196 	struct btrfs_qgroup_swapped_blocks *blocks = &subvol_root->swapped_blocks;
4197 	struct btrfs_qgroup_swapped_block *block;
4198 	struct rb_node **cur;
4199 	struct rb_node *parent = NULL;
4200 	int level = btrfs_header_level(subvol_parent) - 1;
4201 	int ret = 0;
4202 
4203 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4204 		return 0;
4205 
4206 	if (btrfs_node_ptr_generation(subvol_parent, subvol_slot) >
4207 	    btrfs_node_ptr_generation(reloc_parent, reloc_slot)) {
4208 		btrfs_err_rl(fs_info,
4209 		"%s: bad parameter order, subvol_gen=%llu reloc_gen=%llu",
4210 			__func__,
4211 			btrfs_node_ptr_generation(subvol_parent, subvol_slot),
4212 			btrfs_node_ptr_generation(reloc_parent, reloc_slot));
4213 		return -EUCLEAN;
4214 	}
4215 
4216 	block = kmalloc(sizeof(*block), GFP_NOFS);
4217 	if (!block) {
4218 		ret = -ENOMEM;
4219 		goto out;
4220 	}
4221 
4222 	/*
4223 	 * @reloc_parent/slot is still before swap, while @block is going to
4224 	 * record the bytenr after swap, so we do the swap here.
4225 	 */
4226 	block->subvol_bytenr = btrfs_node_blockptr(reloc_parent, reloc_slot);
4227 	block->subvol_generation = btrfs_node_ptr_generation(reloc_parent,
4228 							     reloc_slot);
4229 	block->reloc_bytenr = btrfs_node_blockptr(subvol_parent, subvol_slot);
4230 	block->reloc_generation = btrfs_node_ptr_generation(subvol_parent,
4231 							    subvol_slot);
4232 	block->last_snapshot = last_snapshot;
4233 	block->level = level;
4234 
4235 	/*
4236 	 * If we have bg == NULL, we're called from btrfs_recover_relocation(),
4237 	 * no one else can modify tree blocks thus we qgroup will not change
4238 	 * no matter the value of trace_leaf.
4239 	 */
4240 	if (bg && bg->flags & BTRFS_BLOCK_GROUP_DATA)
4241 		block->trace_leaf = true;
4242 	else
4243 		block->trace_leaf = false;
4244 	btrfs_node_key_to_cpu(reloc_parent, &block->first_key, reloc_slot);
4245 
4246 	/* Insert @block into @blocks */
4247 	spin_lock(&blocks->lock);
4248 	cur = &blocks->blocks[level].rb_node;
4249 	while (*cur) {
4250 		struct btrfs_qgroup_swapped_block *entry;
4251 
4252 		parent = *cur;
4253 		entry = rb_entry(parent, struct btrfs_qgroup_swapped_block,
4254 				 node);
4255 
4256 		if (entry->subvol_bytenr < block->subvol_bytenr) {
4257 			cur = &(*cur)->rb_left;
4258 		} else if (entry->subvol_bytenr > block->subvol_bytenr) {
4259 			cur = &(*cur)->rb_right;
4260 		} else {
4261 			if (entry->subvol_generation !=
4262 					block->subvol_generation ||
4263 			    entry->reloc_bytenr != block->reloc_bytenr ||
4264 			    entry->reloc_generation !=
4265 					block->reloc_generation) {
4266 				/*
4267 				 * Duplicated but mismatch entry found.
4268 				 * Shouldn't happen.
4269 				 *
4270 				 * Marking qgroup inconsistent should be enough
4271 				 * for end users.
4272 				 */
4273 				WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
4274 				ret = -EEXIST;
4275 			}
4276 			kfree(block);
4277 			goto out_unlock;
4278 		}
4279 	}
4280 	rb_link_node(&block->node, parent, cur);
4281 	rb_insert_color(&block->node, &blocks->blocks[level]);
4282 	blocks->swapped = true;
4283 out_unlock:
4284 	spin_unlock(&blocks->lock);
4285 out:
4286 	if (ret < 0)
4287 		fs_info->qgroup_flags |=
4288 			BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4289 	return ret;
4290 }
4291 
4292 /*
4293  * Check if the tree block is a subtree root, and if so do the needed
4294  * delayed subtree trace for qgroup.
4295  *
4296  * This is called during btrfs_cow_block().
4297  */
btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct extent_buffer * subvol_eb)4298 int btrfs_qgroup_trace_subtree_after_cow(struct btrfs_trans_handle *trans,
4299 					 struct btrfs_root *root,
4300 					 struct extent_buffer *subvol_eb)
4301 {
4302 	struct btrfs_fs_info *fs_info = root->fs_info;
4303 	struct btrfs_qgroup_swapped_blocks *blocks = &root->swapped_blocks;
4304 	struct btrfs_qgroup_swapped_block *block;
4305 	struct extent_buffer *reloc_eb = NULL;
4306 	struct rb_node *node;
4307 	bool found = false;
4308 	bool swapped = false;
4309 	int level = btrfs_header_level(subvol_eb);
4310 	int ret = 0;
4311 	int i;
4312 
4313 	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
4314 		return 0;
4315 	if (!is_fstree(root->root_key.objectid) || !root->reloc_root)
4316 		return 0;
4317 
4318 	spin_lock(&blocks->lock);
4319 	if (!blocks->swapped) {
4320 		spin_unlock(&blocks->lock);
4321 		return 0;
4322 	}
4323 	node = blocks->blocks[level].rb_node;
4324 
4325 	while (node) {
4326 		block = rb_entry(node, struct btrfs_qgroup_swapped_block, node);
4327 		if (block->subvol_bytenr < subvol_eb->start) {
4328 			node = node->rb_left;
4329 		} else if (block->subvol_bytenr > subvol_eb->start) {
4330 			node = node->rb_right;
4331 		} else {
4332 			found = true;
4333 			break;
4334 		}
4335 	}
4336 	if (!found) {
4337 		spin_unlock(&blocks->lock);
4338 		goto out;
4339 	}
4340 	/* Found one, remove it from @blocks first and update blocks->swapped */
4341 	rb_erase(&block->node, &blocks->blocks[level]);
4342 	for (i = 0; i < BTRFS_MAX_LEVEL; i++) {
4343 		if (RB_EMPTY_ROOT(&blocks->blocks[i])) {
4344 			swapped = true;
4345 			break;
4346 		}
4347 	}
4348 	blocks->swapped = swapped;
4349 	spin_unlock(&blocks->lock);
4350 
4351 	/* Read out reloc subtree root */
4352 	reloc_eb = read_tree_block(fs_info, block->reloc_bytenr,
4353 				   block->reloc_generation, block->level,
4354 				   &block->first_key);
4355 	if (IS_ERR(reloc_eb)) {
4356 		ret = PTR_ERR(reloc_eb);
4357 		reloc_eb = NULL;
4358 		goto free_out;
4359 	}
4360 	if (!extent_buffer_uptodate(reloc_eb)) {
4361 		ret = -EIO;
4362 		goto free_out;
4363 	}
4364 
4365 	ret = qgroup_trace_subtree_swap(trans, reloc_eb, subvol_eb,
4366 			block->last_snapshot, block->trace_leaf);
4367 free_out:
4368 	kfree(block);
4369 	free_extent_buffer(reloc_eb);
4370 out:
4371 	if (ret < 0) {
4372 		btrfs_err_rl(fs_info,
4373 			     "failed to account subtree at bytenr %llu: %d",
4374 			     subvol_eb->start, ret);
4375 		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
4376 	}
4377 	return ret;
4378 }
4379 
btrfs_qgroup_destroy_extent_records(struct btrfs_transaction * trans)4380 void btrfs_qgroup_destroy_extent_records(struct btrfs_transaction *trans)
4381 {
4382 	struct btrfs_qgroup_extent_record *entry;
4383 	struct btrfs_qgroup_extent_record *next;
4384 	struct rb_root *root;
4385 
4386 	root = &trans->delayed_refs.dirty_extent_root;
4387 	rbtree_postorder_for_each_entry_safe(entry, next, root, node) {
4388 		ulist_free(entry->old_roots);
4389 		kfree(entry);
4390 	}
4391 	*root = RB_ROOT;
4392 }
4393