qgroup.c 97.0 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2 3 4 5 6 7 8 9 10 11 12
/*
 * Copyright (C) 2011 STRATO.  All rights reserved.
 */

#include <linux/sched.h>
#include <linux/pagemap.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/rbtree.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
13
#include <linux/btrfs.h>
14
#include <linux/sizes.h>
15 16 17 18 19 20 21

#include "ctree.h"
#include "transaction.h"
#include "disk-io.h"
#include "locking.h"
#include "ulist.h"
#include "backref.h"
J
Jan Schmidt 已提交
22
#include "extent_io.h"
J
Josef Bacik 已提交
23
#include "qgroup.h"
24

25

26 27 28 29 30 31 32 33 34 35 36 37
/* TODO XXX FIXME
 *  - subvol delete -> delete when ref goes to 0? delete limits also?
 *  - reorganize keys
 *  - compressed
 *  - sync
 *  - copy also limits on subvol creation
 *  - limit
 *  - caches fuer ulists
 *  - performance benchmarks
 *  - check all ioctl parameters
 */

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/*
 * Helpers to access qgroup reservation
 *
 * Callers should ensure the lock context and type are valid
 */

static u64 qgroup_rsv_total(const struct btrfs_qgroup *qgroup)
{
	u64 ret = 0;
	int i;

	for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
		ret += qgroup->rsv.values[i];

	return ret;
}

#ifdef CONFIG_BTRFS_DEBUG
static const char *qgroup_rsv_type_str(enum btrfs_qgroup_rsv_type type)
{
	if (type == BTRFS_QGROUP_RSV_DATA)
		return "data";
60 61 62 63
	if (type == BTRFS_QGROUP_RSV_META_PERTRANS)
		return "meta_pertrans";
	if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
		return "meta_prealloc";
64 65 66 67
	return NULL;
}
#endif

68 69
static void qgroup_rsv_add(struct btrfs_fs_info *fs_info,
			   struct btrfs_qgroup *qgroup, u64 num_bytes,
70 71
			   enum btrfs_qgroup_rsv_type type)
{
72
	trace_qgroup_update_reserve(fs_info, qgroup, num_bytes, type);
73 74 75
	qgroup->rsv.values[type] += num_bytes;
}

76 77
static void qgroup_rsv_release(struct btrfs_fs_info *fs_info,
			       struct btrfs_qgroup *qgroup, u64 num_bytes,
78 79
			       enum btrfs_qgroup_rsv_type type)
{
80
	trace_qgroup_update_reserve(fs_info, qgroup, -(s64)num_bytes, type);
81 82 83 84 85 86 87 88 89 90 91 92 93
	if (qgroup->rsv.values[type] >= num_bytes) {
		qgroup->rsv.values[type] -= num_bytes;
		return;
	}
#ifdef CONFIG_BTRFS_DEBUG
	WARN_RATELIMIT(1,
		"qgroup %llu %s reserved space underflow, have %llu to free %llu",
		qgroup->qgroupid, qgroup_rsv_type_str(type),
		qgroup->rsv.values[type], num_bytes);
#endif
	qgroup->rsv.values[type] = 0;
}

94 95 96
static void qgroup_rsv_add_by_qgroup(struct btrfs_fs_info *fs_info,
				     struct btrfs_qgroup *dest,
				     struct btrfs_qgroup *src)
97 98 99 100
{
	int i;

	for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
101
		qgroup_rsv_add(fs_info, dest, src->rsv.values[i], i);
102 103
}

104 105
static void qgroup_rsv_release_by_qgroup(struct btrfs_fs_info *fs_info,
					 struct btrfs_qgroup *dest,
106 107 108 109 110
					  struct btrfs_qgroup *src)
{
	int i;

	for (i = 0; i < BTRFS_QGROUP_RSV_LAST; i++)
111
		qgroup_rsv_release(fs_info, dest, src->rsv.values[i], i);
112 113
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
static void btrfs_qgroup_update_old_refcnt(struct btrfs_qgroup *qg, u64 seq,
					   int mod)
{
	if (qg->old_refcnt < seq)
		qg->old_refcnt = seq;
	qg->old_refcnt += mod;
}

static void btrfs_qgroup_update_new_refcnt(struct btrfs_qgroup *qg, u64 seq,
					   int mod)
{
	if (qg->new_refcnt < seq)
		qg->new_refcnt = seq;
	qg->new_refcnt += mod;
}

static inline u64 btrfs_qgroup_get_old_refcnt(struct btrfs_qgroup *qg, u64 seq)
{
	if (qg->old_refcnt < seq)
		return 0;
	return qg->old_refcnt - seq;
}

static inline u64 btrfs_qgroup_get_new_refcnt(struct btrfs_qgroup *qg, u64 seq)
{
	if (qg->new_refcnt < seq)
		return 0;
	return qg->new_refcnt - seq;
}

144 145 146 147 148 149 150 151 152 153
/*
 * glue structure to represent the relations between qgroups.
 */
struct btrfs_qgroup_list {
	struct list_head next_group;
	struct list_head next_member;
	struct btrfs_qgroup *group;
	struct btrfs_qgroup *member;
};

154 155 156 157 158 159 160 161 162
static inline u64 qgroup_to_aux(struct btrfs_qgroup *qg)
{
	return (u64)(uintptr_t)qg;
}

static inline struct btrfs_qgroup* unode_aux_to_qgroup(struct ulist_node *n)
{
	return (struct btrfs_qgroup *)(uintptr_t)n->aux;
}
J
Josef Bacik 已提交
163

164 165 166 167
static int
qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
		   int init_flags);
static void qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info);
J
Jan Schmidt 已提交
168

169
/* must be called with qgroup_ioctl_lock held */
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
static struct btrfs_qgroup *find_qgroup_rb(struct btrfs_fs_info *fs_info,
					   u64 qgroupid)
{
	struct rb_node *n = fs_info->qgroup_tree.rb_node;
	struct btrfs_qgroup *qgroup;

	while (n) {
		qgroup = rb_entry(n, struct btrfs_qgroup, node);
		if (qgroup->qgroupid < qgroupid)
			n = n->rb_left;
		else if (qgroup->qgroupid > qgroupid)
			n = n->rb_right;
		else
			return qgroup;
	}
	return NULL;
}

/* must be called with qgroup_lock held */
static struct btrfs_qgroup *add_qgroup_rb(struct btrfs_fs_info *fs_info,
					  u64 qgroupid)
{
	struct rb_node **p = &fs_info->qgroup_tree.rb_node;
	struct rb_node *parent = NULL;
	struct btrfs_qgroup *qgroup;

	while (*p) {
		parent = *p;
		qgroup = rb_entry(parent, struct btrfs_qgroup, node);

		if (qgroup->qgroupid < qgroupid)
			p = &(*p)->rb_left;
		else if (qgroup->qgroupid > qgroupid)
			p = &(*p)->rb_right;
		else
			return qgroup;
	}

	qgroup = kzalloc(sizeof(*qgroup), GFP_ATOMIC);
	if (!qgroup)
		return ERR_PTR(-ENOMEM);

	qgroup->qgroupid = qgroupid;
	INIT_LIST_HEAD(&qgroup->groups);
	INIT_LIST_HEAD(&qgroup->members);
	INIT_LIST_HEAD(&qgroup->dirty);

	rb_link_node(&qgroup->node, parent, p);
	rb_insert_color(&qgroup->node, &fs_info->qgroup_tree);

	return qgroup;
}

223
static void __del_qgroup_rb(struct btrfs_qgroup *qgroup)
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
{
	struct btrfs_qgroup_list *list;

	list_del(&qgroup->dirty);
	while (!list_empty(&qgroup->groups)) {
		list = list_first_entry(&qgroup->groups,
					struct btrfs_qgroup_list, next_group);
		list_del(&list->next_group);
		list_del(&list->next_member);
		kfree(list);
	}

	while (!list_empty(&qgroup->members)) {
		list = list_first_entry(&qgroup->members,
					struct btrfs_qgroup_list, next_member);
		list_del(&list->next_group);
		list_del(&list->next_member);
		kfree(list);
	}
	kfree(qgroup);
244
}
245

246 247 248 249 250 251 252 253 254 255
/* must be called with qgroup_lock held */
static int del_qgroup_rb(struct btrfs_fs_info *fs_info, u64 qgroupid)
{
	struct btrfs_qgroup *qgroup = find_qgroup_rb(fs_info, qgroupid);

	if (!qgroup)
		return -ENOENT;

	rb_erase(&qgroup->node, &fs_info->qgroup_tree);
	__del_qgroup_rb(qgroup);
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
	return 0;
}

/* must be called with qgroup_lock held */
static int add_relation_rb(struct btrfs_fs_info *fs_info,
			   u64 memberid, u64 parentid)
{
	struct btrfs_qgroup *member;
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup_list *list;

	member = find_qgroup_rb(fs_info, memberid);
	parent = find_qgroup_rb(fs_info, parentid);
	if (!member || !parent)
		return -ENOENT;

	list = kzalloc(sizeof(*list), GFP_ATOMIC);
	if (!list)
		return -ENOMEM;

	list->group = parent;
	list->member = member;
	list_add_tail(&list->next_group, &member->groups);
	list_add_tail(&list->next_member, &parent->members);

	return 0;
}

/* must be called with qgroup_lock held */
static int del_relation_rb(struct btrfs_fs_info *fs_info,
			   u64 memberid, u64 parentid)
{
	struct btrfs_qgroup *member;
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup_list *list;

	member = find_qgroup_rb(fs_info, memberid);
	parent = find_qgroup_rb(fs_info, parentid);
	if (!member || !parent)
		return -ENOENT;

	list_for_each_entry(list, &member->groups, next_group) {
		if (list->group == parent) {
			list_del(&list->next_group);
			list_del(&list->next_member);
			kfree(list);
			return 0;
		}
	}
	return -ENOENT;
}

308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
int btrfs_verify_qgroup_counts(struct btrfs_fs_info *fs_info, u64 qgroupid,
			       u64 rfer, u64 excl)
{
	struct btrfs_qgroup *qgroup;

	qgroup = find_qgroup_rb(fs_info, qgroupid);
	if (!qgroup)
		return -EINVAL;
	if (qgroup->rfer != rfer || qgroup->excl != excl)
		return -EINVAL;
	return 0;
}
#endif

323 324 325 326 327 328 329 330 331 332 333 334 335 336
/*
 * The full config is read in one go, only called from open_ctree()
 * It doesn't use any locking, as at this point we're still single-threaded
 */
int btrfs_read_qgroup_config(struct btrfs_fs_info *fs_info)
{
	struct btrfs_key key;
	struct btrfs_key found_key;
	struct btrfs_root *quota_root = fs_info->quota_root;
	struct btrfs_path *path = NULL;
	struct extent_buffer *l;
	int slot;
	int ret = 0;
	u64 flags = 0;
337
	u64 rescan_progress = 0;
338

339
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
340 341
		return 0;

342
	fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
343 344 345 346 347
	if (!fs_info->qgroup_ulist) {
		ret = -ENOMEM;
		goto out;
	}

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
	path = btrfs_alloc_path();
	if (!path) {
		ret = -ENOMEM;
		goto out;
	}

	/* default this to quota off, in case no status key is found */
	fs_info->qgroup_flags = 0;

	/*
	 * pass 1: read status, all qgroup infos and limits
	 */
	key.objectid = 0;
	key.type = 0;
	key.offset = 0;
	ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 1);
	if (ret)
		goto out;

	while (1) {
		struct btrfs_qgroup *qgroup;

		slot = path->slots[0];
		l = path->nodes[0];
		btrfs_item_key_to_cpu(l, &found_key, slot);

		if (found_key.type == BTRFS_QGROUP_STATUS_KEY) {
			struct btrfs_qgroup_status_item *ptr;

			ptr = btrfs_item_ptr(l, slot,
					     struct btrfs_qgroup_status_item);

			if (btrfs_qgroup_status_version(l, ptr) !=
			    BTRFS_QGROUP_STATUS_VERSION) {
382 383
				btrfs_err(fs_info,
				 "old qgroup version, quota disabled");
384 385 386 387 388
				goto out;
			}
			if (btrfs_qgroup_status_generation(l, ptr) !=
			    fs_info->generation) {
				flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
389
				btrfs_err(fs_info,
J
Jeff Mahoney 已提交
390
					"qgroup generation mismatch, marked as inconsistent");
391 392 393
			}
			fs_info->qgroup_flags = btrfs_qgroup_status_flags(l,
									  ptr);
394
			rescan_progress = btrfs_qgroup_status_rescan(l, ptr);
395 396 397 398 399 400 401 402 403 404
			goto next1;
		}

		if (found_key.type != BTRFS_QGROUP_INFO_KEY &&
		    found_key.type != BTRFS_QGROUP_LIMIT_KEY)
			goto next1;

		qgroup = find_qgroup_rb(fs_info, found_key.offset);
		if ((qgroup && found_key.type == BTRFS_QGROUP_INFO_KEY) ||
		    (!qgroup && found_key.type == BTRFS_QGROUP_LIMIT_KEY)) {
405
			btrfs_err(fs_info, "inconsistent qgroup config");
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
			flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		}
		if (!qgroup) {
			qgroup = add_qgroup_rb(fs_info, found_key.offset);
			if (IS_ERR(qgroup)) {
				ret = PTR_ERR(qgroup);
				goto out;
			}
		}
		switch (found_key.type) {
		case BTRFS_QGROUP_INFO_KEY: {
			struct btrfs_qgroup_info_item *ptr;

			ptr = btrfs_item_ptr(l, slot,
					     struct btrfs_qgroup_info_item);
			qgroup->rfer = btrfs_qgroup_info_rfer(l, ptr);
			qgroup->rfer_cmpr = btrfs_qgroup_info_rfer_cmpr(l, ptr);
			qgroup->excl = btrfs_qgroup_info_excl(l, ptr);
			qgroup->excl_cmpr = btrfs_qgroup_info_excl_cmpr(l, ptr);
			/* generation currently unused */
			break;
		}
		case BTRFS_QGROUP_LIMIT_KEY: {
			struct btrfs_qgroup_limit_item *ptr;

			ptr = btrfs_item_ptr(l, slot,
					     struct btrfs_qgroup_limit_item);
			qgroup->lim_flags = btrfs_qgroup_limit_flags(l, ptr);
			qgroup->max_rfer = btrfs_qgroup_limit_max_rfer(l, ptr);
			qgroup->max_excl = btrfs_qgroup_limit_max_excl(l, ptr);
			qgroup->rsv_rfer = btrfs_qgroup_limit_rsv_rfer(l, ptr);
			qgroup->rsv_excl = btrfs_qgroup_limit_rsv_excl(l, ptr);
			break;
		}
		}
next1:
		ret = btrfs_next_item(quota_root, path);
		if (ret < 0)
			goto out;
		if (ret)
			break;
	}
	btrfs_release_path(path);

	/*
	 * pass 2: read all qgroup relations
	 */
	key.objectid = 0;
	key.type = BTRFS_QGROUP_RELATION_KEY;
	key.offset = 0;
	ret = btrfs_search_slot_for_read(quota_root, &key, path, 1, 0);
	if (ret)
		goto out;
	while (1) {
		slot = path->slots[0];
		l = path->nodes[0];
		btrfs_item_key_to_cpu(l, &found_key, slot);

		if (found_key.type != BTRFS_QGROUP_RELATION_KEY)
			goto next2;

		if (found_key.objectid > found_key.offset) {
			/* parent <- member, not needed to build config */
			/* FIXME should we omit the key completely? */
			goto next2;
		}

		ret = add_relation_rb(fs_info, found_key.objectid,
				      found_key.offset);
475
		if (ret == -ENOENT) {
476 477
			btrfs_warn(fs_info,
				"orphan qgroup relation 0x%llx->0x%llx",
478
				found_key.objectid, found_key.offset);
479 480
			ret = 0;	/* ignore the error */
		}
481 482 483 484 485 486 487 488 489 490 491
		if (ret)
			goto out;
next2:
		ret = btrfs_next_item(quota_root, path);
		if (ret < 0)
			goto out;
		if (ret)
			break;
	}
out:
	fs_info->qgroup_flags |= flags;
492 493 494 495
	if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
		clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
	else if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN &&
		 ret >= 0)
