qgroup.c 74.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright (C) 2011 STRATO.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License v2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 021110-1307, USA.
 */

#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>
26
#include <linux/btrfs.h>
27 28 29 30 31 32 33

#include "ctree.h"
#include "transaction.h"
#include "disk-io.h"
#include "locking.h"
#include "ulist.h"
#include "backref.h"
J
Jan Schmidt 已提交
34
#include "extent_io.h"
J
Josef Bacik 已提交
35
#include "qgroup.h"
36

37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
/* 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
 */

/*
 * one struct for each qgroup, organized in fs_info->qgroup_tree.
 */
struct btrfs_qgroup {
	u64 qgroupid;

	/*
	 * state
	 */
	u64 rfer;	/* referenced */
	u64 rfer_cmpr;	/* referenced compressed */
	u64 excl;	/* exclusive */
	u64 excl_cmpr;	/* exclusive compressed */

	/*
	 * limits
	 */
	u64 lim_flags;	/* which limits are set */
	u64 max_rfer;
	u64 max_excl;
	u64 rsv_rfer;
	u64 rsv_excl;

	/*
	 * reservation tracking
	 */
	u64 reserved;

	/*
	 * lists
	 */
	struct list_head groups;  /* groups this group is member of */
	struct list_head members; /* groups that are members of this group */
	struct list_head dirty;   /* dirty groups */
	struct rb_node node;	  /* tree of qgroups */

	/*
	 * temp variables for accounting operations
88
	 * Refer to qgroup_shared_accounting() for details.
89
	 */
J
Josef Bacik 已提交
90 91
	u64 old_refcnt;
	u64 new_refcnt;
92 93
};

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
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;
}

124 125 126 127 128 129 130 131 132 133
/*
 * 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;
};

134 135 136 137 138 139 140 141 142
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 已提交
143

144 145 146 147
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 已提交
148

149
/* must be called with qgroup_ioctl_lock held */
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 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
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;
}

203
static void __del_qgroup_rb(struct btrfs_qgroup *qgroup)
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
{
	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);
224
}
225

226 227 228 229 230 231 232 233 234 235
/* 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);
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 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
	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;
}

288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
#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

303 304 305 306 307 308 309 310 311 312 313 314 315 316
/*
 * 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;
317
	u64 rescan_progress = 0;
318

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

322
	fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
323 324 325 326 327
	if (!fs_info->qgroup_ulist) {
		ret = -ENOMEM;
		goto out;
	}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
	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) {
362 363
				btrfs_err(fs_info,
				 "old qgroup version, quota disabled");
364 365 366 367 368
				goto out;
			}
			if (btrfs_qgroup_status_generation(l, ptr) !=
			    fs_info->generation) {
				flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
369
				btrfs_err(fs_info,
J
Jeff Mahoney 已提交
370
					"qgroup generation mismatch, marked as inconsistent");
371 372 373
			}
			fs_info->qgroup_flags = btrfs_qgroup_status_flags(l,
									  ptr);
374
			rescan_progress = btrfs_qgroup_status_rescan(l, ptr);
375 376 377 378 379 380 381 382 383 384
			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)) {
385
			btrfs_err(fs_info, "inconsistent qgroup config");
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 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
			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);
455
		if (ret == -ENOENT) {
456 457
			btrfs_warn(fs_info,
				"orphan qgroup relation 0x%llx->0x%llx",
458
				found_key.objectid, found_key.offset);
459 460
			ret = 0;	/* ignore the error */
		}
461 462 463 464 465 466 467 468 469 470 471
		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;
472 473 474 475
	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)
476
		ret = qgroup_rescan_init(fs_info, rescan_progress, 0);
477 478
	btrfs_free_path(path);

479
	if (ret < 0) {
480
		ulist_free(fs_info->qgroup_ulist);
481
		fs_info->qgroup_ulist = NULL;
482
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
483
	}
484

485 486 487 488
	return ret < 0 ? ret : 0;
}

/*
489 490 491 492
 * 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.
493 494 495 496 497 498 499 500 501
 */
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);
502
		__del_qgroup_rb(qgroup);
503
	}
504 505
	/*
	 * we call btrfs_free_qgroup_config() when umounting
506
	 * filesystem and disabling quota, so we set qgroup_ulist
507 508
	 * to be null here to avoid double free.
	 */
509
	ulist_free(fs_info->qgroup_ulist);
510
	fs_info->qgroup_ulist = NULL;
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
}

static int add_qgroup_relation_item(struct btrfs_trans_handle *trans,
				    struct btrfs_root *quota_root,
				    u64 src, u64 dst)
{
	int ret;
	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;
}

static int del_qgroup_relation_item(struct btrfs_trans_handle *trans,
				    struct btrfs_root *quota_root,
				    u64 src, u64 dst)
{
	int ret;
	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;

578
	if (btrfs_is_testing(quota_root->fs_info))
579
		return 0;
580

581 582 583 584 585 586 587 588
	path = btrfs_alloc_path();
	if (!path)
		return -ENOMEM;

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

589 590 591 592 593 594
	/*
	 * Avoid a transaction abort by catching -EEXIST here. In that
	 * case, we proceed by re-initializing the existing structure
	 * on disk.
	 */

595 596
	ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
				      sizeof(*qgroup_info));
597
	if (ret && ret != -EEXIST)
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
		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));
616
	if (ret && ret != -EEXIST)
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
		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;
}

static int del_qgroup_item(struct btrfs_trans_handle *trans,
			   struct btrfs_root *quota_root, u64 qgroupid)
{
	int ret;
	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,
683 684
				    struct btrfs_root *root,
				    struct btrfs_qgroup *qgroup)
685 686 687 688 689 690 691 692 693 694
{
	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;
695
	key.offset = qgroup->qgroupid;
696 697

	path = btrfs_alloc_path();
698 699 700
	if (!path)
		return -ENOMEM;

701 702 703 704 705 706 707 708 709
	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
	if (ret > 0)
		ret = -ENOENT;

	if (ret)
		goto out;

	l = path->nodes[0];
	slot = path->slots[0];
710
	qgroup_limit = btrfs_item_ptr(l, slot, struct btrfs_qgroup_limit_item);
711 712 713 714 715
	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);
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

	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_root *root,
				   struct btrfs_qgroup *qgroup)
{
	struct btrfs_path *path;
	struct btrfs_key key;
	struct extent_buffer *l;
	struct btrfs_qgroup_info_item *qgroup_info;
	int ret;
	int slot;

735
	if (btrfs_is_testing(root->fs_info))
736
		return 0;
737

738 739 740 741 742
	key.objectid = 0;
	key.type = BTRFS_QGROUP_INFO_KEY;
	key.offset = qgroup->qgroupid;

	path = btrfs_alloc_path();
743 744 745
	if (!path)
		return -ENOMEM;

746 747 748 749 750 751 752 753 754
	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
	if (ret > 0)
		ret = -ENOENT;

	if (ret)
		goto out;

	l = path->nodes[0];
	slot = path->slots[0];
755
	qgroup_info = btrfs_item_ptr(l, slot, struct btrfs_qgroup_info_item);
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
	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;
}

