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