496
		ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
497 498
	btrfs_free_path(path);

499
	if (ret < 0) {
500
		ulist_free(fs_info->qgroup_ulist);
501
		fs_info->qgroup_ulist = NULL;
502
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
503
	}
504

505 506 507 508
	return ret < 0 ? ret : 0;
}

/*
509 510 511 512
 * This is called from close_ctree() or open_ctree() or btrfs_quota_disable(),
 * first two are in single-threaded paths.And for the third one, we have set
 * quota_root to be null with qgroup_lock held before, so it is safe to clean
 * up the in-memory structures without qgroup_lock held.
513 514 515 516 517 518 519 520 521
 */
void btrfs_free_qgroup_config(struct btrfs_fs_info *fs_info)
{
	struct rb_node *n;
	struct btrfs_qgroup *qgroup;

	while ((n = rb_first(&fs_info->qgroup_tree))) {
		qgroup = rb_entry(n, struct btrfs_qgroup, node);
		rb_erase(n, &fs_info->qgroup_tree);
522
		__del_qgroup_rb(qgroup);
523
	}
524 525
	/*
	 * we call btrfs_free_qgroup_config() when umounting
526
	 * filesystem and disabling quota, so we set qgroup_ulist
527 528
	 * to be null here to avoid double free.
	 */
529
	ulist_free(fs_info->qgroup_ulist);
530
	fs_info->qgroup_ulist = NULL;
531 532
}

533 534
static int add_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
				    u64 dst)
535 536
{
	int ret;
537
	struct btrfs_root *quota_root = trans->fs_info->quota_root;
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
	struct btrfs_path *path;
	struct btrfs_key key;

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	key.objectid = src;
	key.type = BTRFS_QGROUP_RELATION_KEY;
	key.offset = dst;

	ret = btrfs_insert_empty_item(trans, quota_root, path, &key, 0);

	btrfs_mark_buffer_dirty(path->nodes[0]);

	btrfs_free_path(path);
	return ret;
}

557 558
static int del_qgroup_relation_item(struct btrfs_trans_handle *trans, u64 src,
				    u64 dst)
559 560
{
	int ret;
561
	struct btrfs_root *quota_root = trans->fs_info->quota_root;
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
	struct btrfs_path *path;
	struct btrfs_key key;

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	key.objectid = src;
	key.type = BTRFS_QGROUP_RELATION_KEY;
	key.offset = dst;

	ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
	if (ret < 0)
		goto out;

	if (ret > 0) {
		ret = -ENOENT;
		goto out;
	}

	ret = btrfs_del_item(trans, quota_root, path);
out:
	btrfs_free_path(path);
	return ret;
}

static int add_qgroup_item(struct btrfs_trans_handle *trans,
			   struct btrfs_root *quota_root, u64 qgroupid)
{
	int ret;
	struct btrfs_path *path;
	struct btrfs_qgroup_info_item *qgroup_info;
	struct btrfs_qgroup_limit_item *qgroup_limit;
	struct extent_buffer *leaf;
	struct btrfs_key key;

598
	if (btrfs_is_testing(quota_root->fs_info))
599
		return 0;
600

601 602 603 604 605 606 607 608
	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	key.objectid = 0;
	key.type = BTRFS_QGROUP_INFO_KEY;
	key.offset = qgroupid;

609 610 611 612 613 614
	/*
	 * Avoid a transaction abort by catching -EEXIST here. In that
	 * case, we proceed by re-initializing the existing structure
	 * on disk.
	 */

615 616
	ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
				      sizeof(*qgroup_info));
617
	if (ret && ret != -EEXIST)
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
		goto out;

	leaf = path->nodes[0];
	qgroup_info = btrfs_item_ptr(leaf, path->slots[0],
				 struct btrfs_qgroup_info_item);
	btrfs_set_qgroup_info_generation(leaf, qgroup_info, trans->transid);
	btrfs_set_qgroup_info_rfer(leaf, qgroup_info, 0);
	btrfs_set_qgroup_info_rfer_cmpr(leaf, qgroup_info, 0);
	btrfs_set_qgroup_info_excl(leaf, qgroup_info, 0);
	btrfs_set_qgroup_info_excl_cmpr(leaf, qgroup_info, 0);

	btrfs_mark_buffer_dirty(leaf);

	btrfs_release_path(path);

	key.type = BTRFS_QGROUP_LIMIT_KEY;
	ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
				      sizeof(*qgroup_limit));
636
	if (ret && ret != -EEXIST)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
		goto out;

	leaf = path->nodes[0];
	qgroup_limit = btrfs_item_ptr(leaf, path->slots[0],
				  struct btrfs_qgroup_limit_item);
	btrfs_set_qgroup_limit_flags(leaf, qgroup_limit, 0);
	btrfs_set_qgroup_limit_max_rfer(leaf, qgroup_limit, 0);
	btrfs_set_qgroup_limit_max_excl(leaf, qgroup_limit, 0);
	btrfs_set_qgroup_limit_rsv_rfer(leaf, qgroup_limit, 0);
	btrfs_set_qgroup_limit_rsv_excl(leaf, qgroup_limit, 0);

	btrfs_mark_buffer_dirty(leaf);

	ret = 0;
out:
	btrfs_free_path(path);
	return ret;
}

656
static int del_qgroup_item(struct btrfs_trans_handle *trans, u64 qgroupid)
657 658
{
	int ret;
659
	struct btrfs_root *quota_root = trans->fs_info->quota_root;
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
	struct btrfs_path *path;
	struct btrfs_key key;

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	key.objectid = 0;
	key.type = BTRFS_QGROUP_INFO_KEY;
	key.offset = qgroupid;
	ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
	if (ret < 0)
		goto out;

	if (ret > 0) {
		ret = -ENOENT;
		goto out;
	}

	ret = btrfs_del_item(trans, quota_root, path);
	if (ret)
		goto out;

	btrfs_release_path(path);

	key.type = BTRFS_QGROUP_LIMIT_KEY;
	ret = btrfs_search_slot(trans, quota_root, &key, path, -1, 1);
	if (ret < 0)
		goto out;

	if (ret > 0) {
		ret = -ENOENT;
		goto out;
	}

	ret = btrfs_del_item(trans, quota_root, path);

out:
	btrfs_free_path(path);
	return ret;
}

static int update_qgroup_limit_item(struct btrfs_trans_handle *trans,
703
				    struct btrfs_qgroup *qgroup)
704
{
705
	struct btrfs_root *quota_root = trans->fs_info->quota_root;
706 707 708 709 710 711 712 713 714
	struct btrfs_path *path;
	struct btrfs_key key;
	struct extent_buffer *l;
	struct btrfs_qgroup_limit_item *qgroup_limit;
	int ret;
	int slot;

	key.objectid = 0;
	key.type = BTRFS_QGROUP_LIMIT_KEY;
715
	key.offset = qgroup->qgroupid;
716 717

	path = btrfs_alloc_path();
718 719 720
	if (!path)
		return -ENOMEM;

721
	ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
722 723 724 725 726 727 728 729
	if (ret > 0)
		ret = -ENOENT;

	if (ret)
		goto out;

	l = path->nodes[0];
	slot = path->slots[0];
730
	qgroup_limit = btrfs_item_ptr(l, slot, struct btrfs_qgroup_limit_item);
731 732 733 734 735
	btrfs_set_qgroup_limit_flags(l, qgroup_limit, qgroup->lim_flags);
	btrfs_set_qgroup_limit_max_rfer(l, qgroup_limit, qgroup->max_rfer);
	btrfs_set_qgroup_limit_max_excl(l, qgroup_limit, qgroup->max_excl);
	btrfs_set_qgroup_limit_rsv_rfer(l, qgroup_limit, qgroup->rsv_rfer);
	btrfs_set_qgroup_limit_rsv_excl(l, qgroup_limit, qgroup->rsv_excl);
736 737 738 739 740 741 742 743 744 745 746

	btrfs_mark_buffer_dirty(l);

out:
	btrfs_free_path(path);
	return ret;
}

static int update_qgroup_info_item(struct btrfs_trans_handle *trans,
				   struct btrfs_qgroup *qgroup)
{
747 748
	struct btrfs_fs_info *fs_info = trans->fs_info;
	struct btrfs_root *quota_root = fs_info->quota_root;
749 750 751 752 753 754 755
	struct btrfs_path *path;
	struct btrfs_key key;
	struct extent_buffer *l;
	struct btrfs_qgroup_info_item *qgroup_info;
	int ret;
	int slot;

756
	if (btrfs_is_testing(fs_info))
757
		return 0;
758

759 760 761 762 763
	key.objectid = 0;
	key.type = BTRFS_QGROUP_INFO_KEY;
	key.offset = qgroup->qgroupid;

	path = btrfs_alloc_path();
764 765 766
	if (!path)
		return -ENOMEM;

767
	ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
768 769 770 771 772 773 774 775
	if (ret > 0)
		ret = -ENOENT;

	if (ret)
		goto out;

	l = path->nodes[0];
	slot = path->slots[0];
776
	qgroup_info = btrfs_item_ptr(l, slot, struct btrfs_qgroup_info_item);
777 778 779 780 781 782 783 784 785 786 787 788 789
	btrfs_set_qgroup_info_generation(l, qgroup_info, trans->transid);
	btrfs_set_qgroup_info_rfer(l, qgroup_info, qgroup->rfer);
	btrfs_set_qgroup_info_rfer_cmpr(l, qgroup_info, qgroup->rfer_cmpr);
	btrfs_set_qgroup_info_excl(l, qgroup_info, qgroup->excl);
	btrfs_set_qgroup_info_excl_cmpr(l, qgroup_info, qgroup->excl_cmpr);

	btrfs_mark_buffer_dirty(l);

out:
	btrfs_free_path(path);
	return ret;
}

790
static int update_qgroup_status_item(struct btrfs_trans_handle *trans)
791
{
792 793
	struct btrfs_fs_info *fs_info = trans->fs_info;
	struct btrfs_root *quota_root = fs_info->quota_root;
794 795 796 797 798 799 800 801 802 803 804 805
	struct btrfs_path *path;
	struct btrfs_key key;
	struct extent_buffer *l;
	struct btrfs_qgroup_status_item *ptr;
	int ret;
	int slot;

	key.objectid = 0;
	key.type = BTRFS_QGROUP_STATUS_KEY;
	key.offset = 0;

	path = btrfs_alloc_path();
806 807 808
	if (!path)
		return -ENOMEM;

809
	ret = btrfs_search_slot(trans, quota_root, &key, path, 0, 1);
810 811 812 813 814 815 816 817 818 819 820
	if (ret > 0)
		ret = -ENOENT;

	if (ret)
		goto out;

	l = path->nodes[0];
	slot = path->slots[0];
	ptr = btrfs_item_ptr(l, slot, struct btrfs_qgroup_status_item);
	btrfs_set_qgroup_status_flags(l, ptr, fs_info->qgroup_flags);
	btrfs_set_qgroup_status_generation(l, ptr, trans->transid);
J
Jan Schmidt 已提交
821 822
	btrfs_set_qgroup_status_rescan(l, ptr,
				fs_info->qgroup_rescan_progress.objectid);
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838

	btrfs_mark_buffer_dirty(l);

out:
	btrfs_free_path(path);
	return ret;
}

/*
 * called with qgroup_lock held
 */
static int btrfs_clean_quota_tree(struct btrfs_trans_handle *trans,
				  struct btrfs_root *root)
{
	struct btrfs_path *path;
	struct btrfs_key key;
839
	struct extent_buffer *leaf = NULL;
840
	int ret;
841
	int nr = 0;
842 843 844 845 846

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

847 848 849 850 851
	path->leave_spinning = 1;

	key.objectid = 0;
	key.offset = 0;
	key.type = 0;
852

853
	while (1) {
854
		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
855 856 857 858 859
		if (ret < 0)
			goto out;
		leaf = path->nodes[0];
		nr = btrfs_header_nritems(leaf);
		if (!nr)
860
			break;
861 862 863 864 865 866 867
		/*
		 * delete the leaf one by one
		 * since the whole tree is going
		 * to be deleted.
		 */
		path->slots[0] = 0;
		ret = btrfs_del_items(trans, root, path, 0, nr);
868 869
		if (ret)
			goto out;
870

871 872 873 874 875 876 877 878
		btrfs_release_path(path);
	}
	ret = 0;
out:
	btrfs_free_path(path);
	return ret;
}

879
int btrfs_quota_enable(struct btrfs_fs_info *fs_info)
880 881
{
	struct btrfs_root *quota_root;
882
	struct btrfs_root *tree_root = fs_info->tree_root;
883 884 885 886
	struct btrfs_path *path = NULL;
	struct btrfs_qgroup_status_item *ptr;
	struct extent_buffer *leaf;
	struct btrfs_key key;
887 888
	struct btrfs_key found_key;
	struct btrfs_qgroup *qgroup = NULL;
889
	struct btrfs_trans_handle *trans = NULL;
890
	int ret = 0;
891
	int slot;
892

893
	mutex_lock(&fs_info->qgroup_ioctl_lock);
894
	if (fs_info->quota_root)
895 896
		goto out;

897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
	/*
	 * 1 for quota root item
	 * 1 for BTRFS_QGROUP_STATUS item
	 *
	 * Yet we also need 2*n items for a QGROUP_INFO/QGROUP_LIMIT items
	 * per subvolume. However those are not currently reserved since it
	 * would be a lot of overkill.
	 */
	trans = btrfs_start_transaction(tree_root, 2);
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		trans = NULL;
		goto out;
	}

912
	fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
913 914
	if (!fs_info->qgroup_ulist) {
		ret = -ENOMEM;
915
		btrfs_abort_transaction(trans, ret);
916 917 918
		goto out;
	}

919 920 921 922 923 924 925
	/*
	 * initially create the quota tree
	 */
	quota_root = btrfs_create_tree(trans, fs_info,
				       BTRFS_QUOTA_TREE_OBJECTID);
	if (IS_ERR(quota_root)) {
		ret =  PTR_ERR(quota_root);
926
		btrfs_abort_transaction(trans, ret);
927 928 929 930
		goto out;
	}

	path = btrfs_alloc_path();
931 932
	if (!path) {
		ret = -ENOMEM;
933
		btrfs_abort_transaction(trans, ret);
934 935
		goto out_free_root;
	}
936 937 938 939 940 941 942

	key.objectid = 0;
	key.type = BTRFS_QGROUP_STATUS_KEY;
	key.offset = 0;

	ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
				      sizeof(*ptr));
943 944
	if (ret) {
		btrfs_abort_transaction(trans, ret);
945
		goto out_free_path;
946
	}
947 948 949 950 951 952 953 954 955

	leaf = path->nodes[0];
	ptr = btrfs_item_ptr(leaf, path->slots[0],
				 struct btrfs_qgroup_status_item);
	btrfs_set_qgroup_status_generation(leaf, ptr, trans->transid);
	btrfs_set_qgroup_status_version(leaf, ptr, BTRFS_QGROUP_STATUS_VERSION);
	fs_info->qgroup_flags = BTRFS_QGROUP_STATUS_FLAG_ON |
				BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	btrfs_set_qgroup_status_flags(leaf, ptr, fs_info->qgroup_flags);
J
Jan Schmidt 已提交
956
	btrfs_set_qgroup_status_rescan(leaf, ptr, 0);
957 958 959

	btrfs_mark_buffer_dirty(leaf);

960 961 962 963 964 965 966 967
	key.objectid = 0;
	key.type = BTRFS_ROOT_REF_KEY;
	key.offset = 0;

	btrfs_release_path(path);
	ret = btrfs_search_slot_for_read(tree_root, &key, path, 1, 0);
	if (ret > 0)
		goto out_add_root;
968 969
	if (ret < 0) {
		btrfs_abort_transaction(trans, ret);
970
		goto out_free_path;
971
	}