static int update_qgroup_status_item(struct btrfs_trans_handle *trans,
				     struct btrfs_fs_info *fs_info,
				    struct btrfs_root *root)
{
	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();
785 786 787
	if (!path)
		return -ENOMEM;

788 789 790 791 792 793 794 795 796 797 798 799
	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
	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 已提交
800 801
	btrfs_set_qgroup_status_rescan(l, ptr,
				fs_info->qgroup_rescan_progress.objectid);
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

	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;
818
	struct extent_buffer *leaf = NULL;
819
	int ret;
820
	int nr = 0;
821 822 823 824 825

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

826 827 828 829 830
	path->leave_spinning = 1;

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

832
	while (1) {
833
		ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
834 835 836 837 838
		if (ret < 0)
			goto out;
		leaf = path->nodes[0];
		nr = btrfs_header_nritems(leaf);
		if (!nr)
839
			break;
840 841 842 843 844 845 846
		/*
		 * 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);
847 848
		if (ret)
			goto out;
849

850 851 852 853
		btrfs_release_path(path);
	}
	ret = 0;
out:
854
	set_bit(BTRFS_FS_QUOTA_DISABLING, &root->fs_info->flags);
855 856 857 858 859 860 861 862
	btrfs_free_path(path);
	return ret;
}

int btrfs_quota_enable(struct btrfs_trans_handle *trans,
		       struct btrfs_fs_info *fs_info)
{
	struct btrfs_root *quota_root;
863
	struct btrfs_root *tree_root = fs_info->tree_root;
864 865 866 867
	struct btrfs_path *path = NULL;
	struct btrfs_qgroup_status_item *ptr;
	struct extent_buffer *leaf;
	struct btrfs_key key;
868 869
	struct btrfs_key found_key;
	struct btrfs_qgroup *qgroup = NULL;
870
	int ret = 0;
871
	int slot;
872

873
	mutex_lock(&fs_info->qgroup_ioctl_lock);
874
	if (fs_info->quota_root) {
875
		set_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags);
876 877 878
		goto out;
	}

879
	fs_info->qgroup_ulist = ulist_alloc(GFP_KERNEL);
880 881 882 883 884
	if (!fs_info->qgroup_ulist) {
		ret = -ENOMEM;
		goto out;
	}

885 886 887 888 889 890 891 892 893 894 895
	/*
	 * 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);
		goto out;
	}

	path = btrfs_alloc_path();
896 897 898 899
	if (!path) {
		ret = -ENOMEM;
		goto out_free_root;
	}
900 901 902 903 904 905 906 907

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

	ret = btrfs_insert_empty_item(trans, quota_root, path, &key,
				      sizeof(*ptr));
	if (ret)
908
		goto out_free_path;
909 910 911 912 913 914 915 916 917

	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 已提交
918
	btrfs_set_qgroup_status_rescan(leaf, ptr, 0);
919 920 921

	btrfs_mark_buffer_dirty(leaf);

922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
	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;
	if (ret < 0)
		goto out_free_path;


	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);
			if (ret)
				goto out_free_path;

			qgroup = add_qgroup_rb(fs_info, found_key.offset);
			if (IS_ERR(qgroup)) {
				ret = PTR_ERR(qgroup);
				goto out_free_path;
			}
		}
		ret = btrfs_next_item(tree_root, path);
		if (ret < 0)
			goto out_free_path;
		if (ret)
			break;
	}

out_add_root:
	btrfs_release_path(path);
	ret = add_qgroup_item(trans, quota_root, BTRFS_FS_TREE_OBJECTID);
	if (ret)
		goto out_free_path;

	qgroup = add_qgroup_rb(fs_info, BTRFS_FS_TREE_OBJECTID);
	if (IS_ERR(qgroup)) {
		ret = PTR_ERR(qgroup);
		goto out_free_path;
	}
969
	spin_lock(&fs_info->qgroup_lock);
970
	fs_info->quota_root = quota_root;
971
	set_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags);
972
	spin_unlock(&fs_info->qgroup_lock);
973
out_free_path:
974
	btrfs_free_path(path);
975 976 977 978 979 980 981
out_free_root:
	if (ret) {
		free_extent_buffer(quota_root->node);
		free_extent_buffer(quota_root->commit_root);
		kfree(quota_root);
	}
out:
982
	if (ret) {
983
		ulist_free(fs_info->qgroup_ulist);
984 985
		fs_info->qgroup_ulist = NULL;
	}
986
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
987 988 989 990 991 992 993 994 995 996
	return ret;
}

int btrfs_quota_disable(struct btrfs_trans_handle *trans,
			struct btrfs_fs_info *fs_info)
{
	struct btrfs_root *tree_root = fs_info->tree_root;
	struct btrfs_root *quota_root;
	int ret = 0;

997
	mutex_lock(&fs_info->qgroup_ioctl_lock);
998
	if (!fs_info->quota_root)
999
		goto out;
1000 1001
	clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
	set_bit(BTRFS_FS_QUOTA_DISABLING, &fs_info->flags);
1002
	btrfs_qgroup_wait_for_completion(fs_info, false);
1003
	spin_lock(&fs_info->qgroup_lock);
1004 1005
	quota_root = fs_info->quota_root;
	fs_info->quota_root = NULL;
1006
	fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_ON;
1007 1008
	spin_unlock(&fs_info->qgroup_lock);

1009 1010
	btrfs_free_qgroup_config(fs_info);

1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
	ret = btrfs_clean_quota_tree(trans, quota_root);
	if (ret)
		goto out;

	ret = btrfs_del_root(trans, tree_root, &quota_root->root_key);
	if (ret)
		goto out;

	list_del(&quota_root->dirty_list);

	btrfs_tree_lock(quota_root->node);
1022
	clean_tree_block(fs_info, quota_root->node);
1023 1024 1025 1026 1027 1028 1029
	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);
out:
1030
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1031 1032 1033
	return ret;
}

J
Jan Schmidt 已提交
1034 1035
static void qgroup_dirty(struct btrfs_fs_info *fs_info,
			 struct btrfs_qgroup *qgroup)
1036
{
J
Jan Schmidt 已提交
1037 1038
	if (list_empty(&qgroup->dirty))
		list_add(&qgroup->dirty, &fs_info->dirty_qgroups);
1039 1040
}

1041 1042 1043 1044 1045 1046 1047 1048 1049
static void report_reserved_underflow(struct btrfs_fs_info *fs_info,
				      struct btrfs_qgroup *qgroup,
				      u64 num_bytes)
{
	btrfs_warn(fs_info,
		"qgroup %llu reserved space underflow, have: %llu, to free: %llu",
		qgroup->qgroupid, qgroup->reserved, num_bytes);
	qgroup->reserved = 0;
}
1050 1051
/*
 * The easy accounting, if we are adding/removing the only ref for an extent
1052
 * then this qgroup and all of the parent qgroups get their reference and
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
 * exclusive counts adjusted.
 *
 * Caller should hold fs_info->qgroup_lock.
 */
static int __qgroup_excl_accounting(struct btrfs_fs_info *fs_info,
				    struct ulist *tmp, u64 ref_root,
				    u64 num_bytes, int sign)
{
	struct btrfs_qgroup *qgroup;
	struct btrfs_qgroup_list *glist;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	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;
1077 1078 1079 1080 1081 1082
	if (sign > 0) {
		if (WARN_ON(qgroup->reserved < num_bytes))
			report_reserved_underflow(fs_info, qgroup, num_bytes);
		else
			qgroup->reserved -= num_bytes;
	}
1083 1084 1085 1086 1087 1088

	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,
1089
				qgroup_to_aux(glist->group), GFP_ATOMIC);
1090 1091 1092 1093 1094 1095 1096
		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))) {
1097
		qgroup = unode_aux_to_qgroup(unode);
1098 1099 1100 1101
		qgroup->rfer += sign * num_bytes;
		qgroup->rfer_cmpr += sign * num_bytes;
		WARN_ON(sign < 0 && qgroup->excl < num_bytes);
		qgroup->excl += sign * num_bytes;
1102 1103 1104 1105 1106 1107 1108
		if (sign > 0) {
			if (WARN_ON(qgroup->reserved < num_bytes))
				report_reserved_underflow(fs_info, qgroup,
							  num_bytes);
			else
				qgroup->reserved -= num_bytes;
		}
1109 1110 1111 1112 1113 1114
		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,
1115
					qgroup_to_aux(glist->group), GFP_ATOMIC);
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
			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,
					       qgroup->excl, sign);
		if (err < 0) {
			ret = err;
			goto out;
		}
	}
