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