972 973 974 975 976 977 978 979 980

	while (1) {
		slot = path->slots[0];
		leaf = path->nodes[0];
		btrfs_item_key_to_cpu(leaf, &found_key, slot);

		if (found_key.type == BTRFS_ROOT_REF_KEY) {
			ret = add_qgroup_item(trans, quota_root,
					      found_key.offset);
981 982
			if (ret) {
				btrfs_abort_transaction(trans, ret);
983
				goto out_free_path;
984
			}
985 986 987 988

			qgroup = add_qgroup_rb(fs_info, found_key.offset);
			if (IS_ERR(qgroup)) {
				ret = PTR_ERR(qgroup);
989
				btrfs_abort_transaction(trans, ret);
990 991 992 993
				goto out_free_path;
			}
		}
		ret = btrfs_next_item(tree_root, path);
994 995
		if (ret < 0) {
			btrfs_abort_transaction(trans, ret);
996
			goto out_free_path;
997
		}
998 999 1000 1001 1002 1003 1004
		if (ret)
			break;
	}

out_add_root:
	btrfs_release_path(path);
	ret = add_qgroup_item(trans, quota_root, BTRFS_FS_TREE_OBJECTID);
1005 1006
	if (ret) {
		btrfs_abort_transaction(trans, ret);
1007
		goto out_free_path;
1008
	}
1009 1010 1011 1012

	qgroup = add_qgroup_rb(fs_info, BTRFS_FS_TREE_OBJECTID);
	if (IS_ERR(qgroup)) {
		ret = PTR_ERR(qgroup);
1013
		btrfs_abort_transaction(trans, ret);
1014 1015
		goto out_free_path;
	}
1016
	spin_lock(&fs_info->qgroup_lock);
1017
	fs_info->quota_root = quota_root;
1018
	set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1019
	spin_unlock(&fs_info->qgroup_lock);
1020 1021

	ret = btrfs_commit_transaction(trans);
1022 1023
	trans = NULL;
	if (ret)
1024 1025
		goto out_free_path;

1026 1027 1028 1029 1030 1031 1032
	ret = qgroup_rescan_init(fs_info, 0, 1);
	if (!ret) {
	        qgroup_rescan_zero_tracking(fs_info);
	        btrfs_queue_work(fs_info->qgroup_rescan_workers,
	                         &fs_info->qgroup_rescan_work);
	}

1033
out_free_path:
1034
	btrfs_free_path(path);
1035 1036 1037 1038 1039 1040 1041
out_free_root:
	if (ret) {
		free_extent_buffer(quota_root->node);
		free_extent_buffer(quota_root->commit_root);
		kfree(quota_root);
	}
out:
1042
	if (ret) {
1043
		ulist_free(fs_info->qgroup_ulist);
1044
		fs_info->qgroup_ulist = NULL;
1045 1046
		if (trans)
			btrfs_end_transaction(trans);
1047
	}
1048
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1049 1050 1051
	return ret;
}

1052
int btrfs_quota_disable(struct btrfs_fs_info *fs_info)
1053 1054
{
	struct btrfs_root *quota_root;
1055
	struct btrfs_trans_handle *trans = NULL;
1056 1057
	int ret = 0;

1058
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1059
	if (!fs_info->quota_root)
1060
		goto out;
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

	/*
	 * 1 For the root item
	 *
	 * We should also reserve enough items for the quota tree deletion in
	 * btrfs_clean_quota_tree but this is not done.
	 */
	trans = btrfs_start_transaction(fs_info->tree_root, 1);
	if (IS_ERR(trans)) {
		ret = PTR_ERR(trans);
		goto out;
	}

1074
	clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
1075
	btrfs_qgroup_wait_for_completion(fs_info, false);
1076
	spin_lock(&fs_info->qgroup_lock);
1077 1078
	quota_root = fs_info->quota_root;
	fs_info->quota_root = NULL;
1079
	fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1080 1081
	spin_unlock(&fs_info->qgroup_lock);

1082 1083
	btrfs_free_qgroup_config(fs_info);

1084
	ret = btrfs_clean_quota_tree(trans, quota_root);
1085 1086 1087 1088
	if (ret) {
		btrfs_abort_transaction(trans, ret);
		goto end_trans;
	}
1089

1090
	ret = btrfs_del_root(trans, &quota_root->root_key);
1091 1092 1093 1094
	if (ret) {
		btrfs_abort_transaction(trans, ret);
		goto end_trans;
	}
1095 1096 1097 1098

	list_del(&quota_root->dirty_list);

	btrfs_tree_lock(quota_root->node);
1099
	clean_tree_block(fs_info, quota_root->node);
1100 1101 1102 1103 1104 1105
	btrfs_tree_unlock(quota_root->node);
	btrfs_free_tree_block(trans, quota_root, quota_root->node, 0, 1);

	free_extent_buffer(quota_root->node);
	free_extent_buffer(quota_root->commit_root);
	kfree(quota_root);
1106 1107 1108

end_trans:
	ret = btrfs_end_transaction(trans);
1109
out:
1110
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1111 1112 1113
	return ret;
}

J
Jan Schmidt 已提交
1114 1115
static void qgroup_dirty(struct btrfs_fs_info *fs_info,
			 struct btrfs_qgroup *qgroup)
1116
{
J
Jan Schmidt 已提交
1117 1118
	if (list_empty(&qgroup->dirty))
		list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1119 1120
}

1121
/*
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
 * The easy accounting, we're updating qgroup relationship whose child qgroup
 * only has exclusive extents.
 *
 * In this case, all exclsuive extents will also be exlusive for parent, so
 * excl/rfer just get added/removed.
 *
 * So is qgroup reservation space, which should also be added/removed to
 * parent.
 * Or when child tries to release reservation space, parent will underflow its
 * reservation (for relationship adding case).
1132 1133 1134 1135 1136
 *
 * Caller should hold fs_info->qgroup_lock.
 */
static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
				    struct ulist *tmp, u64 ref_root,
1137
				    struct btrfs_qgroup *src, int sign)
1138 1139 1140 1141 1142
{
	struct btrfs_qgroup *qgroup;
	struct btrfs_qgroup_list *glist;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
1143
	u64 num_bytes = src->excl;
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
	int ret = 0;

	qgroup = find_qgroup_rb(fs_info, ref_root);
	if (!qgroup)
		goto out;

	qgroup->rfer += sign * num_bytes;
	qgroup->rfer_cmpr += sign * num_bytes;

	WARN_ON(sign < 0 && qgroup->excl < num_bytes);
	qgroup->excl += sign * num_bytes;
	qgroup->excl_cmpr += sign * num_bytes;
1156 1157

	if (sign > 0)
1158
		qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1159
	else
1160
		qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1161 1162 1163 1164 1165 1166

	qgroup_dirty(fs_info, qgroup);

	/* Get all of the parent groups that contain this qgroup */
	list_for_each_entry(glist, &qgroup->groups, next_group) {
		ret = ulist_add(tmp, glist->group->qgroupid,
1167
				qgroup_to_aux(glist->group), GFP_ATOMIC);
1168 1169 1170 1171 1172 1173 1174
		if (ret < 0)
			goto out;
	}

	/* Iterate all of the parents and adjust their reference counts */
	ULIST_ITER_INIT(&uiter);
	while ((unode = ulist_next(tmp, &uiter))) {
1175
		qgroup = unode_aux_to_qgroup(unode);
1176 1177 1178 1179
		qgroup->rfer += sign * num_bytes;
		qgroup->rfer_cmpr += sign * num_bytes;
		WARN_ON(sign < 0 && qgroup->excl < num_bytes);
		qgroup->excl += sign * num_bytes;
1180
		if (sign > 0)
1181
			qgroup_rsv_add_by_qgroup(fs_info, qgroup, src);
1182
		else
1183
			qgroup_rsv_release_by_qgroup(fs_info, qgroup, src);
1184 1185 1186 1187 1188 1189
		qgroup->excl_cmpr += sign * num_bytes;
		qgroup_dirty(fs_info, qgroup);

		/* Add any parents of the parents */
		list_for_each_entry(glist, &qgroup->groups, next_group) {
			ret = ulist_add(tmp, glist->group->qgroupid,
1190
					qgroup_to_aux(glist->group), GFP_ATOMIC);
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
			if (ret < 0)
				goto out;
		}
	}
	ret = 0;
out:
	return ret;
}


/*
 * Quick path for updating qgroup with only excl refs.
 *
 * In that case, just update all parent will be enough.
 * Or we needs to do a full rescan.
 * Caller should also hold fs_info->qgroup_lock.
 *
 * Return 0 for quick update, return >0 for need to full rescan
 * and mark INCONSISTENT flag.
 * Return < 0 for other error.
 */
static int quick_update_accounting(struct btrfs_fs_info *fs_info,
				   struct ulist *tmp, u64 src, u64 dst,
				   int sign)
{
	struct btrfs_qgroup *qgroup;
	int ret = 1;
	int err = 0;

	qgroup = find_qgroup_rb(fs_info, src);
	if (!qgroup)
		goto out;
	if (qgroup->excl == qgroup->rfer) {
		ret = 0;
		err = __qgroup_excl_accounting(fs_info, tmp, dst,
1226
					       qgroup, sign);
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
		if (err < 0) {
			ret = err;
			goto out;
		}
	}
out:
	if (ret)
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	return ret;
}

1238 1239
int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
			      u64 dst)
1240
{
1241
	struct btrfs_fs_info *fs_info = trans->fs_info;
1242
	struct btrfs_root *quota_root;
1243 1244
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup *member;
1245
	struct btrfs_qgroup_list *list;
1246
	struct ulist *tmp;
1247 1248
	int ret = 0;

1249 1250 1251 1252
	/* Check the level of src and dst first */
	if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
		return -EINVAL;

1253
	tmp = ulist_alloc(GFP_KERNEL);
1254 1255 1256
	if (!tmp)
		return -ENOMEM;

1257
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1258
	quota_root = fs_info->quota_root;
1259 1260 1261 1262
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1263 1264 1265 1266 1267 1268
	member = find_qgroup_rb(fs_info, src);
	parent = find_qgroup_rb(fs_info, dst);
	if (!member || !parent) {
		ret = -EINVAL;
		goto out;
	}
1269

1270 1271 1272 1273 1274 1275 1276 1277
	/* check if such qgroup relation exist firstly */
	list_for_each_entry(list, &member->groups, next_group) {
		if (list->group == parent) {
			ret = -EEXIST;
			goto out;
		}
	}

1278
	ret = add_qgroup_relation_item(trans, src, dst);
1279
	if (ret)
1280
		goto out;
1281

1282
	ret = add_qgroup_relation_item(trans, dst, src);
1283
	if (ret) {
1284
		del_qgroup_relation_item(trans, src, dst);
1285
		goto out;
1286 1287 1288
	}

	spin_lock(&fs_info->qgroup_lock);
1289
	ret = add_relation_rb(fs_info, src, dst);
1290 1291 1292 1293 1294
	if (ret < 0) {
		spin_unlock(&fs_info->qgroup_lock);
		goto out;
	}
	ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1295
	spin_unlock(&fs_info->qgroup_lock);
1296 1297
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1298
	ulist_free(tmp);
1299 1300 1301
	return ret;
}

1302 1303
static int __del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
				 u64 dst)
1304
{
1305
	struct btrfs_fs_info *fs_info = trans->fs_info;
1306
	struct btrfs_root *quota_root;
1307 1308 1309
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup *member;
	struct btrfs_qgroup_list *list;
1310
	struct ulist *tmp;
1311 1312 1313
	int ret = 0;
	int err;

1314
	tmp = ulist_alloc(GFP_KERNEL);
1315 1316 1317
	if (!tmp)
		return -ENOMEM;

1318
	quota_root = fs_info->quota_root;
1319 1320 1321 1322
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1323

1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
	member = find_qgroup_rb(fs_info, src);
	parent = find_qgroup_rb(fs_info, dst);
	if (!member || !parent) {
		ret = -EINVAL;
		goto out;
	}

	/* check if such qgroup relation exist firstly */
	list_for_each_entry(list, &member->groups, next_group) {
		if (list->group == parent)
			goto exist;
	}
	ret = -ENOENT;
	goto out;
exist:
1339 1340
	ret = del_qgroup_relation_item(trans, src, dst);
	err = del_qgroup_relation_item(trans, dst, src);
1341 1342 1343 1344 1345
	if (err && !ret)
		ret = err;

	spin_lock(&fs_info->qgroup_lock);
	del_relation_rb(fs_info, src, dst);
1346
	ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1347
	spin_unlock(&fs_info->qgroup_lock);
1348
out:
1349
	ulist_free(tmp);
1350 1351 1352
	return ret;
}

1353 1354
int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans, u64 src,
			      u64 dst)
1355
{
1356
	struct btrfs_fs_info *fs_info = trans->fs_info;
1357 1358 1359
	int ret = 0;

	mutex_lock(&fs_info->qgroup_ioctl_lock);
1360
	ret = __del_qgroup_relation(trans, src, dst);
1361
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1362

1363 1364 1365
	return ret;
}

1366
int btrfs_create_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1367
{
1368
	struct btrfs_fs_info *fs_info = trans->fs_info;
1369 1370 1371 1372
	struct btrfs_root *quota_root;
	struct btrfs_qgroup *qgroup;
	int ret = 0;

1373
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1374
	quota_root = fs_info->quota_root;
1375 1376 1377 1378
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1379 1380 1381 1382 1383
	qgroup = find_qgroup_rb(fs_info, qgroupid);
	if (qgroup) {
		ret = -EEXIST;
		goto out;
	}
1384 1385

	ret = add_qgroup_item(trans, quota_root, qgroupid);
1386 1387
	if (ret)
		goto out;
1388 1389 1390 1391 1392 1393 1394

	spin_lock(&fs_info->qgroup_lock);
	qgroup = add_qgroup_rb(fs_info, qgroupid);
	spin_unlock(&fs_info->qgroup_lock);

	if (IS_ERR(qgroup))
		ret = PTR_ERR(qgroup);
1395 1396
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1397 1398 1399
	return ret;
}

1400
int btrfs_remove_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid)
1401
{
1402
	struct btrfs_fs_info *fs_info = trans->fs_info;
1403
	struct btrfs_root *quota_root;
1404
	struct btrfs_qgroup *qgroup;
1405
	struct btrfs_qgroup_list *list;
1406 1407
	int ret = 0;

1408
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1409
	quota_root = fs_info->quota_root;
1410 1411 1412 1413
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1414

1415
	qgroup = find_qgroup_rb(fs_info, qgroupid);
1416 1417 1418 1419
	if (!qgroup) {
		ret = -ENOENT;
		goto out;
	} else {
1420 1421
		/* check if there are no children of this qgroup */
		if (!list_empty(&qgroup->members)) {
1422 1423
			ret = -EBUSY;
			goto out;
1424 1425
		}
	}
1426
	ret = del_qgroup_item(trans, qgroupid);
1427 1428
	if (ret && ret != -ENOENT)
		goto out;
1429

1430 1431 1432
	while (!list_empty(&qgroup->groups)) {
		list = list_first_entry(&qgroup->groups,
					struct btrfs_qgroup_list, next_group);
1433 1434
		ret = __del_qgroup_relation(trans, qgroupid,
					    list->group->qgroupid);
1435 1436 1437 1438
		if (ret)
			goto out;
	}

1439
	spin_lock(&fs_info->qgroup_lock);
1440
	del_qgroup_rb(fs_info, qgroupid);
1441
	spin_unlock(&fs_info->qgroup_lock);
1442 1443
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1444 1445 1446
	return ret;
}

1447
int btrfs_limit_qgroup(struct btrfs_trans_handle *trans, u64 qgroupid,
1448 1449
		       struct btrfs_qgroup_limit *limit)
{
1450
	struct btrfs_fs_info *fs_info = trans->fs_info;
1451
	struct btrfs_root *quota_root;
1452 1453
	struct btrfs_qgroup *qgroup;
	int ret = 0;
1454 1455 1456 1457 1458
	/* Sometimes we would want to clear the limit on this qgroup.
	 * To meet this requirement, we treat the -1 as a special value
	 * which tell kernel to clear the limit on this qgroup.
	 */
	const u64 CLEAR_VALUE = -1;
1459

1460 1461 1462 1463 1464 1465
	mutex_lock(&fs_info->qgroup_ioctl_lock);
	quota_root = fs_info->quota_root;
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1466

1467 1468 1469 1470 1471
	qgroup = find_qgroup_rb(fs_info, qgroupid);
	if (!qgroup) {
		ret = -ENOENT;
		goto out;
	}
1472

1473
	spin_lock(&fs_info->qgroup_lock);
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_RFER) {
		if (limit->max_rfer == CLEAR_VALUE) {
			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_RFER;
			qgroup->max_rfer = 0;
		} else {
			qgroup->max_rfer = limit->max_rfer;
		}
	}
	if (limit->flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) {
		if (limit->max_excl == CLEAR_VALUE) {
			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
			limit->flags &= ~BTRFS_QGROUP_LIMIT_MAX_EXCL;
			qgroup->max_excl = 0;
		} else {
			qgroup->max_excl = limit->max_excl;
		}
	}
	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_RFER) {
		if (limit->rsv_rfer == CLEAR_VALUE) {
			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_RFER;
			qgroup->rsv_rfer = 0;
		} else {
			qgroup->rsv_rfer = limit->rsv_rfer;
		}
	}
	if (limit->flags & BTRFS_QGROUP_LIMIT_RSV_EXCL) {
		if (limit->rsv_excl == CLEAR_VALUE) {
			qgroup->lim_flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
			limit->flags &= ~BTRFS_QGROUP_LIMIT_RSV_EXCL;
			qgroup->rsv_excl = 0;
		} else {
			qgroup->rsv_excl = limit->rsv_excl;
		}
	}