out:
	if (ret)
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
	return ret;
}

1163 1164 1165 1166
int btrfs_add_qgroup_relation(struct btrfs_trans_handle *trans,
			      struct btrfs_fs_info *fs_info, u64 src, u64 dst)
{
	struct btrfs_root *quota_root;
1167 1168
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup *member;
1169
	struct btrfs_qgroup_list *list;
1170
	struct ulist *tmp;
1171 1172
	int ret = 0;

1173 1174 1175 1176
	/* Check the level of src and dst first */
	if (btrfs_qgroup_level(src) >= btrfs_qgroup_level(dst))
		return -EINVAL;

1177
	tmp = ulist_alloc(GFP_KERNEL);
1178 1179 1180
	if (!tmp)
		return -ENOMEM;

1181
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1182
	quota_root = fs_info->quota_root;
1183 1184 1185 1186
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1187 1188 1189 1190 1191 1192
	member = find_qgroup_rb(fs_info, src);
	parent = find_qgroup_rb(fs_info, dst);
	if (!member || !parent) {
		ret = -EINVAL;
		goto out;
	}
1193

1194 1195 1196 1197 1198 1199 1200 1201
	/* check if such qgroup relation exist firstly */
	list_for_each_entry(list, &member->groups, next_group) {
		if (list->group == parent) {
			ret = -EEXIST;
			goto out;
		}
	}

1202 1203
	ret = add_qgroup_relation_item(trans, quota_root, src, dst);
	if (ret)
1204
		goto out;
1205 1206 1207 1208

	ret = add_qgroup_relation_item(trans, quota_root, dst, src);
	if (ret) {
		del_qgroup_relation_item(trans, quota_root, src, dst);
1209
		goto out;
1210 1211 1212
	}

	spin_lock(&fs_info->qgroup_lock);
1213
	ret = add_relation_rb(fs_info, src, dst);
1214 1215 1216 1217 1218
	if (ret < 0) {
		spin_unlock(&fs_info->qgroup_lock);
		goto out;
	}
	ret = quick_update_accounting(fs_info, tmp, src, dst, 1);
1219
	spin_unlock(&fs_info->qgroup_lock);
1220 1221
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1222
	ulist_free(tmp);
1223 1224 1225
	return ret;
}

1226
static int __del_qgroup_relation(struct btrfs_trans_handle *trans,
1227 1228 1229
			      struct btrfs_fs_info *fs_info, u64 src, u64 dst)
{
	struct btrfs_root *quota_root;
1230 1231 1232
	struct btrfs_qgroup *parent;
	struct btrfs_qgroup *member;
	struct btrfs_qgroup_list *list;
1233
	struct ulist *tmp;
1234 1235 1236
	int ret = 0;
	int err;

1237
	tmp = ulist_alloc(GFP_KERNEL);
1238 1239 1240
	if (!tmp)
		return -ENOMEM;

1241
	quota_root = fs_info->quota_root;
1242 1243 1244 1245
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1246

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	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:
1262 1263 1264 1265 1266 1267 1268
	ret = del_qgroup_relation_item(trans, quota_root, src, dst);
	err = del_qgroup_relation_item(trans, quota_root, dst, src);
	if (err && !ret)
		ret = err;

	spin_lock(&fs_info->qgroup_lock);
	del_relation_rb(fs_info, src, dst);
1269
	ret = quick_update_accounting(fs_info, tmp, src, dst, -1);
1270
	spin_unlock(&fs_info->qgroup_lock);
1271
out:
1272
	ulist_free(tmp);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
	return ret;
}

int btrfs_del_qgroup_relation(struct btrfs_trans_handle *trans,
			      struct btrfs_fs_info *fs_info, u64 src, u64 dst)
{
	int ret = 0;

	mutex_lock(&fs_info->qgroup_ioctl_lock);
	ret = __del_qgroup_relation(trans, fs_info, src, dst);
1283
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1284

1285 1286 1287 1288
	return ret;
}

int btrfs_create_qgroup(struct btrfs_trans_handle *trans,
1289
			struct btrfs_fs_info *fs_info, u64 qgroupid)
1290 1291 1292 1293 1294
{
	struct btrfs_root *quota_root;
	struct btrfs_qgroup *qgroup;
	int ret = 0;

1295
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1296
	quota_root = fs_info->quota_root;
1297 1298 1299 1300
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1301 1302 1303 1304 1305
	qgroup = find_qgroup_rb(fs_info, qgroupid);
	if (qgroup) {
		ret = -EEXIST;
		goto out;
	}
1306 1307

	ret = add_qgroup_item(trans, quota_root, qgroupid);
1308 1309
	if (ret)
		goto out;
1310 1311 1312 1313 1314 1315 1316

	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);
1317 1318
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1319 1320 1321 1322 1323 1324 1325
	return ret;
}

int btrfs_remove_qgroup(struct btrfs_trans_handle *trans,
			struct btrfs_fs_info *fs_info, u64 qgroupid)
{
	struct btrfs_root *quota_root;
1326
	struct btrfs_qgroup *qgroup;
1327
	struct btrfs_qgroup_list *list;
1328 1329
	int ret = 0;

1330
	mutex_lock(&fs_info->qgroup_ioctl_lock);
1331
	quota_root = fs_info->quota_root;
1332 1333 1334 1335
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1336

1337
	qgroup = find_qgroup_rb(fs_info, qgroupid);
1338 1339 1340 1341
	if (!qgroup) {
		ret = -ENOENT;
		goto out;
	} else {
1342 1343
		/* check if there are no children of this qgroup */
		if (!list_empty(&qgroup->members)) {
1344 1345
			ret = -EBUSY;
			goto out;
1346 1347
		}
	}
1348 1349
	ret = del_qgroup_item(trans, quota_root, qgroupid);

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
	while (!list_empty(&qgroup->groups)) {
		list = list_first_entry(&qgroup->groups,
					struct btrfs_qgroup_list, next_group);
		ret = __del_qgroup_relation(trans, fs_info,
					   qgroupid,
					   list->group->qgroupid);
		if (ret)
			goto out;
	}

1360
	spin_lock(&fs_info->qgroup_lock);
1361
	del_qgroup_rb(fs_info, qgroupid);
1362
	spin_unlock(&fs_info->qgroup_lock);
1363 1364
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1365 1366 1367 1368 1369 1370 1371
	return ret;
}

