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