1510 1511
	qgroup->lim_flags |= limit->flags;

1512
	spin_unlock(&fs_info->qgroup_lock);
1513

1514
	ret = update_qgroup_limit_item(trans, qgroup);
1515 1516 1517 1518 1519 1520
	if (ret) {
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		btrfs_info(fs_info, "unable to update quota limit for %llu",
		       qgroupid);
	}

1521 1522
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1523 1524
	return ret;
}
1525

1526
int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1527 1528
				struct btrfs_delayed_ref_root *delayed_refs,
				struct btrfs_qgroup_extent_record *record)
1529 1530 1531 1532 1533 1534
{
	struct rb_node **p = &delayed_refs->dirty_extent_root.rb_node;
	struct rb_node *parent_node = NULL;
	struct btrfs_qgroup_extent_record *entry;
	u64 bytenr = record->bytenr;

1535
	lockdep_assert_held(&delayed_refs->lock);
1536
	trace_btrfs_qgroup_trace_extent(fs_info, record);
1537

1538 1539 1540 1541 1542 1543 1544 1545 1546
	while (*p) {
		parent_node = *p;
		entry = rb_entry(parent_node, struct btrfs_qgroup_extent_record,
				 node);
		if (bytenr < entry->bytenr)
			p = &(*p)->rb_left;
		else if (bytenr > entry->bytenr)
			p = &(*p)->rb_right;
		else
1547
			return 1;
1548 1549 1550 1551
	}

	rb_link_node(&record->node, parent_node, p);
	rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1552 1553 1554
	return 0;
}

1555 1556 1557 1558 1559 1560 1561
int btrfs_qgroup_trace_extent_post(struct btrfs_fs_info *fs_info,
				   struct btrfs_qgroup_extent_record *qrecord)
{
	struct ulist *old_root;
	u64 bytenr = qrecord->bytenr;
	int ret;

1562
	ret = btrfs_find_all_roots(NULL, fs_info, bytenr, 0, &old_root, false);
1563 1564 1565 1566 1567 1568 1569
	if (ret < 0) {
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		btrfs_warn(fs_info,
"error accounting new delayed refs extent (err code: %d), quota inconsistent",
			ret);
		return 0;
	}
1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581

	/*
	 * Here we don't need to get the lock of
	 * trans->transaction->delayed_refs, since inserted qrecord won't
	 * be deleted, only qrecord->node may be modified (new qrecord insert)
	 *
	 * So modifying qrecord->old_roots is safe here
	 */
	qrecord->old_roots = old_root;
	return 0;
}

1582 1583
int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans, u64 bytenr,
			      u64 num_bytes, gfp_t gfp_flag)
1584
{
1585
	struct btrfs_fs_info *fs_info = trans->fs_info;
1586 1587 1588 1589
	struct btrfs_qgroup_extent_record *record;
	struct btrfs_delayed_ref_root *delayed_refs;
	int ret;

1590 1591
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
	    || bytenr == 0 || num_bytes == 0)
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
		return 0;
	record = kmalloc(sizeof(*record), gfp_flag);
	if (!record)
		return -ENOMEM;

	delayed_refs = &trans->transaction->delayed_refs;
	record->bytenr = bytenr;
	record->num_bytes = num_bytes;
	record->old_roots = NULL;

	spin_lock(&delayed_refs->lock);
1603
	ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1604
	spin_unlock(&delayed_refs->lock);
1605
	if (ret > 0) {
1606
		kfree(record);
1607 1608 1609
		return 0;
	}
	return btrfs_qgroup_trace_extent_post(fs_info, record);
1610 1611
}

1612 1613 1614
int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
				  struct extent_buffer *eb)
{
1615
	struct btrfs_fs_info *fs_info = trans->fs_info;
1616 1617 1618 1619 1620 1621 1622
	int nr = btrfs_header_nritems(eb);
	int i, extent_type, ret;
	struct btrfs_key key;
	struct btrfs_file_extent_item *fi;
	u64 bytenr, num_bytes;

	/* We can be called directly from walk_up_proc() */
1623
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
		return 0;

	for (i = 0; i < nr; i++) {
		btrfs_item_key_to_cpu(eb, &key, i);

		if (key.type != BTRFS_EXTENT_DATA_KEY)
			continue;

		fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
		/* filter out non qgroup-accountable extents  */
		extent_type = btrfs_file_extent_type(eb, fi);

		if (extent_type == BTRFS_FILE_EXTENT_INLINE)
			continue;

		bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
		if (!bytenr)
			continue;

		num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);

1645 1646
		ret = btrfs_qgroup_trace_extent(trans, bytenr, num_bytes,
						GFP_NOFS);
1647 1648 1649
		if (ret)
			return ret;
	}
1650
	cond_resched();
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
	return 0;
}

/*
 * Walk up the tree from the bottom, freeing leaves and any interior
 * nodes which have had all slots visited. If a node (leaf or
 * interior) is freed, the node above it will have it's slot
 * incremented. The root node will never be freed.
 *
 * At the end of this function, we should have a path which has all
 * slots incremented to the next position for a search. If we need to
 * read a new node it will be NULL and the node above it will have the
 * correct slot selected for a later read.
 *
 * If we increment the root nodes slot counter past the number of
 * elements, 1 is returned to signal completion of the search.
 */
1668
static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
{
	int level = 0;
	int nr, slot;
	struct extent_buffer *eb;

	if (root_level == 0)
		return 1;

	while (level <= root_level) {
		eb = path->nodes[level];
		nr = btrfs_header_nritems(eb);
		path->slots[level]++;
		slot = path->slots[level];
		if (slot >= nr || level == 0) {
			/*
			 * Don't free the root -  we will detect this
			 * condition after our loop and return a
			 * positive value for caller to stop walking the tree.
			 */
			if (level != root_level) {
				btrfs_tree_unlock_rw(eb, path->locks[level]);
				path->locks[level] = 0;

				free_extent_buffer(eb);
				path->nodes[level] = NULL;
				path->slots[level] = 0;
			}
		} else {
			/*
			 * We have a valid slot to walk back down
			 * from. Stop here so caller can process these
			 * new nodes.
			 */
			break;
		}

		level++;
	}

	eb = path->nodes[root_level];
	if (path->slots[root_level] >= btrfs_header_nritems(eb))
		return 1;

	return 0;
}

1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
/*
 * Helper function to trace a subtree tree block swap.
 *
 * The swap will happen in highest tree block, but there may be a lot of
 * tree blocks involved.
 *
 * For example:
 *  OO = Old tree blocks
 *  NN = New tree blocks allocated during balance
 *
 *           File tree (257)                  Reloc tree for 257
 * L2              OO                                NN
 *               /    \                            /    \
 * L1          OO      OO (a)                    OO      NN (a)
 *            / \     / \                       / \     / \
 * L0       OO   OO OO   OO                   OO   OO NN   NN
 *                  (b)  (c)                          (b)  (c)
 *
 * When calling qgroup_trace_extent_swap(), we will pass:
 * @src_eb = OO(a)
 * @dst_path = [ nodes[1] = NN(a), nodes[0] = NN(c) ]
 * @dst_level = 0
 * @root_level = 1
 *
 * In that case, qgroup_trace_extent_swap() will search from OO(a) to
 * reach OO(c), then mark both OO(c) and NN(c) as qgroup dirty.
 *
 * The main work of qgroup_trace_extent_swap() can be split into 3 parts:
 *
 * 1) Tree search from @src_eb
 *    It should acts as a simplified btrfs_search_slot().
 *    The key for search can be extracted from @dst_path->nodes[dst_level]
 *    (first key).
 *
 * 2) Mark the final tree blocks in @src_path and @dst_path qgroup dirty
 *    NOTE: In above case, OO(a) and NN(a) won't be marked qgroup dirty.
 *    They should be marked during preivous (@dst_level = 1) iteration.
 *
 * 3) Mark file extents in leaves dirty
 *    We don't have good way to pick out new file extents only.
 *    So we still follow the old method by scanning all file extents in
 *    the leave.
 *
 * This function can free us from keeping two pathes, thus later we only need
 * to care about how to iterate all new tree blocks in reloc tree.
 */
static int 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)
{
	struct btrfs_key key;
	struct btrfs_path *src_path;
	struct btrfs_fs_info *fs_info = trans->fs_info;
	u32 nodesize = fs_info->nodesize;
	int cur_level = root_level;
	int ret;

	BUG_ON(dst_level > root_level);
	/* Level mismatch */
	if (btrfs_header_level(src_eb) != root_level)
		return -EINVAL;

	src_path = btrfs_alloc_path();
	if (!src_path) {
		ret = -ENOMEM;
		goto out;
	}

	if (dst_level)
		btrfs_node_key_to_cpu(dst_path->nodes[dst_level], &key, 0);
	else
		btrfs_item_key_to_cpu(dst_path->nodes[dst_level], &key, 0);

	/* For src_path */
	extent_buffer_get(src_eb);
	src_path->nodes[root_level] = src_eb;
	src_path->slots[root_level] = dst_path->slots[root_level];
	src_path->locks[root_level] = 0;

	/* A simplified version of btrfs_search_slot() */
	while (cur_level >= dst_level) {
		struct btrfs_key src_key;
		struct btrfs_key dst_key;

		if (src_path->nodes[cur_level] == NULL) {
			struct btrfs_key first_key;
			struct extent_buffer *eb;
			int parent_slot;
			u64 child_gen;
			u64 child_bytenr;

			eb = src_path->nodes[cur_level + 1];
			parent_slot = src_path->slots[cur_level + 1];
			child_bytenr = btrfs_node_blockptr(eb, parent_slot);
			child_gen = btrfs_node_ptr_generation(eb, parent_slot);
			btrfs_node_key_to_cpu(eb, &first_key, parent_slot);

			eb = read_tree_block(fs_info, child_bytenr, child_gen,
					     cur_level, &first_key);
			if (IS_ERR(eb)) {
				ret = PTR_ERR(eb);
				goto out;
			} else if (!extent_buffer_uptodate(eb)) {
				free_extent_buffer(eb);
				ret = -EIO;
				goto out;
			}

			src_path->nodes[cur_level] = eb;

			btrfs_tree_read_lock(eb);
			btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
			src_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
		}

		src_path->slots[cur_level] = dst_path->slots[cur_level];
		if (cur_level) {
			btrfs_node_key_to_cpu(dst_path->nodes[cur_level],
					&dst_key, dst_path->slots[cur_level]);
			btrfs_node_key_to_cpu(src_path->nodes[cur_level],
					&src_key, src_path->slots[cur_level]);
		} else {
			btrfs_item_key_to_cpu(dst_path->nodes[cur_level],
					&dst_key, dst_path->slots[cur_level]);
			btrfs_item_key_to_cpu(src_path->nodes[cur_level],
					&src_key, src_path->slots[cur_level]);
		}
		/* Content mismatch, something went wrong */
		if (btrfs_comp_cpu_keys(&dst_key, &src_key)) {
			ret = -ENOENT;
			goto out;
		}
		cur_level--;
	}

	/*
	 * Now both @dst_path and @src_path have been populated, record the tree
	 * blocks for qgroup accounting.
	 */
	ret = btrfs_qgroup_trace_extent(trans, src_path->nodes[dst_level]->start,
			nodesize, GFP_NOFS);
	if (ret < 0)
		goto out;
	ret = btrfs_qgroup_trace_extent(trans,
			dst_path->nodes[dst_level]->start,
			nodesize, GFP_NOFS);
	if (ret < 0)
		goto out;

	/* Record leaf file extents */
	if (dst_level == 0) {
		ret = btrfs_qgroup_trace_leaf_items(trans, src_path->nodes[0]);
		if (ret < 0)
			goto out;
		ret = btrfs_qgroup_trace_leaf_items(trans, dst_path->nodes[0]);
	}
out:
	btrfs_free_path(src_path);
	return ret;
}

1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
/*
 * Helper function to do recursive generation-aware depth-first search, to
 * locate all new tree blocks in a subtree of reloc tree.
 *
 * E.g. (OO = Old tree blocks, NN = New tree blocks, whose gen == last_snapshot)
 *         reloc tree
 * L2         NN (a)
 *          /    \
 * L1    OO        NN (b)
 *      /  \      /  \
 * L0  OO  OO    OO  NN
 *               (c) (d)
 * If we pass:
 * @dst_path = [ nodes[1] = NN(b), nodes[0] = NULL ],
 * @cur_level = 1
 * @root_level = 1
 *
 * We will iterate through tree blocks NN(b), NN(d) and info qgroup to trace
 * above tree blocks along with their counter parts in file tree.
 * While during search, old tree blocsk OO(c) will be skiped as tree block swap
 * won't affect OO(c).
 */
static int 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)
{
	struct btrfs_fs_info *fs_info = trans->fs_info;
	struct extent_buffer *eb;
	bool need_cleanup = false;
	int ret = 0;
	int i;

	/* Level sanity check */
	if (cur_level < 0 || cur_level >= BTRFS_MAX_LEVEL ||
	    root_level < 0 || root_level >= BTRFS_MAX_LEVEL ||
	    root_level < cur_level) {
		btrfs_err_rl(fs_info,
			"%s: bad levels, cur_level=%d root_level=%d",
			__func__, cur_level, root_level);
		return -EUCLEAN;
	}

	/* Read the tree block if needed */
	if (dst_path->nodes[cur_level] == NULL) {
		struct btrfs_key first_key;
		int parent_slot;
		u64 child_gen;
		u64 child_bytenr;

		/*
		 * dst_path->nodes[root_level] must be initialized before
		 * calling this function.
		 */
		if (cur_level == root_level) {
			btrfs_err_rl(fs_info,
	"%s: dst_path->nodes[%d] not initialized, root_level=%d cur_level=%d",
				__func__, root_level, root_level, cur_level);
			return -EUCLEAN;
		}

		/*
		 * We need to get child blockptr/gen from parent before we can
		 * read it.
		  */
		eb = dst_path->nodes[cur_level + 1];
		parent_slot = dst_path->slots[cur_level + 1];
		child_bytenr = btrfs_node_blockptr(eb, parent_slot);
		child_gen = btrfs_node_ptr_generation(eb, parent_slot);
		btrfs_node_key_to_cpu(eb, &first_key, parent_slot);

		/* This node is old, no need to trace */
		if (child_gen < last_snapshot)
			goto out;

		eb = read_tree_block(fs_info, child_bytenr, child_gen,
				     cur_level, &first_key);
		if (IS_ERR(eb)) {
			ret = PTR_ERR(eb);
			goto out;
		} else if (!extent_buffer_uptodate(eb)) {
			free_extent_buffer(eb);
			ret = -EIO;
			goto out;
		}

		dst_path->nodes[cur_level] = eb;
		dst_path->slots[cur_level] = 0;

		btrfs_tree_read_lock(eb);
		btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
		dst_path->locks[cur_level] = BTRFS_READ_LOCK_BLOCKING;
		need_cleanup = true;
	}

	/* Now record this tree block and its counter part for qgroups */
	ret = qgroup_trace_extent_swap(trans, src_eb, dst_path, cur_level,
				       root_level);
	if (ret < 0)
		goto cleanup;

	eb = dst_path->nodes[cur_level];

	if (cur_level > 0) {
		/* Iterate all child tree blocks */
		for (i = 0; i < btrfs_header_nritems(eb); i++) {
			/* Skip old tree blocks as they won't be swapped */
			if (btrfs_node_ptr_generation(eb, i) < last_snapshot)
				continue;
			dst_path->slots[cur_level] = i;

			/* Recursive call (at most 7 times) */
			ret = qgroup_trace_new_subtree_blocks(trans, src_eb,
					dst_path, cur_level - 1, root_level,
					last_snapshot);
			if (ret < 0)
				goto cleanup;
		}
	}

cleanup:
	if (need_cleanup) {
		/* Clean up */
		btrfs_tree_unlock_rw(dst_path->nodes[cur_level],
				     dst_path->locks[cur_level]);
		free_extent_buffer(dst_path->nodes[cur_level]);
		dst_path->nodes[cur_level] = NULL;
		dst_path->slots[cur_level] = 0;
		dst_path->locks[cur_level] = 0;
	}
out:
	return ret;
}

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
/*
 * Inform qgroup to trace subtree swap used in balance.
 *
 * Unlike btrfs_qgroup_trace_subtree(), this function will only trace
 * new tree blocks whose generation is equal to (or larger than) @last_snapshot.
 *
 * Will go down the tree block pointed by @dst_eb (pointed by @dst_parent and
 * @dst_slot), and find any tree blocks whose generation is at @last_snapshot,
 * and then go down @src_eb (pointed by @src_parent and @src_slot) to find
 * the conterpart of the tree block, then mark both tree blocks as qgroup dirty,
 * and skip all tree blocks whose generation is smaller than last_snapshot.
 *
 * This would skip tons of tree blocks of original btrfs_qgroup_trace_subtree(),
 * which could be the cause of very slow balance if the file tree is large.
 *
 * @src_parent, @src_slot: pointer to src (file tree) eb.
 * @dst_parent, @dst_slot: pointer to dst (reloc tree) eb.
 */