int btrfs_limit_qgroup(struct btrfs_trans_handle *trans,
		       struct btrfs_fs_info *fs_info, u64 qgroupid,
		       struct btrfs_qgroup_limit *limit)
{
1372
	struct btrfs_root *quota_root;
1373 1374
	struct btrfs_qgroup *qgroup;
	int ret = 0;
1375 1376 1377 1378 1379
	/* 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;
1380

1381 1382 1383 1384 1385 1386
	mutex_lock(&fs_info->qgroup_ioctl_lock);
	quota_root = fs_info->quota_root;
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
1387

1388 1389 1390 1391 1392
	qgroup = find_qgroup_rb(fs_info, qgroupid);
	if (!qgroup) {
		ret = -ENOENT;
		goto out;
	}
1393

1394
	spin_lock(&fs_info->qgroup_lock);
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
	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;
		}
	}
1431 1432
	qgroup->lim_flags |= limit->flags;

1433
	spin_unlock(&fs_info->qgroup_lock);
1434 1435 1436 1437 1438 1439 1440 1441

	ret = update_qgroup_limit_item(trans, quota_root, qgroup);
	if (ret) {
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		btrfs_info(fs_info, "unable to update quota limit for %llu",
		       qgroupid);
	}

1442 1443
out:
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
1444 1445
	return ret;
}
1446

1447 1448 1449 1450 1451 1452
int btrfs_qgroup_prepare_account_extents(struct btrfs_trans_handle *trans,
					 struct btrfs_fs_info *fs_info)
{
	struct btrfs_qgroup_extent_record *record;
	struct btrfs_delayed_ref_root *delayed_refs;
	struct rb_node *node;
1453
	u64 qgroup_to_skip;
1454 1455 1456
	int ret = 0;

	delayed_refs = &trans->transaction->delayed_refs;
1457
	qgroup_to_skip = delayed_refs->qgroup_to_skip;
1458 1459 1460

	/*
	 * No need to do lock, since this function will only be called in
1461
	 * btrfs_commit_transaction().
1462 1463 1464 1465 1466
	 */
	node = rb_first(&delayed_refs->dirty_extent_root);
	while (node) {
		record = rb_entry(node, struct btrfs_qgroup_extent_record,
				  node);
1467 1468 1469
		if (WARN_ON(!record->old_roots))
			ret = btrfs_find_all_roots(NULL, fs_info,
					record->bytenr, 0, &record->old_roots);
1470 1471
		if (ret < 0)
			break;
1472 1473
		if (qgroup_to_skip)
			ulist_del(record->old_roots, qgroup_to_skip, 0);
1474 1475 1476 1477 1478
		node = rb_next(node);
	}
	return ret;
}

1479
int btrfs_qgroup_trace_extent_nolock(struct btrfs_fs_info *fs_info,
1480 1481
				struct btrfs_delayed_ref_root *delayed_refs,
				struct btrfs_qgroup_extent_record *record)
1482 1483 1484 1485 1486 1487
{
	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;

1488
	assert_spin_locked(&delayed_refs->lock);
1489
	trace_btrfs_qgroup_trace_extent(fs_info, record);
1490

1491 1492 1493 1494 1495 1496 1497 1498 1499
	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
1500
			return 1;
1501 1502 1503 1504
	}

	rb_link_node(&record->node, parent_node, p);
	rb_insert_color(&record->node, &delayed_refs->dirty_extent_root);
1505 1506 1507
	return 0;
}

1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
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;

	ret = btrfs_find_all_roots(NULL, fs_info, bytenr, 0, &old_root);
	if (ret < 0)
		return ret;

	/*
	 * 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;
}

1530
int btrfs_qgroup_trace_extent(struct btrfs_trans_handle *trans,
1531 1532 1533 1534 1535 1536 1537
		struct btrfs_fs_info *fs_info, u64 bytenr, u64 num_bytes,
		gfp_t gfp_flag)
{
	struct btrfs_qgroup_extent_record *record;
	struct btrfs_delayed_ref_root *delayed_refs;
	int ret;

1538 1539
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)
	    || bytenr == 0 || num_bytes == 0)
1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
		return 0;
	if (WARN_ON(trans == NULL))
		return -EINVAL;
	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);
1553
	ret = btrfs_qgroup_trace_extent_nolock(fs_info, delayed_refs, record);
1554
	spin_unlock(&delayed_refs->lock);
1555
	if (ret > 0) {
1556
		kfree(record);
1557 1558 1559
		return 0;
	}
	return btrfs_qgroup_trace_extent_post(fs_info, record);
1560 1561
}

1562
int btrfs_qgroup_trace_leaf_items(struct btrfs_trans_handle *trans,
1563
				  struct btrfs_fs_info *fs_info,
1564 1565 1566 1567 1568 1569 1570 1571 1572
				  struct extent_buffer *eb)
{
	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() */
1573
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
		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);

1595 1596
		ret = btrfs_qgroup_trace_extent(trans, fs_info, bytenr,
						num_bytes, GFP_NOFS);
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
		if (ret)
			return ret;
	}
	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.
 */
1617
static int adjust_slots_upwards(struct btrfs_path *path, int root_level)
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
{
	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;
}

int btrfs_qgroup_trace_subtree(struct btrfs_trans_handle *trans,
			       struct btrfs_root *root,
			       struct extent_buffer *root_eb,
			       u64 root_gen, int root_level)
{
1669
	struct btrfs_fs_info *fs_info = root->fs_info;
1670 1671 1672 1673 1674 1675 1676 1677
	int ret = 0;
	int level;
	struct extent_buffer *eb = root_eb;
	struct btrfs_path *path = NULL;

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

1678
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
1679 1680 1681 1682 1683 1684 1685 1686 1687
		return 0;

	if (!extent_buffer_uptodate(root_eb)) {
		ret = btrfs_read_buffer(root_eb, root_gen);
		if (ret)
			goto out;
	}

	if (root_level == 0) {
1688
		ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, root_eb);
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 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
		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) {
			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);

1726
			eb = read_tree_block(fs_info, child_bytenr, child_gen);
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
			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;

1743 1744 1745 1746
			ret = btrfs_qgroup_trace_extent(trans, fs_info,
							child_bytenr,
							fs_info->nodesize,
							GFP_NOFS);
1747 1748 1749 1750 1751
			if (ret)
				goto out;
		}

		if (level == 0) {
1752 1753
			ret = btrfs_qgroup_trace_leaf_items(trans,fs_info,
							   path->nodes[level]);
1754 1755 1756 1757
			if (ret)
				goto out;

			/* Nonzero return here means we completed our search */
1758
			ret = adjust_slots_upwards(path, root_level);
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
			if (ret)
				break;

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

		level--;
	}

	ret = 0;
out:
	btrfs_free_path(path);

	return ret;
}

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
#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);
1801
		ret = ulist_add(qgroups, qg->qgroupid, qgroup_to_aux(qg),
1802 1803 1804
				GFP_ATOMIC);
		if (ret < 0)
			return ret;
1805
		ret = ulist_add(tmp, qg->qgroupid, qgroup_to_aux(qg), GFP_ATOMIC);
1806 1807 1808 1809 1810 1811
		if (ret < 0)
			return ret;
		ULIST_ITER_INIT(&tmp_uiter);
		while ((tmp_unode = ulist_next(tmp, &tmp_uiter))) {
			struct btrfs_qgroup_list *glist;

1812
			qg = unode_aux_to_qgroup(tmp_unode);
1813 1814 1815 1816 1817 1818
			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,
1819
						qgroup_to_aux(glist->group),
1820 1821 1822 1823
						GFP_ATOMIC);
				if (ret < 0)
					return ret;
				ret = ulist_add(tmp, glist->group->qgroupid,
1824
						qgroup_to_aux(glist->group),
1825 1826 1827 1828 1829 1830 1831 1832 1833
						GFP_ATOMIC);
				if (ret < 0)
					return ret;
			}
		}
	}
	return 0;
}

1834 1835 1836
/*
 * Update qgroup rfer/excl counters.
 * Rfer update is easy, codes can explain themselves.
1837
 *
1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
 * 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)
1851
 * !B:	cur_new_roots == nr_new_roots	(possible exclusive now)
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 1877 1878 1879 1880 1881 1882 1883 1884
 *
 * 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;

1885
		qg = unode_aux_to_qgroup(unode);
1886 1887 1888
		cur_old_count = btrfs_qgroup_get_old_refcnt(qg, seq);
		cur_new_count = btrfs_qgroup_get_new_refcnt(qg, seq);

1889 1890
		trace_qgroup_update_counters(fs_info, qg->qgroupid,
					     cur_old_count, cur_new_count);
M
Mark Fasheh 已提交
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
		/* 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 */
			}
		}
1952

1953 1954 1955 1956 1957 1958
		if (dirty)
			qgroup_dirty(fs_info, qg);
	}
	return 0;
}

1959
int
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
btrfs_qgroup_account_extent(struct btrfs_trans_handle *trans,
			    struct btrfs_fs_info *fs_info,
			    u64 bytenr, u64 num_bytes,
			    struct ulist *old_roots, struct ulist *new_roots)
{
	struct ulist *qgroups = NULL;
	struct ulist *tmp = NULL;
	u64 seq;
	u64 nr_new_roots = 0;
	u64 nr_old_roots = 0;
	int ret = 0;

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

1975 1976 1977 1978 1979 1980 1981
	if (new_roots)
		nr_new_roots = new_roots->nnodes;
	if (old_roots)
		nr_old_roots = old_roots->nnodes;

	BUG_ON(!fs_info->quota_root);

1982 1983
	trace_btrfs_qgroup_account_extent(fs_info, bytenr, num_bytes,
					  nr_old_roots, nr_new_roots);
M
Mark Fasheh 已提交
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 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
	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;
}

int btrfs_qgroup_account_extents(struct btrfs_trans_handle *trans,
				 struct btrfs_fs_info *fs_info)
{
	struct btrfs_qgroup_extent_record *record;
	struct btrfs_delayed_ref_root *delayed_refs;
	struct ulist *new_roots = NULL;
	struct rb_node *node;
2045
	u64 qgroup_to_skip;
2046 2047 2048
	int ret = 0;

	delayed_refs = &trans->transaction->delayed_refs;
2049
	qgroup_to_skip = delayed_refs->qgroup_to_skip;
2050 2051 2052 2053
	while ((node = rb_first(&delayed_refs->dirty_extent_root))) {
		record = rb_entry(node, struct btrfs_qgroup_extent_record,
				  node);

2054
		trace_btrfs_qgroup_account_extents(fs_info, record);
M
Mark Fasheh 已提交
2055

2056 2057
		if (!ret) {
			/*
2058
			 * Use SEQ_LAST as time_seq to do special search, which
2059 2060 2061 2062
			 * 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,
2063
					record->bytenr, SEQ_LAST, &new_roots);
2064 2065
			if (ret < 0)
				goto cleanup;
2066 2067
			if (qgroup_to_skip)
				ulist_del(new_roots, qgroup_to_skip, 0);
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
			ret = btrfs_qgroup_account_extent(trans, fs_info,
					record->bytenr, record->num_bytes,
					record->old_roots, new_roots);
			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);

	}
	return ret;
}

2085 2086 2087 2088 2089 2090 2091 2092
/*
 * called from commit_transaction. Writes all changed qgroups to disk.
 */
int btrfs_run_qgroups(struct btrfs_trans_handle *trans,
		      struct btrfs_fs_info *fs_info)
{
	struct btrfs_root *quota_root = fs_info->quota_root;
	int ret = 0;
2093
	int start_rescan_worker = 0;
2094 2095 2096 2097

	if (!quota_root)
		goto out;

2098 2099
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) &&
	    test_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags))
2100 2101
		start_rescan_worker = 1;

2102 2103 2104 2105
	if (test_and_clear_bit(BTRFS_FS_QUOTA_ENABLING, &fs_info->flags))
		set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
	if (test_and_clear_bit(BTRFS_FS_QUOTA_DISABLING, &fs_info->flags))
		clear_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
2106 2107 2108 2109 2110 2111 2112 2113 2114

	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);
		ret = update_qgroup_info_item(trans, quota_root, qgroup);
2115 2116 2117 2118
		if (ret)
			fs_info->qgroup_flags |=
					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		ret = update_qgroup_limit_item(trans, quota_root, qgroup);
2119 2120 2121 2122 2123
		if (ret)
			fs_info->qgroup_flags |=
					BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
		spin_lock(&fs_info->qgroup_lock);
	}
2124
	if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2125 2126 2127 2128 2129 2130 2131 2132 2133
		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);

	ret = update_qgroup_status_item(trans, fs_info, quota_root);
	if (ret)
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;

2134
	if (!ret && start_rescan_worker) {
2135 2136 2137
		ret = qgroup_rescan_init(fs_info, 0, 1);
		if (!ret) {
			qgroup_rescan_zero_tracking(fs_info);
2138 2139
			btrfs_queue_work(fs_info->qgroup_rescan_workers,
					 &fs_info->qgroup_rescan_work);
2140
		}
2141 2142 2143
		ret = 0;
	}

2144 2145 2146 2147 2148 2149
out:

	return ret;
}

/*
2150
 * Copy the accounting information between qgroups. This is necessary
2151 2152 2153
 * 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.
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
 */
int btrfs_qgroup_inherit(struct btrfs_trans_handle *trans,
			 struct btrfs_fs_info *fs_info, u64 srcid, u64 objectid,
			 struct btrfs_qgroup_inherit *inherit)
{
	int ret = 0;
	int i;
	u64 *i_qgroups;
	struct btrfs_root *quota_root = fs_info->quota_root;
	struct btrfs_qgroup *srcgroup;
	struct btrfs_qgroup *dstgroup;
	u32 level_size = 0;
2166
	u64 nums;
2167

2168
	mutex_lock(&fs_info->qgroup_ioctl_lock);
2169
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags))
2170
		goto out;
2171

2172 2173 2174 2175
	if (!quota_root) {
		ret = -EINVAL;
		goto out;
	}
2176

2177 2178 2179 2180 2181 2182
	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);
2183

2184 2185 2186 2187 2188 2189 2190 2191
			/*
			 * Zero out invalid groups so we can ignore
			 * them later.
			 */
			if (!srcgroup ||
			    ((srcgroup->qgroupid >> 48) <= (objectid >> 48)))
				*i_qgroups = 0ULL;

2192 2193 2194 2195
			++i_qgroups;
		}
	}

2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
	/*
	 * create a tracking group for the subvol itself
	 */
	ret = add_qgroup_item(trans, quota_root, objectid);
	if (ret)
		goto out;

	if (srcid) {
		struct btrfs_root *srcroot;
		struct btrfs_key srckey;

		srckey.objectid = srcid;
		srckey.type = BTRFS_ROOT_ITEM_KEY;
		srckey.offset = (u64)-1;
		srcroot = btrfs_read_fs_root_no_name(fs_info, &srckey);
		if (IS_ERR(srcroot)) {
			ret = PTR_ERR(srcroot);
			goto out;
		}

2216
		level_size = fs_info->nodesize;
2217 2218 2219 2220 2221 2222 2223
	}

	/*
	 * add qgroup to all inherited groups
	 */
	if (inherit) {
		i_qgroups = (u64 *)(inherit + 1);
2224 2225 2226
		for (i = 0; i < inherit->num_qgroups; ++i, ++i_qgroups) {
			if (*i_qgroups == 0)
				continue;
2227 2228
			ret = add_qgroup_relation_item(trans, quota_root,
						       objectid, *i_qgroups);
2229
			if (ret && ret != -EEXIST)
2230 2231 2232
				goto out;
			ret = add_qgroup_relation_item(trans, quota_root,
						       *i_qgroups, objectid);
2233
			if (ret && ret != -EEXIST)
2234 2235
				goto out;
		}
2236
		ret = 0;
2237 2238 2239 2240 2241 2242
	}


	spin_lock(&fs_info->qgroup_lock);

	dstgroup = add_qgroup_rb(fs_info, objectid);