int btrfs_qgroup_trace_subtree_swap(struct btrfs_trans_handle *trans,
				struct extent_buffer *src_parent, int src_slot,
				struct extent_buffer *dst_parent, int dst_slot,
				u64 last_snapshot)
{
	struct btrfs_fs_info *fs_info = trans->fs_info;
	struct btrfs_path *dst_path = NULL;
	struct btrfs_key first_key;
	struct extent_buffer *src_eb = NULL;
	struct extent_buffer *dst_eb = NULL;
	u64 child_gen;
	u64 child_bytenr;
	int level;
	int ret;

	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
		return 0;

	/* Check parameter order */
	if (btrfs_node_ptr_generation(src_parent, src_slot) >
	    btrfs_node_ptr_generation(dst_parent, dst_slot)) {
		btrfs_err_rl(fs_info,
		"%s: bad parameter order, src_gen=%llu dst_gen=%llu", __func__,
			btrfs_node_ptr_generation(src_parent, src_slot),
			btrfs_node_ptr_generation(dst_parent, dst_slot));
		return -EUCLEAN;
	}

	/* Read out real @src_eb, pointed by @src_parent and @src_slot */
	child_bytenr = btrfs_node_blockptr(src_parent, src_slot);
	child_gen = btrfs_node_ptr_generation(src_parent, src_slot);
	btrfs_node_key_to_cpu(src_parent, &first_key, src_slot);

	src_eb = read_tree_block(fs_info, child_bytenr, child_gen,
			btrfs_header_level(src_parent) - 1, &first_key);
	if (IS_ERR(src_eb)) {
		ret = PTR_ERR(src_eb);
		goto out;
	}

	/* Read out real @dst_eb, pointed by @src_parent and @src_slot */
	child_bytenr = btrfs_node_blockptr(dst_parent, dst_slot);
	child_gen = btrfs_node_ptr_generation(dst_parent, dst_slot);
	btrfs_node_key_to_cpu(dst_parent, &first_key, dst_slot);

	dst_eb = read_tree_block(fs_info, child_bytenr, child_gen,
			btrfs_header_level(dst_parent) - 1, &first_key);
	if (IS_ERR(dst_eb)) {
		ret = PTR_ERR(dst_eb);
		goto out;
	}

	if (!extent_buffer_uptodate(src_eb) || !extent_buffer_uptodate(dst_eb)) {
		ret = -EINVAL;
		goto out;
	}

	level = btrfs_header_level(dst_eb);
	dst_path = btrfs_alloc_path();
	if (!dst_path) {
		ret = -ENOMEM;
		goto out;
	}

	/* For dst_path */
	extent_buffer_get(dst_eb);
	dst_path->nodes[level] = dst_eb;
	dst_path->slots[level] = 0;
	dst_path->locks[level] = 0;

	/* Do the generation-aware breadth-first search */
	ret = qgroup_trace_new_subtree_blocks(trans, src_eb, dst_path, level,
					      level, last_snapshot);
	if (ret < 0)
		goto out;
	ret = 0;

out:
	free_extent_buffer(src_eb);
	free_extent_buffer(dst_eb);
	btrfs_free_path(dst_path);
	if (ret < 0)
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	return ret;
}

2116 2117 2118 2119
int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
			       struct extent_buffer *root_eb,
			       u64 root_gen, int root_level)
{
2120
	struct btrfs_fs_info *fs_info = trans->fs_info;
2121 2122 2123 2124 2125
	int ret = 0;
	int level;
	struct extent_buffer *eb = root_eb;
	struct btrfs_path *path = NULL;

2126
	BUG_ON(root_level < 0 || root_level >= BTRFS_MAX_LEVEL);
2127 2128
	BUG_ON(root_eb == NULL);

2129
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2130 2131 2132
		return 0;

	if (!extent_buffer_uptodate(root_eb)) {
2133
		ret = btrfs_read_buffer(root_eb, root_gen, root_level, NULL);
2134 2135 2136 2137 2138
		if (ret)
			goto out;
	}

	if (root_level == 0) {
2139
		ret = btrfs_qgroup_trace_leaf_items(trans, root_eb);
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
		goto out;
	}

	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

	/*
	 * Walk down the tree.  Missing extent blocks are filled in as
	 * we go. Metadata is accounted every time we read a new
	 * extent block.
	 *
	 * When we reach a leaf, we account for file extent items in it,
	 * walk back up the tree (adjusting slot pointers as we go)
	 * and restart the search process.
	 */
	extent_buffer_get(root_eb); /* For path */
	path->nodes[root_level] = root_eb;
	path->slots[root_level] = 0;
	path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
walk_down:
	level = root_level;
	while (level >= 0) {
		if (path->nodes[level] == NULL) {
2164
			struct btrfs_key first_key;
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
			int parent_slot;
			u64 child_gen;
			u64 child_bytenr;

			/*
			 * We need to get child blockptr/gen from parent before
			 * we can read it.
			  */
			eb = path->nodes[level + 1];
			parent_slot = path->slots[level + 1];
			child_bytenr = btrfs_node_blockptr(eb, parent_slot);
			child_gen = btrfs_node_ptr_generation(eb, parent_slot);
2177
			btrfs_node_key_to_cpu(eb, &first_key, parent_slot);
2178

2179 2180
			eb = read_tree_block(fs_info, child_bytenr, child_gen,
					     level, &first_key);
2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196
			if (IS_ERR(eb)) {
				ret = PTR_ERR(eb);
				goto out;
			} else if (!extent_buffer_uptodate(eb)) {
				free_extent_buffer(eb);
				ret = -EIO;
				goto out;
			}

			path->nodes[level] = eb;
			path->slots[level] = 0;

			btrfs_tree_read_lock(eb);
			btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
			path->locks[level] = BTRFS_READ_LOCK_BLOCKING;

2197
			ret = btrfs_qgroup_trace_extent(trans, child_bytenr,
2198 2199
							fs_info->nodesize,
							GFP_NOFS);
2200 2201 2202 2203 2204
			if (ret)
				goto out;
		}

		if (level == 0) {
2205 2206
			ret = btrfs_qgroup_trace_leaf_items(trans,
							    path->nodes[level]);
2207 2208 2209 2210
			if (ret)
				goto out;

			/* Nonzero return here means we completed our search */
2211
			ret = adjust_slots_upwards(path, root_level);
2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
			if (ret)
				break;

			/* Restart search with new slots */
			goto walk_down;
		}

		level--;
	}

	ret = 0;
out:
	btrfs_free_path(path);

	return ret;
}

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
#define UPDATE_NEW	0
#define UPDATE_OLD	1
/*
 * Walk all of the roots that points to the bytenr and adjust their refcnts.
 */
static int qgroup_update_refcnt(struct btrfs_fs_info *fs_info,
				struct ulist *roots, struct ulist *tmp,
				struct ulist *qgroups, u64 seq, int update_old)
{
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	struct ulist_node *tmp_unode;
	struct ulist_iterator tmp_uiter;
	struct btrfs_qgroup *qg;
	int ret = 0;

	if (!roots)
		return 0;
	ULIST_ITER_INIT(&uiter);
	while ((unode = ulist_next(roots, &uiter))) {
		qg = find_qgroup_rb(fs_info, unode->val);
		if (!qg)
			continue;

		ulist_reinit(tmp);
2254
		ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
2255 2256 2257
				GFP_ATOMIC);
		if (ret < 0)
			return ret;
2258
		ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
2259 2260 2261 2262 2263 2264
		if (ret < 0)
			return ret;
		ULIST_ITER_INIT(&tmp_uiter);
		while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
			struct btrfs_qgroup_list *glist;

2265
			qg = unode_aux_to_qgroup(tmp_unode);
2266 2267 2268 2269 2270 2271
			if (update_old)
				btrfs_qgroup_update_old_refcnt(qg, seq, 1);
			else
				btrfs_qgroup_update_new_refcnt(qg, seq, 1);
			list_for_each_entry(glist, &qg->groups, next_group) {
				ret = ulist_add(qgroups, glist->group->qgroupid,
2272
						qgroup_to_aux(glist->group),
2273 2274 2275 2276
						GFP_ATOMIC);
				if (ret < 0)
					return ret;
				ret = ulist_add(tmp, glist->group->qgroupid,
2277
						qgroup_to_aux(glist->group),
2278 2279 2280 2281 2282 2283 2284 2285 2286
						GFP_ATOMIC);
				if (ret < 0)
					return ret;
			}
		}
	}
	return 0;
}

2287 2288 2289
/*
 * Update qgroup rfer/excl counters.
 * Rfer update is easy, codes can explain themselves.
2290
 *
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
 * Excl update is tricky, the update is split into 2 part.
 * Part 1: Possible exclusive <-> sharing detect:
 *	|	A	|	!A	|
 *  -------------------------------------
 *  B	|	*	|	-	|
 *  -------------------------------------
 *  !B	|	+	|	**	|
 *  -------------------------------------
 *
 * Conditions:
 * A:	cur_old_roots < nr_old_roots	(not exclusive before)
 * !A:	cur_old_roots == nr_old_roots	(possible exclusive before)
 * B:	cur_new_roots < nr_new_roots	(not exclusive now)
2304
 * !B:	cur_new_roots == nr_new_roots	(possible exclusive now)
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337
 *
 * Results:
 * +: Possible sharing -> exclusive	-: Possible exclusive -> sharing
 * *: Definitely not changed.		**: Possible unchanged.
 *
 * For !A and !B condition, the exception is cur_old/new_roots == 0 case.
 *
 * To make the logic clear, we first use condition A and B to split
 * combination into 4 results.
 *
 * Then, for result "+" and "-", check old/new_roots == 0 case, as in them
 * only on variant maybe 0.
 *
 * Lastly, check result **, since there are 2 variants maybe 0, split them
 * again(2x2).
 * But this time we don't need to consider other things, the codes and logic
 * is easy to understand now.
 */
static int 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)
{
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	struct btrfs_qgroup *qg;
	u64 cur_new_count, cur_old_count;

	ULIST_ITER_INIT(&uiter);
	while ((unode = ulist_next(qgroups, &uiter))) {
		bool dirty = false;

2338
		qg = unode_aux_to_qgroup(unode);
2339 2340 2341
		cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
		cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);

2342 2343
		trace_qgroup_update_counters(fs_info, qg, cur_old_count,
					     cur_new_count);
M
Mark Fasheh 已提交
2344

2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
		/* Rfer update part */
		if (cur_old_count == 0 && cur_new_count > 0) {
			qg->rfer += num_bytes;
			qg->rfer_cmpr += num_bytes;
			dirty = true;
		}
		if (cur_old_count > 0 && cur_new_count == 0) {
			qg->rfer -= num_bytes;
			qg->rfer_cmpr -= num_bytes;
			dirty = true;
		}

		/* Excl update part */
		/* Exclusive/none -> shared case */
		if (cur_old_count == nr_old_roots &&
		    cur_new_count < nr_new_roots) {
			/* Exclusive -> shared */
			if (cur_old_count != 0) {
				qg->excl -= num_bytes;
				qg->excl_cmpr -= num_bytes;
				dirty = true;
			}
		}

		/* Shared -> exclusive/none case */
		if (cur_old_count < nr_old_roots &&
		    cur_new_count == nr_new_roots) {
			/* Shared->exclusive */
			if (cur_new_count != 0) {
				qg->excl += num_bytes;
				qg->excl_cmpr += num_bytes;
				dirty = true;
			}
		}

		/* Exclusive/none -> exclusive/none case */
		if (cur_old_count == nr_old_roots &&
		    cur_new_count == nr_new_roots) {
			if (cur_old_count == 0) {
				/* None -> exclusive/none */

				if (cur_new_count != 0) {
					/* None -> exclusive */
					qg->excl += num_bytes;
					qg->excl_cmpr += num_bytes;
					dirty = true;
				}
				/* None -> none, nothing changed */
			} else {
				/* Exclusive -> exclusive/none */

				if (cur_new_count == 0) {
					/* Exclusive -> none */
					qg->excl -= num_bytes;
					qg->excl_cmpr -= num_bytes;
					dirty = true;
				}
				/* Exclusive -> exclusive, nothing changed */
			}
		}
2405

2406 2407 2408 2409 2410 2411
		if (dirty)
			qgroup_dirty(fs_info, qg);
	}
	return 0;
}

2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
/*
 * Check if the @roots potentially is a list of fs tree roots
 *
 * Return 0 for definitely not a fs/subvol tree roots ulist
 * Return 1 for possible fs/subvol tree roots in the list (considering an empty
 *          one as well)
 */
static int maybe_fs_roots(struct ulist *roots)
{
	struct ulist_node *unode;
	struct ulist_iterator uiter;

	/* Empty one, still possible for fs roots */
	if (!roots || roots->nnodes == 0)
		return 1;

	ULIST_ITER_INIT(&uiter);
	unode = ulist_next(roots, &uiter);
	if (!unode)
		return 1;

	/*
	 * If it contains fs tree roots, then it must belong to fs/subvol
	 * trees.
	 * If it contains a non-fs tree, it won't be shared with fs/subvol trees.
	 */
	return is_fstree(unode->val);
}

2441 2442 2443
int btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans, u64 bytenr,
				u64 num_bytes, struct ulist *old_roots,
				struct ulist *new_roots)
2444
{
2445
	struct btrfs_fs_info *fs_info = trans->fs_info;
2446 2447 2448 2449 2450 2451 2452
	struct ulist *qgroups = NULL;
	struct ulist *tmp = NULL;
	u64 seq;
	u64 nr_new_roots = 0;
	u64 nr_old_roots = 0;
	int ret = 0;

2453 2454 2455
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
		return 0;

2456 2457 2458
	if (new_roots) {
		if (!maybe_fs_roots(new_roots))
			goto out_free;
2459
		nr_new_roots = new_roots->nnodes;
2460 2461 2462 2463
	}
	if (old_roots) {
		if (!maybe_fs_roots(old_roots))
			goto out_free;
2464
		nr_old_roots = old_roots->nnodes;
2465 2466 2467 2468 2469
	}

	/* Quick exit, either not fs tree roots, or won't affect any qgroup */
	if (nr_old_roots == 0 && nr_new_roots == 0)
		goto out_free;
2470 2471 2472

	BUG_ON(!fs_info->quota_root);

2473 2474
	trace_btrfs_qgroup_account_extent(fs_info, trans->transid, bytenr,
					num_bytes, nr_old_roots, nr_new_roots);
M
Mark Fasheh 已提交
2475

2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
	qgroups = ulist_alloc(GFP_NOFS);
	if (!qgroups) {
		ret = -ENOMEM;
		goto out_free;
	}
	tmp = ulist_alloc(GFP_NOFS);
	if (!tmp) {
		ret = -ENOMEM;
		goto out_free;
	}

	mutex_lock(&fs_info->qgroup_rescan_lock);
	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
		if (fs_info->qgroup_rescan_progress.objectid <= bytenr) {
			mutex_unlock(&fs_info->qgroup_rescan_lock);
			ret = 0;
			goto out_free;
		}
	}
	mutex_unlock(&fs_info->qgroup_rescan_lock);

	spin_lock(&fs_info->qgroup_lock);
	seq = fs_info->qgroup_seq;

	/* Update old refcnts using old_roots */
	ret = qgroup_update_refcnt(fs_info, old_roots, tmp, qgroups, seq,
				   UPDATE_OLD);
	if (ret < 0)
		goto out;

	/* Update new refcnts using new_roots */
	ret = qgroup_update_refcnt(fs_info, new_roots, tmp, qgroups, seq,
				   UPDATE_NEW);
	if (ret < 0)
		goto out;

	qgroup_update_counters(fs_info, qgroups, nr_old_roots, nr_new_roots,
			       num_bytes, seq);

	/*
	 * Bump qgroup_seq to avoid seq overlap
	 */
	fs_info->qgroup_seq += max(nr_old_roots, nr_new_roots) + 1;
out:
	spin_unlock(&fs_info->qgroup_lock);
out_free:
	ulist_free(tmp);
	ulist_free(qgroups);
	ulist_free(old_roots);
	ulist_free(new_roots);
	return ret;
}

2529
int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans)
2530
{
2531
	struct btrfs_fs_info *fs_info = trans->fs_info;
2532 2533 2534 2535
	struct btrfs_qgroup_extent_record *record;
	struct btrfs_delayed_ref_root *delayed_refs;
	struct ulist *new_roots = NULL;
	struct rb_node *node;
2536
	u64 num_dirty_extents = 0;
2537
	u64 qgroup_to_skip;
2538 2539 2540
	int ret = 0;

	delayed_refs = &trans->transaction->delayed_refs;
2541
	qgroup_to_skip = delayed_refs->qgroup_to_skip;
2542 2543 2544 2545
	while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
		record = rb_entry(node, struct btrfs_qgroup_extent_record,
				  node);

2546
		num_dirty_extents++;
2547
		trace_btrfs_qgroup_account_extents(fs_info, record);
M
Mark Fasheh 已提交
2548

2549
		if (!ret) {
2550 2551 2552 2553 2554 2555 2556 2557
			/*
			 * Old roots should be searched when inserting qgroup
			 * extent record
			 */
			if (WARN_ON(!record->old_roots)) {
				/* Search commit root to find old_roots */
				ret = btrfs_find_all_roots(NULL, fs_info,
						record->bytenr, 0,
2558
						&record->old_roots, false);
2559 2560 2561 2562
				if (ret < 0)
					goto cleanup;
			}

2563
			/*
2564
			 * Use SEQ_LAST as time_seq to do special search, which
2565 2566 2567 2568
			 * doesn't lock tree or delayed_refs and search current
			 * root. It's safe inside commit_transaction().
			 */
			ret = btrfs_find_all_roots(trans, fs_info,
2569
				record->bytenr, SEQ_LAST, &new_roots, false);
2570 2571
			if (ret < 0)
				goto cleanup;
2572
			if (qgroup_to_skip) {
2573
				ulist_del(new_roots, qgroup_to_skip, 0);
2574 2575 2576
				ulist_del(record->old_roots, qgroup_to_skip,
					  0);
			}
2577 2578 2579 2580
			ret = btrfs_qgroup_account_extent(trans, record->bytenr,
							  record->num_bytes,
							  record->old_roots,
							  new_roots);
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
			record->old_roots = NULL;
			new_roots = NULL;
		}
cleanup:
		ulist_free(record->old_roots);
		ulist_free(new_roots);
		new_roots = NULL;
		rb_erase(node, &delayed_refs->dirty_extent_root);
		kfree(record);

	}
2592 2593
	trace_qgroup_num_dirty_extents(fs_info, trans->transid,
				       num_dirty_extents);
2594 2595 2596
	return ret;
}

2597 2598 2599
/*
 * called from commit_transaction. Writes all changed qgroups to disk.
 */
2600
int btrfs_run_qgroups(struct btrfs_trans_handle *trans)
2601
{
2602
	struct btrfs_fs_info *fs_info = trans->fs_info;
2603 2604 2605 2606
	struct btrfs_root *quota_root = fs_info->quota_root;
	int ret = 0;

	if (!quota_root)
2607
		return ret;
2608 2609 2610 2611 2612 2613 2614 2615

	spin_lock(&fs_info->qgroup_lock);
	while (!list_empty(&fs_info->dirty_qgroups)) {
		struct btrfs_qgroup *qgroup;
		qgroup = list_first_entry(&fs_info->dirty_qgroups,
					  struct btrfs_qgroup, dirty);
		list_del_init(&qgroup->dirty);
		spin_unlock(&fs_info->qgroup_lock);
2616
		ret = update_qgroup_info_item(trans, qgroup);
2617 2618 2619
		if (ret)
			fs_info->qgroup_flags |=
					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
2620
		ret = update_qgroup_limit_item(trans, qgroup);
2621 2622 2623 2624 2625
		if (ret)
			fs_info->qgroup_flags |=
					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		spin_lock(&fs_info->qgroup_lock);
	}
2626
	if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2627 2628 2629 2630 2631
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_ON;
	else
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
	spin_unlock(&fs_info->qgroup_lock);

2632
	ret = update_qgroup_status_item(trans);
2633 2634 2635 2636 2637 2638 2639
	if (ret)
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;

	return ret;
}

/*
2640
 * Copy the accounting information between qgroups. This is necessary
2641 2642 2643
 * when a snapshot or a subvolume is created. Throwing an error will
 * cause a transaction abort so we take extra care here to only error
 * when a readonly fs is a reasonable outcome.
2644
 */
2645 2646
int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans, u64 srcid,
			 u64 objectid, struct btrfs_qgroup_inherit *inherit)
2647 2648 2649 2650
{
	int ret = 0;
	int i;
	u64 *i_qgroups;
2651
	struct btrfs_fs_info *fs_info = trans->fs_info;
2652 2653 2654 2655
	struct btrfs_root *quota_root = fs_info->quota_root;
	struct btrfs_qgroup *srcgroup;
	struct btrfs_qgroup *dstgroup;
	u32 level_size = 0;
2656
	u64 nums;
2657

2658
	mutex_lock(&fs_info->qgroup_ioctl_lock);
2659
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2660
		goto out;
2661

2662 2663 2664 2665
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
2666

2667 2668 2669 2670 2671 2672
	if (inherit) {
		i_qgroups = (u64 *)(inherit + 1);
		nums = inherit->num_qgroups + 2 * inherit->num_ref_copies +
		       2 * inherit->num_excl_copies;
		for (i = 0; i < nums; ++i) {
			srcgroup = find_qgroup_rb(fs_info, *i_qgroups);
2673

2674 2675 2676 2677 2678 2679 2680 2681
			/*
			 * Zero out invalid groups so we can ignore
			 * them later.
			 */
			if (!srcgroup ||
			    ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
				*i_qgroups = 0ULL;

2682 2683 2684 2685
			++i_qgroups;
		}
	}

2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
	/*
	 * create a tracking group for the subvol itself
	 */
	ret = add_qgroup_item(trans, quota_root, objectid);
	if (ret)
		goto out;

	/*
	 * add qgroup to all inherited groups
	 */
	if (inherit) {
		i_qgroups = (u64 *)(inherit + 1);
2698 2699 2700
		for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
			if (*i_qgroups == 0)
				continue;
2701 2702
			ret = add_qgroup_relation_item(trans, objectid,
						       *i_qgroups);
2703
			if (ret && ret != -EEXIST)
2704
				goto out;
2705 2706
			ret = add_qgroup_relation_item(trans, *i_qgroups,
						       objectid);
2707
			if (ret && ret != -EEXIST)
2708 2709
				goto out;
		}
2710
		ret = 0;
2711 2712 2713 2714 2715 2716
	}


	spin_lock(&fs_info->qgroup_lock);

	dstgroup = add_qgroup_rb(fs_info, objectid);
2717 2718
	if (IS_ERR(dstgroup)) {
		ret = PTR_ERR(dstgroup);
2719
		goto unlock;
2720
	}
2721

2722 2723 2724 2725 2726 2727
	if (inherit && inherit->flags & BTRFS_QGROUP_INHERIT_SET_LIMITS) {
		dstgroup->lim_flags = inherit->lim.flags;
		dstgroup->max_rfer = inherit->lim.max_rfer;
		dstgroup->max_excl = inherit->lim.max_excl;
		dstgroup->rsv_rfer = inherit->lim.rsv_rfer;
		dstgroup->rsv_excl = inherit->lim.rsv_excl;
2728

2729
		ret = update_qgroup_limit_item(trans, dstgroup);
2730 2731
		if (ret) {
			fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
J
Jeff Mahoney 已提交
2732 2733 2734
			btrfs_info(fs_info,
				   "unable to update quota limit for %llu",
				   dstgroup->qgroupid);
2735 2736
			goto unlock;
		}
2737 2738
	}

2739 2740
	if (srcid) {
		srcgroup = find_qgroup_rb(fs_info, srcid);
2741
		if (!srcgroup)
2742
			goto unlock;
J
Josef Bacik 已提交
2743 2744 2745 2746 2747 2748

		/*
		 * We call inherit after we clone the root in order to make sure
		 * our counts don't go crazy, so at this point the only
		 * difference between the two roots should be the root node.
		 */
2749
		level_size = fs_info->nodesize;
J
Josef Bacik 已提交
2750 2751 2752 2753
		dstgroup->rfer = srcgroup->rfer;
		dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
		dstgroup->excl = level_size;
		dstgroup->excl_cmpr = level_size;
2754 2755
		srcgroup->excl = level_size;
		srcgroup->excl_cmpr = level_size;
2756 2757 2758 2759 2760 2761 2762 2763

		/* inherit the limit info */
		dstgroup->lim_flags = srcgroup->lim_flags;
		dstgroup->max_rfer = srcgroup->max_rfer;
		dstgroup->max_excl = srcgroup->max_excl;
		dstgroup->rsv_rfer = srcgroup->rsv_rfer;
		dstgroup->rsv_excl = srcgroup->rsv_excl;

2764 2765 2766 2767
		qgroup_dirty(fs_info, dstgroup);
		qgroup_dirty(fs_info, srcgroup);
	}

2768
	if (!inherit)
2769 2770 2771 2772
		goto unlock;

	i_qgroups = (u64 *)(inherit + 1);
	for (i = 0; i < inherit->num_qgroups; ++i) {
2773
		if (*i_qgroups) {
2774
			ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2775 2776 2777
			if (ret)
				goto unlock;
		}
2778 2779 2780
		++i_qgroups;
	}

2781
	for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
2782 2783 2784
		struct btrfs_qgroup *src;
		struct btrfs_qgroup *dst;

2785 2786 2787
		if (!i_qgroups[0] || !i_qgroups[1])
			continue;

2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
		src = find_qgroup_rb(fs_info, i_qgroups[0]);
		dst = find_qgroup_rb(fs_info, i_qgroups[1]);

		if (!src || !dst) {
			ret = -EINVAL;
			goto unlock;
		}

		dst->rfer = src->rfer - level_size;
		dst->rfer_cmpr = src->rfer_cmpr - level_size;
	}
2799
	for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
2800 2801 2802
		struct btrfs_qgroup *src;
		struct btrfs_qgroup *dst;

2803 2804 2805
		if (!i_qgroups[0] || !i_qgroups[1])
			continue;

2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
		src = find_qgroup_rb(fs_info, i_qgroups[0]);
		dst = find_qgroup_rb(fs_info, i_qgroups[1]);

		if (!src || !dst) {
			ret = -EINVAL;
			goto unlock;
		}

		dst->excl = src->excl + level_size;
		dst->excl_cmpr = src->excl_cmpr + level_size;
	}

unlock:
	spin_unlock(&fs_info->qgroup_lock);
out:
2821
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
2822 2823 2824
	return ret;
}

2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
/*
 * Two limits to commit transaction in advance.
 *
 * For RATIO, it will be 1/RATIO of the remaining limit
 * (excluding data and prealloc meta) as threshold.
 * For SIZE, it will be in byte unit as threshold.
 */
#define QGROUP_PERTRANS_RATIO		32
#define QGROUP_PERTRANS_SIZE		SZ_32M
static bool qgroup_check_limits(struct btrfs_fs_info *fs_info,
				const struct btrfs_qgroup *qg, u64 num_bytes)
2836
{
2837 2838 2839
	u64 limit;
	u64 threshold;

2840
	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
2841
	    qgroup_rsv_total(qg) + (s64)qg->rfer + num_bytes > qg->max_rfer)
2842 2843 2844
		return false;

	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
2845
	    qgroup_rsv_total(qg) + (s64)qg->excl + num_bytes > qg->max_excl)
2846 2847
		return false;

2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872
	/*
	 * Even if we passed the check, it's better to check if reservation
	 * for meta_pertrans is pushing us near limit.
	 * If there is too much pertrans reservation or it's near the limit,
	 * let's try commit transaction to free some, using transaction_kthread
	 */
	if ((qg->lim_flags & (BTRFS_QGROUP_LIMIT_MAX_RFER |
			      BTRFS_QGROUP_LIMIT_MAX_EXCL))) {
		if (qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL)
			limit = qg->max_excl;
		else
			limit = qg->max_rfer;
		threshold = (limit - qg->rsv.values[BTRFS_QGROUP_RSV_DATA] -
			    qg->rsv.values[BTRFS_QGROUP_RSV_META_PREALLOC]) /
			    QGROUP_PERTRANS_RATIO;
		threshold = min_t(u64, threshold, QGROUP_PERTRANS_SIZE);

		/*
		 * Use transaction_kthread to commit transaction, so we no
		 * longer need to bother nested transaction nor lock context.
		 */
		if (qg->rsv.values[BTRFS_QGROUP_RSV_META_PERTRANS] > threshold)
			btrfs_commit_transaction_locksafe(fs_info);
	}

2873 2874 2875
	return true;
}

2876 2877
static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce,
			  enum btrfs_qgroup_rsv_type type)
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
{
	struct btrfs_root *quota_root;
	struct btrfs_qgroup *qgroup;
	struct btrfs_fs_info *fs_info = root->fs_info;
	u64 ref_root = root->root_key.objectid;
	int ret = 0;
	struct ulist_node *unode;
	struct ulist_iterator uiter;

	if (!is_fstree(ref_root))
		return 0;

	if (num_bytes == 0)
		return 0;
2892 2893 2894 2895 2896

	if (test_bit(BTRFS_FS_QUOTA_OVERRIDE, &fs_info->flags) &&
	    capable(CAP_SYS_RESOURCE))
		enforce = false;

2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
	spin_lock(&fs_info->qgroup_lock);
	quota_root = fs_info->quota_root;
	if (!quota_root)
		goto out;

	qgroup = find_qgroup_rb(fs_info, ref_root);
	if (!qgroup)
		goto out;

	/*
	 * in a first step, we check all affected qgroups if any limits would
	 * be exceeded
	 */
2910 2911
	ulist_reinit(fs_info->qgroup_ulist);
	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
2912
			qgroup_to_aux(qgroup), GFP_ATOMIC);
2913 2914
	if (ret < 0)
		goto out;
2915
	ULIST_ITER_INIT(&uiter);
2916
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2917 2918 2919
		struct btrfs_qgroup *qg;
		struct btrfs_qgroup_list *glist;

2920
		qg = unode_aux_to_qgroup(unode);
2921

2922
		if (enforce && !qgroup_check_limits(fs_info, qg, num_bytes)) {
2923
			ret = -EDQUOT;
2924 2925
			goto out;
		}