2243 2244
	if (IS_ERR(dstgroup)) {
		ret = PTR_ERR(dstgroup);
2245
		goto unlock;
2246
	}
2247

2248 2249 2250 2251 2252 2253
	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;
2254 2255 2256 2257

		ret = update_qgroup_limit_item(trans, quota_root, dstgroup);
		if (ret) {
			fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_INCONSISTENT;
J
Jeff Mahoney 已提交
2258 2259 2260
			btrfs_info(fs_info,
				   "unable to update quota limit for %llu",
				   dstgroup->qgroupid);
2261 2262
			goto unlock;
		}
2263 2264
	}

2265 2266
	if (srcid) {
		srcgroup = find_qgroup_rb(fs_info, srcid);
2267
		if (!srcgroup)
2268
			goto unlock;
J
Josef Bacik 已提交
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278

		/*
		 * 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.
		 */
		dstgroup->rfer = srcgroup->rfer;
		dstgroup->rfer_cmpr = srcgroup->rfer_cmpr;
		dstgroup->excl = level_size;
		dstgroup->excl_cmpr = level_size;
2279 2280
		srcgroup->excl = level_size;
		srcgroup->excl_cmpr = level_size;
2281 2282 2283 2284 2285 2286 2287 2288

		/* 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;

2289 2290 2291 2292
		qgroup_dirty(fs_info, dstgroup);
		qgroup_dirty(fs_info, srcgroup);
	}

2293
	if (!inherit)
2294 2295 2296 2297
		goto unlock;

	i_qgroups = (u64 *)(inherit + 1);
	for (i = 0; i < inherit->num_qgroups; ++i) {
2298
		if (*i_qgroups) {
2299
			ret = add_relation_rb(fs_info, objectid, *i_qgroups);
2300 2301 2302
			if (ret)
				goto unlock;
		}
2303 2304 2305
		++i_qgroups;
	}

2306
	for (i = 0; i <  inherit->num_ref_copies; ++i, i_qgroups += 2) {
2307 2308 2309
		struct btrfs_qgroup *src;
		struct btrfs_qgroup *dst;

2310 2311 2312
		if (!i_qgroups[0] || !i_qgroups[1])
			continue;

2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
		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;
	}
2324
	for (i = 0; i <  inherit->num_excl_copies; ++i, i_qgroups += 2) {
2325 2326 2327
		struct btrfs_qgroup *src;
		struct btrfs_qgroup *dst;

2328 2329 2330
		if (!i_qgroups[0] || !i_qgroups[1])
			continue;

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345
		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:
2346
	mutex_unlock(&fs_info->qgroup_ioctl_lock);
2347 2348 2349
	return ret;
}

2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363
static bool qgroup_check_limits(const struct btrfs_qgroup *qg, u64 num_bytes)
{
	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_RFER) &&
	    qg->reserved + (s64)qg->rfer + num_bytes > qg->max_rfer)
		return false;

	if ((qg->lim_flags & BTRFS_QGROUP_LIMIT_MAX_EXCL) &&
	    qg->reserved + (s64)qg->excl + num_bytes > qg->max_excl)
		return false;

	return true;
}

static int qgroup_reserve(struct btrfs_root *root, u64 num_bytes, bool enforce)
2364 2365 2366 2367 2368 2369
{
	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;
2370
	int retried = 0;
2371 2372 2373 2374 2375 2376 2377 2378
	struct ulist_node *unode;
	struct ulist_iterator uiter;

	if (!is_fstree(ref_root))
		return 0;

	if (num_bytes == 0)
		return 0;
2379
retry:
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
	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
	 */
2393 2394
	ulist_reinit(fs_info->qgroup_ulist);
	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
2395 2396 2397
			(uintptr_t)qgroup, GFP_ATOMIC);
	if (ret < 0)
		goto out;
2398
	ULIST_ITER_INIT(&uiter);
2399
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2400 2401 2402
		struct btrfs_qgroup *qg;
		struct btrfs_qgroup_list *glist;

2403
		qg = unode_aux_to_qgroup(unode);
2404

2405
		if (enforce && !qgroup_check_limits(qg, num_bytes)) {
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
			/*
			 * Commit the tree and retry, since we may have
			 * deletions which would free up space.
			 */
			if (!retried && qg->reserved > 0) {
				struct btrfs_trans_handle *trans;

				spin_unlock(&fs_info->qgroup_lock);
				ret = btrfs_start_delalloc_inodes(root, 0);
				if (ret)
					return ret;
				btrfs_wait_ordered_extents(root, -1, 0, (u64)-1);
				trans = btrfs_join_transaction(root);
				if (IS_ERR(trans))
					return PTR_ERR(trans);
				ret = btrfs_commit_transaction(trans);
				if (ret)
					return ret;
				retried++;
				goto retry;
			}
2427
			ret = -EDQUOT;
2428 2429
			goto out;
		}
2430 2431

		list_for_each_entry(glist, &qg->groups, next_group) {
2432 2433
			ret = ulist_add(fs_info->qgroup_ulist,
					glist->group->qgroupid,
2434 2435 2436
					(uintptr_t)glist->group, GFP_ATOMIC);
			if (ret < 0)
				goto out;
2437 2438
		}
	}
2439
	ret = 0;
2440 2441 2442 2443
	/*
	 * no limits exceeded, now record the reservation into all qgroups
	 */
	ULIST_ITER_INIT(&uiter);
2444
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2445 2446
		struct btrfs_qgroup *qg;

2447
		qg = unode_aux_to_qgroup(unode);
2448

2449
		qg->reserved += num_bytes;
2450 2451 2452 2453 2454 2455 2456
	}

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

2457 2458
void btrfs_qgroup_free_refroot(struct btrfs_fs_info *fs_info,
			       u64 ref_root, u64 num_bytes)
2459 2460 2461 2462 2463
{
	struct btrfs_root *quota_root;
	struct btrfs_qgroup *qgroup;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
2464
	int ret = 0;
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481

	if (!is_fstree(ref_root))
		return;

	if (num_bytes == 0)
		return;

	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;

2482 2483
	ulist_reinit(fs_info->qgroup_ulist);
	ret = ulist_add(fs_info->qgroup_ulist, qgroup->qgroupid,
2484 2485 2486
			(uintptr_t)qgroup, GFP_ATOMIC);
	if (ret < 0)
		goto out;
2487
	ULIST_ITER_INIT(&uiter);
2488
	while ((unode = ulist_next(fs_info->qgroup_ulist, &uiter))) {
2489 2490 2491
		struct btrfs_qgroup *qg;
		struct btrfs_qgroup_list *glist;

2492
		qg = unode_aux_to_qgroup(unode);
2493

2494 2495 2496 2497
		if (WARN_ON(qg->reserved < num_bytes))
			report_reserved_underflow(fs_info, qg, num_bytes);
		else
			qg->reserved -= num_bytes;
2498 2499

		list_for_each_entry(glist, &qg->groups, next_group) {
2500 2501
			ret = ulist_add(fs_info->qgroup_ulist,
					glist->group->qgroupid,
2502 2503 2504
					(uintptr_t)glist->group, GFP_ATOMIC);
			if (ret < 0)
				goto out;
2505 2506 2507 2508 2509 2510 2511
		}
	}

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

J
Jan Schmidt 已提交
2512 2513
/*
 * returns < 0 on error, 0 when more leafs are to be scanned.
2514
 * returns 1 when done.
J
Jan Schmidt 已提交
2515 2516
 */
static int
2517
qgroup_rescan_leaf(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
2518
		   struct btrfs_trans_handle *trans)
J
Jan Schmidt 已提交
2519 2520
{
	struct btrfs_key found;
2521
	struct extent_buffer *scratch_leaf = NULL;
J
Jan Schmidt 已提交
2522
	struct ulist *roots = NULL;
2523
	struct seq_list tree_mod_seq_elem = SEQ_LIST_INIT(tree_mod_seq_elem);
J
Josef Bacik 已提交
2524
	u64 num_bytes;
J
Jan Schmidt 已提交
2525 2526 2527 2528 2529 2530 2531 2532
	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);

2533 2534 2535 2536 2537
	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 已提交
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558

	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;
	}

	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;

	btrfs_get_tree_mod_seq(fs_info, &tree_mod_seq_elem);