2926 2927

		list_for_each_entry(glist, &qg->groups, next_group) {
2928 2929
			ret = ulist_add(fs_info->qgroup_ulist,
					glist->group->qgroupid,
2930
					qgroup_to_aux(glist->group), GFP_ATOMIC);
2931 2932
			if (ret < 0)
				goto out;
2933 2934
		}
	}
2935
	ret = 0;
2936 2937 2938 2939
	/*
	 * no limits exceeded, now record the reservation into all qgroups
	 */
	ULIST_ITER_INIT(&uiter);
2940
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2941 2942
		struct btrfs_qgroup *qg;

2943
		qg = unode_aux_to_qgroup(unode);
2944

2945 2946
		trace_qgroup_update_reserve(fs_info, qg, num_bytes, type);
		qgroup_rsv_add(fs_info, qg, num_bytes, type);
2947 2948 2949 2950 2951 2952 2953
	}

out:
	spin_unlock(&fs_info->qgroup_lock);
	return ret;
}

2954 2955 2956 2957 2958 2959 2960 2961 2962
/*
 * Free @num_bytes of reserved space with @type for qgroup.  (Normally level 0
 * qgroup).
 *
 * Will handle all higher level qgroup too.
 *
 * NOTE: If @num_bytes is (u64)-1, this means to free all bytes of this qgroup.
 * This special case is only used for META_PERTRANS type.
 */
2963
void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
2964 2965
			       u64 ref_root, u64 num_bytes,
			       enum btrfs_qgroup_rsv_type type)
2966 2967 2968 2969 2970
{
	struct btrfs_root *quota_root;
	struct btrfs_qgroup *qgroup;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
2971
	int ret = 0;
2972 2973 2974 2975 2976 2977 2978

	if (!is_fstree(ref_root))
		return;

	if (num_bytes == 0)
		return;

2979 2980 2981 2982
	if (num_bytes == (u64)-1 && type != BTRFS_QGROUP_RSV_META_PERTRANS) {
		WARN(1, "%s: Invalid type to free", __func__);
		return;
	}
2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
	spin_lock(&fs_info->qgroup_lock);

	quota_root = fs_info->quota_root;
	if (!quota_root)
		goto out;

	qgroup = find_qgroup_rb(fs_info, ref_root);
	if (!qgroup)
		goto out;

2993
	if (num_bytes == (u64)-1)
2994 2995 2996 2997
		/*
		 * We're freeing all pertrans rsv, get reserved value from
		 * level 0 qgroup as real num_bytes to free.
		 */
2998 2999
		num_bytes = qgroup->rsv.values[type];

3000 3001
	ulist_reinit(fs_info->qgroup_ulist);
	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3002
			qgroup_to_aux(qgroup), GFP_ATOMIC);
3003 3004
	if (ret < 0)
		goto out;
3005
	ULIST_ITER_INIT(&uiter);
3006
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
3007 3008 3009
		struct btrfs_qgroup *qg;
		struct btrfs_qgroup_list *glist;

3010
		qg = unode_aux_to_qgroup(unode);
3011

3012 3013
		trace_qgroup_update_reserve(fs_info, qg, -(s64)num_bytes, type);
		qgroup_rsv_release(fs_info, qg, num_bytes, type);
3014 3015

		list_for_each_entry(glist, &qg->groups, next_group) {
3016 3017
			ret = ulist_add(fs_info->qgroup_ulist,
					glist->group->qgroupid,
3018
					qgroup_to_aux(glist->group), GFP_ATOMIC);
3019 3020
			if (ret < 0)
				goto out;
3021 3022 3023 3024 3025 3026 3027
		}
	}

out:
	spin_unlock(&fs_info->qgroup_lock);
}

3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
/*
 * Check if the leaf is the last leaf. Which means all node pointers
 * are at their last position.
 */
static bool is_last_leaf(struct btrfs_path *path)
{
	int i;

	for (i = 1; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
		if (path->slots[i] != btrfs_header_nritems(path->nodes[i]) - 1)
			return false;
	}
	return true;
}

J
Jan Schmidt 已提交
3043 3044
/*
 * returns < 0 on error, 0 when more leafs are to be scanned.
3045
 * returns 1 when done.
J
Jan Schmidt 已提交
3046
 */
3047 3048
static int qgroup_rescan_leaf(struct btrfs_trans_handle *trans,
			      struct btrfs_path *path)
J
Jan Schmidt 已提交
3049
{
3050
	struct btrfs_fs_info *fs_info = trans->fs_info;
J
Jan Schmidt 已提交
3051
	struct btrfs_key found;
3052
	struct extent_buffer *scratch_leaf = NULL;
J
Jan Schmidt 已提交
3053
	struct ulist *roots = NULL;
J
Josef Bacik 已提交
3054
	u64 num_bytes;
3055
	bool done;
J
Jan Schmidt 已提交
3056 3057 3058 3059 3060 3061 3062 3063
	int slot;
	int ret;

	mutex_lock(&fs_info->qgroup_rescan_lock);
	ret = btrfs_search_slot_for_read(fs_info->extent_root,
					 &fs_info->qgroup_rescan_progress,
					 path, 1, 0);

3064 3065 3066 3067 3068
	btrfs_debug(fs_info,
		"current progress key (%llu %u %llu), search_slot ret %d",
		fs_info->qgroup_rescan_progress.objectid,
		fs_info->qgroup_rescan_progress.type,
		fs_info->qgroup_rescan_progress.offset, ret);
J
Jan Schmidt 已提交
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083

	if (ret) {
		/*
		 * The rescan is about to end, we will not be scanning any
		 * further blocks. We cannot unset the RESCAN flag here, because
		 * we want to commit the transaction if everything went well.
		 * To make the live accounting work in this phase, we set our
		 * scan progress pointer such that every real extent objectid
		 * will be smaller.
		 */
		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
		btrfs_release_path(path);
		mutex_unlock(&fs_info->qgroup_rescan_lock);
		return ret;
	}
3084
	done = is_last_leaf(path);
J
Jan Schmidt 已提交
3085 3086 3087 3088 3089

	btrfs_item_key_to_cpu(path->nodes[0], &found,
			      btrfs_header_nritems(path->nodes[0]) - 1);
	fs_info->qgroup_rescan_progress.objectid = found.objectid + 1;

3090 3091 3092 3093 3094 3095 3096 3097 3098
	scratch_leaf = btrfs_clone_extent_buffer(path->nodes[0]);
	if (!scratch_leaf) {
		ret = -ENOMEM;
		mutex_unlock(&fs_info->qgroup_rescan_lock);
		goto out;
	}
	extent_buffer_get(scratch_leaf);
	btrfs_tree_read_lock(scratch_leaf);
	btrfs_set_lock_blocking_rw(scratch_leaf, BTRFS_READ_LOCK);
J
Jan Schmidt 已提交
3099 3100 3101 3102 3103 3104
	slot = path->slots[0];
	btrfs_release_path(path);
	mutex_unlock(&fs_info->qgroup_rescan_lock);

	for (; slot < btrfs_header_nritems(scratch_leaf); ++slot) {
		btrfs_item_key_to_cpu(scratch_leaf, &found, slot);
3105 3106
		if (found.type != BTRFS_EXTENT_ITEM_KEY &&
		    found.type != BTRFS_METADATA_ITEM_KEY)
J
Jan Schmidt 已提交
3107
			continue;
3108
		if (found.type == BTRFS_METADATA_ITEM_KEY)
3109
			num_bytes = fs_info->nodesize;
3110 3111 3112
		else
			num_bytes = found.offset;

J
Josef Bacik 已提交
3113
		ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
3114
					   &roots, false);
J
Jan Schmidt 已提交
3115 3116
		if (ret < 0)
			goto out;
3117
		/* For rescan, just pass old_roots as NULL */
3118 3119
		ret = btrfs_qgroup_account_extent(trans, found.objectid,
						  num_bytes, NULL, roots);
3120
		if (ret < 0)
J
Josef Bacik 已提交
3121
			goto out;
J
Jan Schmidt 已提交
3122 3123
	}
out:
3124 3125 3126 3127
	if (scratch_leaf) {
		btrfs_tree_read_unlock_blocking(scratch_leaf);
		free_extent_buffer(scratch_leaf);
	}
J
Jan Schmidt 已提交
3128

3129
	if (done && !ret) {
3130
		ret = 1;
3131 3132
		fs_info->qgroup_rescan_progress.objectid = (u64)-1;
	}
J
Jan Schmidt 已提交
3133 3134 3135
	return ret;
}

3136
static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
J
Jan Schmidt 已提交
3137
{
3138 3139
	struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
						     qgroup_rescan_work);
J
Jan Schmidt 已提交
3140 3141 3142
	struct btrfs_path *path;
	struct btrfs_trans_handle *trans = NULL;
	int err = -ENOMEM;
3143
	int ret = 0;
J
Jan Schmidt 已提交
3144 3145 3146 3147

	path = btrfs_alloc_path();
	if (!path)
		goto out;
3148 3149 3150 3151 3152 3153
	/*
	 * Rescan should only search for commit root, and any later difference
	 * should be recorded by qgroup
	 */
	path->search_commit_root = 1;
	path->skip_locking = 1;
J
Jan Schmidt 已提交
3154 3155

	err = 0;
3156
	while (!err && !btrfs_fs_closing(fs_info)) {
J
Jan Schmidt 已提交
3157 3158 3159 3160 3161
		trans = btrfs_start_transaction(fs_info->fs_root, 0);
		if (IS_ERR(trans)) {
			err = PTR_ERR(trans);
			break;
		}
3162
		if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
J
Jan Schmidt 已提交
3163 3164
			err = -EINTR;
		} else {
3165
			err = qgroup_rescan_leaf(trans, path);
J
Jan Schmidt 已提交
3166 3167
		}
		if (err > 0)
3168
			btrfs_commit_transaction(trans);
J
Jan Schmidt 已提交
3169
		else
3170
			btrfs_end_transaction(trans);
J
Jan Schmidt 已提交
3171 3172 3173 3174 3175 3176
	}

out:
	btrfs_free_path(path);

	mutex_lock(&fs_info->qgroup_rescan_lock);
3177 3178
	if (!btrfs_fs_closing(fs_info))
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
J
Jan Schmidt 已提交
3179

3180
	if (err > 0 &&
J
Jan Schmidt 已提交
3181 3182 3183 3184 3185 3186 3187
	    fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT) {
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	} else if (err < 0) {
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	}
	mutex_unlock(&fs_info->qgroup_rescan_lock);

3188
	/*
3189
	 * only update status, since the previous part has already updated the
3190 3191 3192 3193 3194 3195
	 * qgroup info.
	 */
	trans = btrfs_start_transaction(fs_info->quota_root, 1);
	if (IS_ERR(trans)) {
		err = PTR_ERR(trans);
		btrfs_err(fs_info,
3196
			  "fail to start transaction for status update: %d",
3197 3198 3199
			  err);
		goto done;
	}
3200
	ret = update_qgroup_status_item(trans);
3201 3202
	if (ret < 0) {
		err = ret;
3203
		btrfs_err(fs_info, "fail to update qgroup status: %d", err);
3204
	}
3205
	btrfs_end_transaction(trans);
3206

3207 3208 3209
	if (btrfs_fs_closing(fs_info)) {
		btrfs_info(fs_info, "qgroup scan paused");
	} else if (err >= 0) {
3210
		btrfs_info(fs_info, "qgroup scan completed%s",
3211
			err > 0 ? " (inconsistency flag cleared)" : "");
J
Jan Schmidt 已提交
3212
	} else {
3213
		btrfs_err(fs_info, "qgroup scan failed with %d", err);
J
Jan Schmidt 已提交
3214
	}
3215

3216
done:
3217 3218 3219
	mutex_lock(&fs_info->qgroup_rescan_lock);
	fs_info->qgroup_rescan_running = false;
	mutex_unlock(&fs_info->qgroup_rescan_lock);
3220
	complete_all(&fs_info->qgroup_rescan_completion);
J
Jan Schmidt 已提交
3221 3222
}

3223 3224 3225 3226 3227 3228 3229
/*
 * Checks that (a) no rescan is running and (b) quota is enabled. Allocates all
 * memory required for the rescan context.
 */
static int
qgroup_rescan_init(struct btrfs_fs_info *fs_info, u64 progress_objectid,
		   int init_flags)
J
Jan Schmidt 已提交
3230 3231 3232
{
	int ret = 0;

3233 3234
	if (!init_flags) {
		/* we're resuming qgroup rescan at mount time */
3235 3236
		if (!(fs_info->qgroup_flags &
		      BTRFS_QGROUP_STATUS_FLAG_RESCAN)) {
3237 3238
			btrfs_warn(fs_info,
			"qgroup rescan init failed, qgroup is not enabled");
3239 3240 3241
			ret = -EINVAL;
		} else if (!(fs_info->qgroup_flags &
			     BTRFS_QGROUP_STATUS_FLAG_ON)) {
3242 3243
			btrfs_warn(fs_info,
			"qgroup rescan init failed, qgroup rescan is not queued");
3244 3245 3246 3247 3248
			ret = -EINVAL;
		}

		if (ret)
			return ret;
3249
	}
J
Jan Schmidt 已提交
3250 3251 3252

	mutex_lock(&fs_info->qgroup_rescan_lock);
	spin_lock(&fs_info->qgroup_lock);
3253 3254

	if (init_flags) {
3255 3256 3257
		if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) {
			btrfs_warn(fs_info,
				   "qgroup rescan is already in progress");
3258
			ret = -EINPROGRESS;
3259 3260 3261 3262
		} else if (!(fs_info->qgroup_flags &
			     BTRFS_QGROUP_STATUS_FLAG_ON)) {
			btrfs_warn(fs_info,
			"qgroup rescan init failed, qgroup is not enabled");
3263
			ret = -EINVAL;
3264
		}
3265 3266 3267 3268

		if (ret) {
			spin_unlock(&fs_info->qgroup_lock);
			mutex_unlock(&fs_info->qgroup_rescan_lock);
3269
			return ret;
3270 3271
		}
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
J
Jan Schmidt 已提交
3272 3273 3274 3275
	}

	memset(&fs_info->qgroup_rescan_progress, 0,
		sizeof(fs_info->qgroup_rescan_progress));
3276
	fs_info->qgroup_rescan_progress.objectid = progress_objectid;
3277
	init_completion(&fs_info->qgroup_rescan_completion);
3278
	fs_info->qgroup_rescan_running = true;
3279 3280 3281 3282 3283 3284

	spin_unlock(&fs_info->qgroup_lock);
	mutex_unlock(&fs_info->qgroup_rescan_lock);

	memset(&fs_info->qgroup_rescan_work, 0,
	       sizeof(fs_info->qgroup_rescan_work));
3285
	btrfs_init_work(&fs_info->qgroup_rescan_work,
3286
			btrfs_qgroup_rescan_helper,
3287
			btrfs_qgroup_rescan_worker, NULL, NULL);
3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
	return 0;
}

static void
qgroup_rescan_zero_tracking(struct btrfs_fs_info *fs_info)
{
	struct rb_node *n;
	struct btrfs_qgroup *qgroup;

	spin_lock(&fs_info->qgroup_lock);
J
Jan Schmidt 已提交
3298 3299 3300 3301 3302 3303 3304
	/* clear all current qgroup tracking information */
	for (n = rb_first(&fs_info->qgroup_tree); n; n = rb_next(n)) {
		qgroup = rb_entry(n, struct btrfs_qgroup, node);
		qgroup->rfer = 0;
		qgroup->rfer_cmpr = 0;
		qgroup->excl = 0;
		qgroup->excl_cmpr = 0;
3305
		qgroup_dirty(fs_info, qgroup);
J
Jan Schmidt 已提交
3306 3307
	}
	spin_unlock(&fs_info->qgroup_lock);
3308
}
J
Jan Schmidt 已提交
3309