2559 2560 2561 2562 2563 2564 2565 2566 2567
	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 已提交
2568 2569 2570 2571 2572 2573
	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);
2574 2575
		if (found.type != BTRFS_EXTENT_ITEM_KEY &&
		    found.type != BTRFS_METADATA_ITEM_KEY)
J
Jan Schmidt 已提交
2576
			continue;
2577
		if (found.type == BTRFS_METADATA_ITEM_KEY)
2578
			num_bytes = fs_info->nodesize;
2579 2580 2581
		else
			num_bytes = found.offset;

J
Josef Bacik 已提交
2582 2583
		ret = btrfs_find_all_roots(NULL, fs_info, found.objectid, 0,
					   &roots);
J
Jan Schmidt 已提交
2584 2585
		if (ret < 0)
			goto out;
2586 2587 2588 2589
		/* For rescan, just pass old_roots as NULL */
		ret = btrfs_qgroup_account_extent(trans, fs_info,
				found.objectid, num_bytes, NULL, roots);
		if (ret < 0)
J
Josef Bacik 已提交
2590
			goto out;
J
Jan Schmidt 已提交
2591 2592
	}
out:
2593 2594 2595 2596
	if (scratch_leaf) {
		btrfs_tree_read_unlock_blocking(scratch_leaf);
		free_extent_buffer(scratch_leaf);
	}
J
Jan Schmidt 已提交
2597 2598 2599 2600 2601
	btrfs_put_tree_mod_seq(fs_info, &tree_mod_seq_elem);

	return ret;
}

2602
static void btrfs_qgroup_rescan_worker(struct btrfs_work *work)
J
Jan Schmidt 已提交
2603
{
2604 2605
	struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
						     qgroup_rescan_work);
J
Jan Schmidt 已提交
2606 2607 2608
	struct btrfs_path *path;
	struct btrfs_trans_handle *trans = NULL;
	int err = -ENOMEM;
2609
	int ret = 0;
J
Jan Schmidt 已提交
2610 2611 2612 2613 2614 2615

	path = btrfs_alloc_path();
	if (!path)
		goto out;

	err = 0;
2616
	while (!err && !btrfs_fs_closing(fs_info)) {
J
Jan Schmidt 已提交
2617 2618 2619 2620 2621
		trans = btrfs_start_transaction(fs_info->fs_root, 0);
		if (IS_ERR(trans)) {
			err = PTR_ERR(trans);
			break;
		}
2622
		if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
J
Jan Schmidt 已提交
2623 2624
			err = -EINTR;
		} else {
2625
			err = qgroup_rescan_leaf(fs_info, path, trans);
J
Jan Schmidt 已提交
2626 2627
		}
		if (err > 0)
2628
			btrfs_commit_transaction(trans);
J
Jan Schmidt 已提交
2629
		else
2630
			btrfs_end_transaction(trans);
J
Jan Schmidt 已提交
2631 2632 2633 2634 2635 2636
	}

out:
	btrfs_free_path(path);

	mutex_lock(&fs_info->qgroup_rescan_lock);
2637 2638
	if (!btrfs_fs_closing(fs_info))
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
J
Jan Schmidt 已提交
2639

2640
	if (err > 0 &&
J
Jan Schmidt 已提交
2641 2642 2643 2644 2645 2646 2647
	    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);

2648
	/*
2649
	 * only update status, since the previous part has already updated the
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662
	 * qgroup info.
	 */
	trans = btrfs_start_transaction(fs_info->quota_root, 1);
	if (IS_ERR(trans)) {
		err = PTR_ERR(trans);
		btrfs_err(fs_info,
			  "fail to start transaction for status update: %d\n",
			  err);
		goto done;
	}
	ret = update_qgroup_status_item(trans, fs_info, fs_info->quota_root);
	if (ret < 0) {
		err = ret;
2663
		btrfs_err(fs_info, "fail to update qgroup status: %d", err);
2664
	}
2665
	btrfs_end_transaction(trans);
2666

2667 2668 2669
	if (btrfs_fs_closing(fs_info)) {
		btrfs_info(fs_info, "qgroup scan paused");
	} else if (err >= 0) {
2670
		btrfs_info(fs_info, "qgroup scan completed%s",
2671
			err > 0 ? " (inconsistency flag cleared)" : "");
J
Jan Schmidt 已提交
2672
	} else {
2673
		btrfs_err(fs_info, "qgroup scan failed with %d", err);
J
Jan Schmidt 已提交
2674
	}
2675

2676
done:
2677 2678 2679
	mutex_lock(&fs_info->qgroup_rescan_lock);
	fs_info->qgroup_rescan_running = false;
	mutex_unlock(&fs_info->qgroup_rescan_lock);
2680
	complete_all(&fs_info->qgroup_rescan_completion);
J
Jan Schmidt 已提交
2681 2682
}

2683 2684 2685 2686 2687 2688 2689
/*
 * 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 已提交
2690 2691 2692
{
	int ret = 0;

2693 2694 2695 2696 2697 2698
	if (!init_flags &&
	    (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN) ||
	     !(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))) {
		ret = -EINVAL;
		goto err;
	}
J
Jan Schmidt 已提交
2699 2700 2701

	mutex_lock(&fs_info->qgroup_rescan_lock);
	spin_lock(&fs_info->qgroup_lock);
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714

	if (init_flags) {
		if (fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_RESCAN)
			ret = -EINPROGRESS;
		else if (!(fs_info->qgroup_flags & BTRFS_QGROUP_STATUS_FLAG_ON))
			ret = -EINVAL;

		if (ret) {
			spin_unlock(&fs_info->qgroup_lock);
			mutex_unlock(&fs_info->qgroup_rescan_lock);
			goto err;
		}
		fs_info->qgroup_flags |= BTRFS_QGROUP_STATUS_FLAG_RESCAN;
J
Jan Schmidt 已提交
2715 2716 2717 2718
	}

	memset(&fs_info->qgroup_rescan_progress, 0,
		sizeof(fs_info->qgroup_rescan_progress));
2719
	fs_info->qgroup_rescan_progress.objectid = progress_objectid;
2720
	init_completion(&fs_info->qgroup_rescan_completion);
2721
	fs_info->qgroup_rescan_running = true;
2722 2723 2724 2725 2726 2727

	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));
2728
	btrfs_init_work(&fs_info->qgroup_rescan_work,
2729
			btrfs_qgroup_rescan_helper,
2730
			btrfs_qgroup_rescan_worker, NULL, NULL);
2731 2732 2733

	if (ret) {
err:
2734
		btrfs_info(fs_info, "qgroup_rescan_init failed with %d", ret);
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
		return ret;
	}

	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 已提交
2748 2749 2750 2751 2752 2753 2754 2755 2756
	/* 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;
	}
	spin_unlock(&fs_info->qgroup_lock);
2757
}
J
Jan Schmidt 已提交
2758

2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
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);
	}
2785
	ret = btrfs_commit_transaction(trans);
2786 2787 2788 2789 2790 2791 2792
	if (ret) {
		fs_info->qgroup_flags &= ~BTRFS_QGROUP_STATUS_FLAG_RESCAN;
		return ret;
	}

	qgroup_rescan_zero_tracking(fs_info);

2793 2794
	btrfs_queue_work(fs_info->qgroup_rescan_workers,
			 &fs_info->qgroup_rescan_work);
J
Jan Schmidt 已提交
2795 2796 2797

	return 0;
}
2798

2799 2800
int btrfs_qgroup_wait_for_completion(struct btrfs_fs_info *fs_info,
				     bool interruptible)
2801 2802 2803 2804 2805 2806
{
	int running;
	int ret = 0;

	mutex_lock(&fs_info->qgroup_rescan_lock);
	spin_lock(&fs_info->qgroup_lock);
2807
	running = fs_info->qgroup_rescan_running;
2808 2809 2810
	spin_unlock(&fs_info->qgroup_lock);
	mutex_unlock(&fs_info->qgroup_rescan_lock);

2811 2812 2813 2814
	if (!running)
		return 0;

	if (interruptible)
2815 2816
		ret = wait_for_completion_interruptible(
					&fs_info->qgroup_rescan_completion);
2817 2818
	else
		wait_for_completion(&fs_info->qgroup_rescan_completion);
2819 2820 2821

	return ret;
}
2822 2823 2824 2825 2826 2827 2828 2829 2830

/*
 * 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)
2831 2832
		btrfs_queue_work(fs_info->qgroup_rescan_workers,
				 &fs_info->qgroup_rescan_work);
2833
}
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853

/*
 * 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.
 */