3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335
int
btrfs_qgroup_rescan(struct btrfs_fs_info *fs_info)
{
	int ret = 0;
	struct btrfs_trans_handle *trans;

	ret = qgroup_rescan_init(fs_info, 0, 1);
	if (ret)
		return ret;

	/*
	 * We have set the rescan_progress to 0, which means no more
	 * delayed refs will be accounted by btrfs_qgroup_account_ref.
	 * However, btrfs_qgroup_account_ref may be right after its call
	 * to btrfs_find_all_roots, in which case it would still do the
	 * accounting.
	 * To solve this, we're committing the transaction, which will
	 * ensure we run all delayed refs and only after that, we are
	 * going to clear all tracking information for a clean start.
	 */

	trans = btrfs_join_transaction(fs_info->fs_root);
	if (IS_ERR(trans)) {
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
		return PTR_ERR(trans);
	}
3336
	ret = btrfs_commit_transaction(trans);
3337 3338 3339 3340 3341 3342 3343
	if (ret) {
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
		return ret;
	}

	qgroup_rescan_zero_tracking(fs_info);

3344 3345
	btrfs_queue_work(fs_info->qgroup_rescan_workers,
			 &fs_info->qgroup_rescan_work);
J
Jan Schmidt 已提交
3346 3347 3348

	return 0;
}
3349

3350 3351
int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
				     bool interruptible)
3352 3353 3354 3355 3356 3357
{
	int running;
	int ret = 0;

	mutex_lock(&fs_info->qgroup_rescan_lock);
	spin_lock(&fs_info->qgroup_lock);
3358
	running = fs_info->qgroup_rescan_running;
3359 3360 3361
	spin_unlock(&fs_info->qgroup_lock);
	mutex_unlock(&fs_info->qgroup_rescan_lock);

3362 3363 3364 3365
	if (!running)
		return 0;

	if (interruptible)
3366 3367
		ret = wait_for_completion_interruptible(
					&fs_info->qgroup_rescan_completion);
3368 3369
	else
		wait_for_completion(&fs_info->qgroup_rescan_completion);
3370 3371 3372

	return ret;
}
3373 3374 3375 3376 3377 3378 3379 3380 3381

/*
 * this is only called from open_ctree where we're still single threaded, thus
 * locking is omitted here.
 */
void
btrfs_qgroup_rescan_resume(struct btrfs_fs_info *fs_info)
{
	if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN)
3382 3383
		btrfs_queue_work(fs_info->qgroup_rescan_workers,
				 &fs_info->qgroup_rescan_work);
3384
}
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395

/*
 * Reserve qgroup space for range [start, start + len).
 *
 * This function will either reserve space from related qgroups or doing
 * nothing if the range is already reserved.
 *
 * Return 0 for successful reserve
 * Return <0 for error (including -EQUOT)
 *
 * NOTE: this function may sleep for memory allocation.
3396 3397 3398
 *       if btrfs_qgroup_reserve_data() is called multiple times with
 *       same @reserved, caller must ensure when error happens it's OK
 *       to free *ALL* reserved space.
3399
 */
3400 3401 3402
int btrfs_qgroup_reserve_data(struct inode *inode,
			struct extent_changeset **reserved_ret, u64 start,
			u64 len)
3403 3404 3405 3406
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
3407 3408 3409
	struct extent_changeset *reserved;
	u64 orig_reserved;
	u64 to_reserve;
3410 3411
	int ret;

3412
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
3413
	    !is_fstree(root->root_key.objectid) || len == 0)
3414 3415
		return 0;

3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426
	/* @reserved parameter is mandatory for qgroup */
	if (WARN_ON(!reserved_ret))
		return -EINVAL;
	if (!*reserved_ret) {
		*reserved_ret = extent_changeset_alloc();
		if (!*reserved_ret)
			return -ENOMEM;
	}
	reserved = *reserved_ret;
	/* Record already reserved space */
	orig_reserved = reserved->bytes_changed;
3427
	ret = set_record_extent_bits(&BTRFS_I(inode)->io_tree, start,
3428 3429 3430 3431
			start + len -1, EXTENT_QGROUP_RESERVED, reserved);

	/* Newly reserved space */
	to_reserve = reserved->bytes_changed - orig_reserved;
3432
	trace_btrfs_qgroup_reserve_data(inode, start, len,
3433
					to_reserve, QGROUP_RESERVE);
3434 3435
	if (ret < 0)
		goto cleanup;
3436
	ret = qgroup_reserve(root, to_reserve, true, BTRFS_QGROUP_RSV_DATA);
3437 3438 3439 3440 3441 3442
	if (ret < 0)
		goto cleanup;

	return ret;

cleanup:
3443
	/* cleanup *ALL* already reserved ranges */
3444
	ULIST_ITER_INIT(&uiter);
3445
	while ((unode = ulist_next(&reserved->range_changed, &uiter)))
3446
		clear_extent_bit(&BTRFS_I(inode)->io_tree, unode->val,
3447
				 unode->aux, EXTENT_QGROUP_RESERVED, 0, 0, NULL);
3448
	extent_changeset_release(reserved);
3449 3450
	return ret;
}
3451

3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
/* Free ranges specified by @reserved, normally in error path */
static int qgroup_free_reserved_data(struct inode *inode,
			struct extent_changeset *reserved, u64 start, u64 len)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	struct extent_changeset changeset;
	int freed = 0;
	int ret;

	extent_changeset_init(&changeset);
	len = round_up(start + len, root->fs_info->sectorsize);
	start = round_down(start, root->fs_info->sectorsize);

	ULIST_ITER_INIT(&uiter);
	while ((unode = ulist_next(&reserved->range_changed, &uiter))) {
		u64 range_start = unode->val;
		/* unode->aux is the inclusive end */
		u64 range_len = unode->aux - range_start + 1;
		u64 free_start;
		u64 free_len;

		extent_changeset_release(&changeset);

		/* Only free range in range [start, start + len) */
		if (range_start >= start + len ||
		    range_start + range_len <= start)
			continue;
		free_start = max(range_start, start);
		free_len = min(start + len, range_start + range_len) -
			   free_start;
		/*
		 * TODO: To also modify reserved->ranges_reserved to reflect
		 * the modification.
		 *
		 * However as long as we free qgroup reserved according to
		 * EXTENT_QGROUP_RESERVED, we won't double free.
		 * So not need to rush.
		 */
		ret = clear_record_extent_bits(&BTRFS_I(inode)->io_failure_tree,
				free_start, free_start + free_len - 1,
				EXTENT_QGROUP_RESERVED, &changeset);
		if (ret < 0)
			goto out;
		freed += changeset.bytes_changed;
	}
3499
	btrfs_qgroup_free_refroot(root->fs_info, root->root_key.objectid, freed,
3500
				  BTRFS_QGROUP_RSV_DATA);
3501 3502 3503 3504 3505 3506 3507 3508 3509
	ret = freed;
out:
	extent_changeset_release(&changeset);
	return ret;
}

static int __btrfs_qgroup_release_data(struct inode *inode,
			struct extent_changeset *reserved, u64 start, u64 len,
			int free)
3510 3511
{
	struct extent_changeset changeset;
3512
	int trace_op = QGROUP_RELEASE;
3513 3514
	int ret;

3515 3516 3517 3518
	/* In release case, we shouldn't have @reserved */
	WARN_ON(!free && reserved);
	if (free && reserved)
		return qgroup_free_reserved_data(inode, reserved, start, len);
3519
	extent_changeset_init(&changeset);
3520
	ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, start, 
3521
			start + len -1, EXTENT_QGROUP_RESERVED, &changeset);
3522 3523 3524
	if (ret < 0)
		goto out;

3525
	if (free)
3526 3527 3528
		trace_op = QGROUP_FREE;
	trace_btrfs_qgroup_release_data(inode, start, len,
					changeset.bytes_changed, trace_op);
3529 3530
	if (free)
		btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
3531
				BTRFS_I(inode)->root->root_key.objectid,
3532
				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3533
	ret = changeset.bytes_changed;
3534
out:
3535
	extent_changeset_release(&changeset);
3536 3537 3538 3539 3540 3541 3542 3543
	return ret;
}

/*
 * Free a reserved space range from io_tree and related qgroups
 *
 * Should be called when a range of pages get invalidated before reaching disk.
 * Or for error cleanup case.
3544 3545
 * if @reserved is given, only reserved range in [@start, @start + @len) will
 * be freed.
3546 3547 3548 3549 3550
 *
 * For data written to disk, use btrfs_qgroup_release_data().
 *
 * NOTE: This function may sleep for memory allocation.
 */
3551 3552
int btrfs_qgroup_free_data(struct inode *inode,
			struct extent_changeset *reserved, u64 start, u64 len)
3553
{
3554
	return __btrfs_qgroup_release_data(inode, reserved, start, len, 1);
3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
}

/*
 * Release a reserved space range from io_tree only.
 *
 * Should be called when a range of pages get written to disk and corresponding
 * FILE_EXTENT is inserted into corresponding root.
 *
 * Since new qgroup accounting framework will only update qgroup numbers at
 * commit_transaction() time, its reserved space shouldn't be freed from
 * related qgroups.
 *
 * But we should release the range from io_tree, to allow further write to be
 * COWed.
 *
 * NOTE: This function may sleep for memory allocation.
 */
int btrfs_qgroup_release_data(struct inode *inode, u64 start, u64 len)
{
3574
	return __btrfs_qgroup_release_data(inode, NULL, start, len, 0);
3575
}
3576

3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616
static void add_root_meta_rsv(struct btrfs_root *root, int num_bytes,
			      enum btrfs_qgroup_rsv_type type)
{
	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
		return;
	if (num_bytes == 0)
		return;

	spin_lock(&root->qgroup_meta_rsv_lock);
	if (type == BTRFS_QGROUP_RSV_META_PREALLOC)
		root->qgroup_meta_rsv_prealloc += num_bytes;
	else
		root->qgroup_meta_rsv_pertrans += num_bytes;
	spin_unlock(&root->qgroup_meta_rsv_lock);
}

static int sub_root_meta_rsv(struct btrfs_root *root, int num_bytes,
			     enum btrfs_qgroup_rsv_type type)
{
	if (type != BTRFS_QGROUP_RSV_META_PREALLOC &&
	    type != BTRFS_QGROUP_RSV_META_PERTRANS)
		return 0;
	if (num_bytes == 0)
		return 0;

	spin_lock(&root->qgroup_meta_rsv_lock);
	if (type == BTRFS_QGROUP_RSV_META_PREALLOC) {
		num_bytes = min_t(u64, root->qgroup_meta_rsv_prealloc,
				  num_bytes);
		root->qgroup_meta_rsv_prealloc -= num_bytes;
	} else {
		num_bytes = min_t(u64, root->qgroup_meta_rsv_pertrans,
				  num_bytes);
		root->qgroup_meta_rsv_pertrans -= num_bytes;
	}
	spin_unlock(&root->qgroup_meta_rsv_lock);
	return num_bytes;
}

3617 3618
int __btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
				enum btrfs_qgroup_rsv_type type, bool enforce)
3619
{
3620
	struct btrfs_fs_info *fs_info = root->fs_info;
3621 3622
	int ret;

3623
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3624
	    !is_fstree(root->root_key.objectid) || num_bytes == 0)
3625 3626
		return 0;

3627
	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3628
	trace_qgroup_meta_reserve(root, type, (s64)num_bytes);
3629
	ret = qgroup_reserve(root, num_bytes, enforce, type);
3630 3631
	if (ret < 0)
		return ret;
3632 3633 3634 3635 3636 3637 3638 3639 3640
	/*
	 * Record what we have reserved into root.
	 *
	 * To avoid quota disabled->enabled underflow.
	 * In that case, we may try to free space we haven't reserved
	 * (since quota was disabled), so record what we reserved into root.
	 * And ensure later release won't underflow this number.
	 */
	add_root_meta_rsv(root, num_bytes, type);
3641 3642 3643
	return ret;
}

3644
void btrfs_qgroup_free_meta_all_pertrans(struct btrfs_root *root)
3645
{
3646
	struct btrfs_fs_info *fs_info = root->fs_info;
3647

3648
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3649
	    !is_fstree(root->root_key.objectid))
3650 3651
		return;

3652
	/* TODO: Update trace point to handle such free */
3653
	trace_qgroup_meta_free_all_pertrans(root);
3654
	/* Special value -1 means to free all reserved space */
3655
	btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid, (u64)-1,
3656
				  BTRFS_QGROUP_RSV_META_PERTRANS);
3657 3658
}

3659 3660
void __btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes,
			      enum btrfs_qgroup_rsv_type type)
3661
{
3662 3663 3664
	struct btrfs_fs_info *fs_info = root->fs_info;

	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3665
	    !is_fstree(root->root_key.objectid))
3666 3667
		return;

3668 3669 3670 3671 3672 3673
	/*
	 * reservation for META_PREALLOC can happen before quota is enabled,
	 * which can lead to underflow.
	 * Here ensure we will only free what we really have reserved.
	 */
	num_bytes = sub_root_meta_rsv(root, num_bytes, type);
3674
	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
3675
	trace_qgroup_meta_reserve(root, type, -(s64)num_bytes);
3676 3677
	btrfs_qgroup_free_refroot(fs_info, root->root_key.objectid,
				  num_bytes, type);
3678
}
3679

3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699
static void qgroup_convert_meta(struct btrfs_fs_info *fs_info, u64 ref_root,
				int num_bytes)
{
	struct btrfs_root *quota_root = fs_info->quota_root;
	struct btrfs_qgroup *qgroup;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	int ret = 0;

	if (num_bytes == 0)
		return;
	if (!quota_root)
		return;

	spin_lock(&fs_info->qgroup_lock);
	qgroup = find_qgroup_rb(fs_info, ref_root);
	if (!qgroup)
		goto out;
	ulist_reinit(fs_info->qgroup_ulist);
	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
3700
		       qgroup_to_aux(qgroup), GFP_ATOMIC);
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716
	if (ret < 0)
		goto out;
	ULIST_ITER_INIT(&uiter);
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
		struct btrfs_qgroup *qg;
		struct btrfs_qgroup_list *glist;

		qg = unode_aux_to_qgroup(unode);

		qgroup_rsv_release(fs_info, qg, num_bytes,
				BTRFS_QGROUP_RSV_META_PREALLOC);
		qgroup_rsv_add(fs_info, qg, num_bytes,
				BTRFS_QGROUP_RSV_META_PERTRANS);
		list_for_each_entry(glist, &qg->groups, next_group) {
			ret = ulist_add(fs_info->qgroup_ulist,
					glist->group->qgroupid,
3717
					qgroup_to_aux(glist->group), GFP_ATOMIC);
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730
			if (ret < 0)
				goto out;
		}
	}
out:
	spin_unlock(&fs_info->qgroup_lock);
}

void btrfs_qgroup_convert_reserved_meta(struct btrfs_root *root, int num_bytes)
{
	struct btrfs_fs_info *fs_info = root->fs_info;

	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
3731
	    !is_fstree(root->root_key.objectid))
3732
		return;
3733 3734 3735
	/* Same as btrfs_qgroup_free_meta_prealloc() */
	num_bytes = sub_root_meta_rsv(root, num_bytes,
				      BTRFS_QGROUP_RSV_META_PREALLOC);
3736
	trace_qgroup_meta_convert(root, num_bytes);
3737
	qgroup_convert_meta(fs_info, root->root_key.objectid, num_bytes);
3738 3739
}

3740
/*
3741
 * Check qgroup reserved space leaking, normally at destroy inode
3742 3743 3744 3745 3746 3747 3748 3749 3750
 * time
 */
void btrfs_qgroup_check_reserved_leak(struct inode *inode)
{
	struct extent_changeset changeset;
	struct ulist_node *unode;
	struct ulist_iterator iter;
	int ret;

3751
	extent_changeset_init(&changeset);
3752
	ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, 0, (u64)-1,
3753
			EXTENT_QGROUP_RESERVED, &changeset);
3754 3755 3756 3757

	WARN_ON(ret < 0);
	if (WARN_ON(changeset.bytes_changed)) {
		ULIST_ITER_INIT(&iter);
3758
		while ((unode = ulist_next(&changeset.range_changed, &iter))) {
3759 3760 3761 3762
			btrfs_warn(BTRFS_I(inode)->root->fs_info,
				"leaking qgroup reserved space, ino: %lu, start: %llu, end: %llu",
				inode->i_ino, unode->val, unode->aux);
		}
3763
		btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
3764
				BTRFS_I(inode)->root->root_key.objectid,
3765
				changeset.bytes_changed, BTRFS_QGROUP_RSV_DATA);
3766

3767
	}
3768
	extent_changeset_release(&changeset);
3769
}