int btrfs_qgroup_reserve_data(struct inode *inode, u64 start, u64 len)
{
	struct btrfs_root *root = BTRFS_I(inode)->root;
	struct extent_changeset changeset;
	struct ulist_node *unode;
	struct ulist_iterator uiter;
	int ret;

2854 2855
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &root->fs_info->flags) ||
	    !is_fstree(root->objectid) || len == 0)
2856 2857 2858
		return 0;

	changeset.bytes_changed = 0;
2859
	ulist_init(&changeset.range_changed);
2860
	ret = set_record_extent_bits(&BTRFS_I(inode)->io_tree, start,
2861
			start + len -1, EXTENT_QGROUP_RESERVED, &changeset);
2862 2863 2864
	trace_btrfs_qgroup_reserve_data(inode, start, len,
					changeset.bytes_changed,
					QGROUP_RESERVE);
2865 2866
	if (ret < 0)
		goto cleanup;
2867
	ret = qgroup_reserve(root, changeset.bytes_changed, true);
2868 2869 2870
	if (ret < 0)
		goto cleanup;

2871
	ulist_release(&changeset.range_changed);
2872 2873 2874 2875 2876
	return ret;

cleanup:
	/* cleanup already reserved ranges */
	ULIST_ITER_INIT(&uiter);
2877
	while ((unode = ulist_next(&changeset.range_changed, &uiter)))
2878 2879 2880
		clear_extent_bit(&BTRFS_I(inode)->io_tree, unode->val,
				 unode->aux, EXTENT_QGROUP_RESERVED, 0, 0, NULL,
				 GFP_NOFS);
2881
	ulist_release(&changeset.range_changed);
2882 2883
	return ret;
}
2884 2885 2886 2887 2888

static int __btrfs_qgroup_release_data(struct inode *inode, u64 start, u64 len,
				       int free)
{
	struct extent_changeset changeset;
2889
	int trace_op = QGROUP_RELEASE;
2890 2891 2892
	int ret;

	changeset.bytes_changed = 0;
2893
	ulist_init(&changeset.range_changed);
2894
	ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, start, 
2895
			start + len -1, EXTENT_QGROUP_RESERVED, &changeset);
2896 2897 2898
	if (ret < 0)
		goto out;

2899
	if (free) {
2900 2901 2902
		btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
				BTRFS_I(inode)->root->objectid,
				changeset.bytes_changed);
2903 2904 2905 2906
		trace_op = QGROUP_FREE;
	}
	trace_btrfs_qgroup_release_data(inode, start, len,
					changeset.bytes_changed, trace_op);
2907
out:
2908
	ulist_release(&changeset.range_changed);
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945
	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.
 *
 * For data written to disk, use btrfs_qgroup_release_data().
 *
 * NOTE: This function may sleep for memory allocation.
 */
int btrfs_qgroup_free_data(struct inode *inode, u64 start, u64 len)
{
	return __btrfs_qgroup_release_data(inode, start, len, 1);
}

/*
 * 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)
{
	return __btrfs_qgroup_release_data(inode, start, len, 0);
}
2946

2947 2948
int btrfs_qgroup_reserve_meta(struct btrfs_root *root, int num_bytes,
			      bool enforce)
2949
{
2950
	struct btrfs_fs_info *fs_info = root->fs_info;
2951 2952
	int ret;

2953
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
2954
	    !is_fstree(root->objectid) || num_bytes == 0)
2955 2956
		return 0;

2957
	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
2958
	ret = qgroup_reserve(root, num_bytes, enforce);
2959 2960
	if (ret < 0)
		return ret;
2961
	atomic64_add(num_bytes, &root->qgroup_meta_rsv);
2962 2963 2964 2965 2966
	return ret;
}

void btrfs_qgroup_free_meta_all(struct btrfs_root *root)
{
2967
	struct btrfs_fs_info *fs_info = root->fs_info;
2968
	u64 reserved;
2969

2970
	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
2971
	    !is_fstree(root->objectid))
2972 2973
		return;

2974
	reserved = atomic64_xchg(&root->qgroup_meta_rsv, 0);
2975 2976
	if (reserved == 0)
		return;
2977
	btrfs_qgroup_free_refroot(fs_info, root->objectid, reserved);
2978 2979 2980 2981
}

void btrfs_qgroup_free_meta(struct btrfs_root *root, int num_bytes)
{
2982 2983 2984
	struct btrfs_fs_info *fs_info = root->fs_info;

	if (!test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags) ||
2985
	    !is_fstree(root->objectid))
2986 2987
		return;

2988
	BUG_ON(num_bytes != round_down(num_bytes, fs_info->nodesize));
2989 2990
	WARN_ON(atomic64_read(&root->qgroup_meta_rsv) < num_bytes);
	atomic64_sub(num_bytes, &root->qgroup_meta_rsv);
2991
	btrfs_qgroup_free_refroot(fs_info, root->objectid, num_bytes);
2992
}
2993 2994

/*
2995
 * Check qgroup reserved space leaking, normally at destroy inode
2996 2997 2998 2999 3000 3001 3002 3003 3004 3005
 * time
 */
void btrfs_qgroup_check_reserved_leak(struct inode *inode)
{
	struct extent_changeset changeset;
	struct ulist_node *unode;
	struct ulist_iterator iter;
	int ret;

	changeset.bytes_changed = 0;
3006
	ulist_init(&changeset.range_changed);
3007
	ret = clear_record_extent_bits(&BTRFS_I(inode)->io_tree, 0, (u64)-1,
3008
			EXTENT_QGROUP_RESERVED, &changeset);
3009 3010 3011 3012

	WARN_ON(ret < 0);
	if (WARN_ON(changeset.bytes_changed)) {
		ULIST_ITER_INIT(&iter);
3013
		while ((unode = ulist_next(&changeset.range_changed, &iter))) {
3014 3015 3016 3017
			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);
		}
3018 3019 3020 3021
		btrfs_qgroup_free_refroot(BTRFS_I(inode)->root->fs_info,
				BTRFS_I(inode)->root->objectid,
				changeset.bytes_changed);

3022
	}
3023
	ulist_release(&changeset.range_changed);
3024
}