File Index
Files and directories
Sign in
FILE

volumes.c

File preview with syntax highlighting.

linux-6.19.14/fs/btrfs/volumes.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * Copyright (C) 2007 Oracle.  All rights reserved.
   4 */
   5
   6#include <linux/sched.h>
   7#include <linux/sched/mm.h>
   8#include <linux/slab.h>
   9#include <linux/ratelimit.h>
  10#include <linux/kthread.h>
  11#include <linux/semaphore.h>
  12#include <linux/uuid.h>
  13#include <linux/list_sort.h>
  14#include <linux/namei.h>
  15#include "misc.h"
  16#include "disk-io.h"
  17#include "extent-tree.h"
  18#include "transaction.h"
  19#include "volumes.h"
  20#include "raid56.h"
  21#include "dev-replace.h"
  22#include "sysfs.h"
  23#include "tree-checker.h"
  24#include "space-info.h"
  25#include "block-group.h"
  26#include "discard.h"
  27#include "zoned.h"
  28#include "fs.h"
  29#include "accessors.h"
  30#include "uuid-tree.h"
  31#include "ioctl.h"
  32#include "relocation.h"
  33#include "scrub.h"
  34#include "super.h"
  35#include "raid-stripe-tree.h"
  36
  37#define BTRFS_BLOCK_GROUP_STRIPE_MASK	(BTRFS_BLOCK_GROUP_RAID0 | \
  38					 BTRFS_BLOCK_GROUP_RAID10 | \
  39					 BTRFS_BLOCK_GROUP_RAID56_MASK)
  40
  41struct btrfs_io_geometry {
  42	u32 stripe_index;
  43	u32 stripe_nr;
  44	int mirror_num;
  45	int num_stripes;
  46	u64 stripe_offset;
  47	u64 raid56_full_stripe_start;
  48	int max_errors;
  49	enum btrfs_map_op op;
  50	bool use_rst;
  51};
  52
  53const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
  54	[BTRFS_RAID_RAID10] = {
  55		.sub_stripes	= 2,
  56		.dev_stripes	= 1,
  57		.devs_max	= 0,	/* 0 == as many as possible */
  58		.devs_min	= 2,
  59		.tolerated_failures = 1,
  60		.devs_increment	= 2,
  61		.ncopies	= 2,
  62		.nparity        = 0,
  63		.raid_name	= "raid10",
  64		.bg_flag	= BTRFS_BLOCK_GROUP_RAID10,
  65		.mindev_error	= BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
  66	},
  67	[BTRFS_RAID_RAID1] = {
  68		.sub_stripes	= 1,
  69		.dev_stripes	= 1,
  70		.devs_max	= 2,
  71		.devs_min	= 2,
  72		.tolerated_failures = 1,
  73		.devs_increment	= 2,
  74		.ncopies	= 2,
  75		.nparity        = 0,
  76		.raid_name	= "raid1",
  77		.bg_flag	= BTRFS_BLOCK_GROUP_RAID1,
  78		.mindev_error	= BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
  79	},
  80	[BTRFS_RAID_RAID1C3] = {
  81		.sub_stripes	= 1,
  82		.dev_stripes	= 1,
  83		.devs_max	= 3,
  84		.devs_min	= 3,
  85		.tolerated_failures = 2,
  86		.devs_increment	= 3,
  87		.ncopies	= 3,
  88		.nparity        = 0,
  89		.raid_name	= "raid1c3",
  90		.bg_flag	= BTRFS_BLOCK_GROUP_RAID1C3,
  91		.mindev_error	= BTRFS_ERROR_DEV_RAID1C3_MIN_NOT_MET,
  92	},
  93	[BTRFS_RAID_RAID1C4] = {
  94		.sub_stripes	= 1,
  95		.dev_stripes	= 1,
  96		.devs_max	= 4,
  97		.devs_min	= 4,
  98		.tolerated_failures = 3,
  99		.devs_increment	= 4,
 100		.ncopies	= 4,
 101		.nparity        = 0,
 102		.raid_name	= "raid1c4",
 103		.bg_flag	= BTRFS_BLOCK_GROUP_RAID1C4,
 104		.mindev_error	= BTRFS_ERROR_DEV_RAID1C4_MIN_NOT_MET,
 105	},
 106	[BTRFS_RAID_DUP] = {
 107		.sub_stripes	= 1,
 108		.dev_stripes	= 2,
 109		.devs_max	= 1,
 110		.devs_min	= 1,
 111		.tolerated_failures = 0,
 112		.devs_increment	= 1,
 113		.ncopies	= 2,
 114		.nparity        = 0,
 115		.raid_name	= "dup",
 116		.bg_flag	= BTRFS_BLOCK_GROUP_DUP,
 117		.mindev_error	= 0,
 118	},
 119	[BTRFS_RAID_RAID0] = {
 120		.sub_stripes	= 1,
 121		.dev_stripes	= 1,
 122		.devs_max	= 0,
 123		.devs_min	= 1,
 124		.tolerated_failures = 0,
 125		.devs_increment	= 1,
 126		.ncopies	= 1,
 127		.nparity        = 0,
 128		.raid_name	= "raid0",
 129		.bg_flag	= BTRFS_BLOCK_GROUP_RAID0,
 130		.mindev_error	= 0,
 131	},
 132	[BTRFS_RAID_SINGLE] = {
 133		.sub_stripes	= 1,
 134		.dev_stripes	= 1,
 135		.devs_max	= 1,
 136		.devs_min	= 1,
 137		.tolerated_failures = 0,
 138		.devs_increment	= 1,
 139		.ncopies	= 1,
 140		.nparity        = 0,
 141		.raid_name	= "single",
 142		.bg_flag	= 0,
 143		.mindev_error	= 0,
 144	},
 145	[BTRFS_RAID_RAID5] = {
 146		.sub_stripes	= 1,
 147		.dev_stripes	= 1,
 148		.devs_max	= 0,
 149		.devs_min	= 2,
 150		.tolerated_failures = 1,
 151		.devs_increment	= 1,
 152		.ncopies	= 1,
 153		.nparity        = 1,
 154		.raid_name	= "raid5",
 155		.bg_flag	= BTRFS_BLOCK_GROUP_RAID5,
 156		.mindev_error	= BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
 157	},
 158	[BTRFS_RAID_RAID6] = {
 159		.sub_stripes	= 1,
 160		.dev_stripes	= 1,
 161		.devs_max	= 0,
 162		.devs_min	= 3,
 163		.tolerated_failures = 2,
 164		.devs_increment	= 1,
 165		.ncopies	= 1,
 166		.nparity        = 2,
 167		.raid_name	= "raid6",
 168		.bg_flag	= BTRFS_BLOCK_GROUP_RAID6,
 169		.mindev_error	= BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
 170	},
 171};
 172
 173/*
 174 * Convert block group flags (BTRFS_BLOCK_GROUP_*) to btrfs_raid_types, which
 175 * can be used as index to access btrfs_raid_array[].
 176 */
 177enum btrfs_raid_types __attribute_const__ btrfs_bg_flags_to_raid_index(u64 flags)
 178{
 179	const u64 profile = (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK);
 180
 181	if (!profile)
 182		return BTRFS_RAID_SINGLE;
 183
 184	return BTRFS_BG_FLAG_TO_INDEX(profile);
 185}
 186
 187const char *btrfs_bg_type_to_raid_name(u64 flags)
 188{
 189	const int index = btrfs_bg_flags_to_raid_index(flags);
 190
 191	if (index >= BTRFS_NR_RAID_TYPES)
 192		return NULL;
 193
 194	return btrfs_raid_array[index].raid_name;
 195}
 196
 197int btrfs_nr_parity_stripes(u64 type)
 198{
 199	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(type);
 200
 201	return btrfs_raid_array[index].nparity;
 202}
 203
 204/*
 205 * Fill @buf with textual description of @bg_flags, no more than @size_buf
 206 * bytes including terminating null byte.
 207 */
 208void btrfs_describe_block_groups(u64 bg_flags, char *buf, u32 size_buf)
 209{
 210	int i;
 211	int ret;
 212	char *bp = buf;
 213	u64 flags = bg_flags;
 214	u32 size_bp = size_buf;
 215
 216	if (!flags)
 217		return;
 218
 219#define DESCRIBE_FLAG(flag, desc)						\
 220	do {								\
 221		if (flags & (flag)) {					\
 222			ret = snprintf(bp, size_bp, "%s|", (desc));	\
 223			if (ret < 0 || ret >= size_bp)			\
 224				goto out_overflow;			\
 225			size_bp -= ret;					\
 226			bp += ret;					\
 227			flags &= ~(flag);				\
 228		}							\
 229	} while (0)
 230
 231	DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_DATA, "data");
 232	DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_SYSTEM, "system");
 233	DESCRIBE_FLAG(BTRFS_BLOCK_GROUP_METADATA, "metadata");
 234
 235	DESCRIBE_FLAG(BTRFS_AVAIL_ALLOC_BIT_SINGLE, "single");
 236	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
 237		DESCRIBE_FLAG(btrfs_raid_array[i].bg_flag,
 238			      btrfs_raid_array[i].raid_name);
 239#undef DESCRIBE_FLAG
 240
 241	if (flags) {
 242		ret = snprintf(bp, size_bp, "0x%llx|", flags);
 243		size_bp -= ret;
 244	}
 245
 246	if (size_bp < size_buf)
 247		buf[size_buf - size_bp - 1] = '\0'; /* remove last | */
 248
 249	/*
 250	 * The text is trimmed, it's up to the caller to provide sufficiently
 251	 * large buffer
 252	 */
 253out_overflow:;
 254}
 255
 256static int init_first_rw_device(struct btrfs_trans_handle *trans);
 257static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
 258static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
 259
 260/*
 261 * Device locking
 262 * ==============
 263 *
 264 * There are several mutexes that protect manipulation of devices and low-level
 265 * structures like chunks but not block groups, extents or files
 266 *
 267 * uuid_mutex (global lock)
 268 * ------------------------
 269 * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
 270 * the SCAN_DEV ioctl registration or from mount either implicitly (the first
 271 * device) or requested by the device= mount option
 272 *
 273 * the mutex can be very coarse and can cover long-running operations
 274 *
 275 * protects: updates to fs_devices counters like missing devices, rw devices,
 276 * seeding, structure cloning, opening/closing devices at mount/umount time
 277 *
 278 * global::fs_devs - add, remove, updates to the global list
 279 *
 280 * does not protect: manipulation of the fs_devices::devices list in general
 281 * but in mount context it could be used to exclude list modifications by eg.
 282 * scan ioctl
 283 *
 284 * btrfs_device::name - renames (write side), read is RCU
 285 *
 286 * fs_devices::device_list_mutex (per-fs, with RCU)
 287 * ------------------------------------------------
 288 * protects updates to fs_devices::devices, ie. adding and deleting
 289 *
 290 * simple list traversal with read-only actions can be done with RCU protection
 291 *
 292 * may be used to exclude some operations from running concurrently without any
 293 * modifications to the list (see write_all_supers)
 294 *
 295 * Is not required at mount and close times, because our device list is
 296 * protected by the uuid_mutex at that point.
 297 *
 298 * balance_mutex
 299 * -------------
 300 * protects balance structures (status, state) and context accessed from
 301 * several places (internally, ioctl)
 302 *
 303 * chunk_mutex
 304 * -----------
 305 * protects chunks, adding or removing during allocation, trim or when a new
 306 * device is added/removed. Additionally it also protects post_commit_list of
 307 * individual devices, since they can be added to the transaction's
 308 * post_commit_list only with chunk_mutex held.
 309 *
 310 * cleaner_mutex
 311 * -------------
 312 * a big lock that is held by the cleaner thread and prevents running subvolume
 313 * cleaning together with relocation or delayed iputs
 314 *
 315 *
 316 * Lock nesting
 317 * ============
 318 *
 319 * uuid_mutex
 320 *   device_list_mutex
 321 *     chunk_mutex
 322 *   balance_mutex
 323 *
 324 *
 325 * Exclusive operations
 326 * ====================
 327 *
 328 * Maintains the exclusivity of the following operations that apply to the
 329 * whole filesystem and cannot run in parallel.
 330 *
 331 * - Balance (*)
 332 * - Device add
 333 * - Device remove
 334 * - Device replace (*)
 335 * - Resize
 336 *
 337 * The device operations (as above) can be in one of the following states:
 338 *
 339 * - Running state
 340 * - Paused state
 341 * - Completed state
 342 *
 343 * Only device operations marked with (*) can go into the Paused state for the
 344 * following reasons:
 345 *
 346 * - ioctl (only Balance can be Paused through ioctl)
 347 * - filesystem remounted as read-only
 348 * - filesystem unmounted and mounted as read-only
 349 * - system power-cycle and filesystem mounted as read-only
 350 * - filesystem or device errors leading to forced read-only
 351 *
 352 * The status of exclusive operation is set and cleared atomically.
 353 * During the course of Paused state, fs_info::exclusive_operation remains set.
 354 * A device operation in Paused or Running state can be canceled or resumed
 355 * either by ioctl (Balance only) or when remounted as read-write.
 356 * The exclusive status is cleared when the device operation is canceled or
 357 * completed.
 358 */
 359
 360DEFINE_MUTEX(uuid_mutex);
 361static LIST_HEAD(fs_uuids);
 362struct list_head * __attribute_const__ btrfs_get_fs_uuids(void)
 363{
 364	return &fs_uuids;
 365}
 366
 367/*
 368 * Allocate new btrfs_fs_devices structure identified by a fsid.
 369 *
 370 * @fsid:    if not NULL, copy the UUID to fs_devices::fsid and to
 371 *           fs_devices::metadata_fsid
 372 *
 373 * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
 374 * The returned struct is not linked onto any lists and can be destroyed with
 375 * kfree() right away.
 376 */
 377static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
 378{
 379	struct btrfs_fs_devices *fs_devs;
 380
 381	fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
 382	if (!fs_devs)
 383		return ERR_PTR(-ENOMEM);
 384
 385	mutex_init(&fs_devs->device_list_mutex);
 386
 387	INIT_LIST_HEAD(&fs_devs->devices);
 388	INIT_LIST_HEAD(&fs_devs->alloc_list);
 389	INIT_LIST_HEAD(&fs_devs->fs_list);
 390	INIT_LIST_HEAD(&fs_devs->seed_list);
 391
 392	if (fsid) {
 393		memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
 394		memcpy(fs_devs->metadata_uuid, fsid, BTRFS_FSID_SIZE);
 395	}
 396
 397	return fs_devs;
 398}
 399
 400static void btrfs_free_device(struct btrfs_device *device)
 401{
 402	WARN_ON(!list_empty(&device->post_commit_list));
 403	/*
 404	 * No need to call kfree_rcu() nor do RCU lock/unlock, nothing is
 405	 * reading the device name.
 406	 */
 407	kfree(rcu_dereference_raw(device->name));
 408	btrfs_extent_io_tree_release(&device->alloc_state);
 409	btrfs_destroy_dev_zone_info(device);
 410	kfree(device);
 411}
 412
 413static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
 414{
 415	struct btrfs_device *device;
 416
 417	WARN_ON(fs_devices->opened);
 418	WARN_ON(fs_devices->holding);
 419	while (!list_empty(&fs_devices->devices)) {
 420		device = list_first_entry(&fs_devices->devices,
 421					  struct btrfs_device, dev_list);
 422		list_del(&device->dev_list);
 423		btrfs_free_device(device);
 424	}
 425	kfree(fs_devices);
 426}
 427
 428void __exit btrfs_cleanup_fs_uuids(void)
 429{
 430	struct btrfs_fs_devices *fs_devices;
 431
 432	while (!list_empty(&fs_uuids)) {
 433		fs_devices = list_first_entry(&fs_uuids, struct btrfs_fs_devices,
 434					      fs_list);
 435		list_del(&fs_devices->fs_list);
 436		free_fs_devices(fs_devices);
 437	}
 438}
 439
 440static bool match_fsid_fs_devices(const struct btrfs_fs_devices *fs_devices,
 441				  const u8 *fsid, const u8 *metadata_fsid)
 442{
 443	if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) != 0)
 444		return false;
 445
 446	if (!metadata_fsid)
 447		return true;
 448
 449	if (memcmp(metadata_fsid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE) != 0)
 450		return false;
 451
 452	return true;
 453}
 454
 455static noinline struct btrfs_fs_devices *find_fsid(
 456		const u8 *fsid, const u8 *metadata_fsid)
 457{
 458	struct btrfs_fs_devices *fs_devices;
 459
 460	ASSERT(fsid);
 461
 462	/* Handle non-split brain cases */
 463	list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
 464		if (match_fsid_fs_devices(fs_devices, fsid, metadata_fsid))
 465			return fs_devices;
 466	}
 467	return NULL;
 468}
 469
 470static int
 471btrfs_get_bdev_and_sb(const char *device_path, blk_mode_t flags, void *holder,
 472		      int flush, struct file **bdev_file,
 473		      struct btrfs_super_block **disk_super)
 474{
 475	struct block_device *bdev;
 476	int ret;
 477
 478	*bdev_file = bdev_file_open_by_path(device_path, flags, holder, &fs_holder_ops);
 479
 480	if (IS_ERR(*bdev_file)) {
 481		ret = PTR_ERR(*bdev_file);
 482		btrfs_err(NULL, "failed to open device for path %s with flags 0x%x: %d",
 483			  device_path, flags, ret);
 484		goto error;
 485	}
 486	bdev = file_bdev(*bdev_file);
 487
 488	if (flush)
 489		sync_blockdev(bdev);
 490	if (holder) {
 491		ret = set_blocksize(*bdev_file, BTRFS_BDEV_BLOCKSIZE);
 492		if (ret) {
 493			bdev_fput(*bdev_file);
 494			goto error;
 495		}
 496	}
 497	invalidate_bdev(bdev);
 498	*disk_super = btrfs_read_disk_super(bdev, 0, false);
 499	if (IS_ERR(*disk_super)) {
 500		ret = PTR_ERR(*disk_super);
 501		bdev_fput(*bdev_file);
 502		goto error;
 503	}
 504
 505	return 0;
 506
 507error:
 508	*disk_super = NULL;
 509	*bdev_file = NULL;
 510	return ret;
 511}
 512
 513/*
 514 *  Search and remove all stale devices (which are not mounted).  When both
 515 *  inputs are NULL, it will search and release all stale devices.
 516 *
 517 *  @devt:         Optional. When provided will it release all unmounted devices
 518 *                 matching this devt only.
 519 *  @skip_device:  Optional. Will skip this device when searching for the stale
 520 *                 devices.
 521 *
 522 *  Return:	0 for success or if @devt is 0.
 523 *		-EBUSY if @devt is a mounted device.
 524 *		-ENOENT if @devt does not match any device in the list.
 525 */
 526static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device)
 527{
 528	struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
 529	struct btrfs_device *device, *tmp_device;
 530	int ret;
 531	bool freed = false;
 532
 533	lockdep_assert_held(&uuid_mutex);
 534
 535	/* Return good status if there is no instance of devt. */
 536	ret = 0;
 537	list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
 538
 539		mutex_lock(&fs_devices->device_list_mutex);
 540		list_for_each_entry_safe(device, tmp_device,
 541					 &fs_devices->devices, dev_list) {
 542			if (skip_device && skip_device == device)
 543				continue;
 544			if (devt && devt != device->devt)
 545				continue;
 546			if (fs_devices->opened || fs_devices->holding) {
 547				if (devt)
 548					ret = -EBUSY;
 549				break;
 550			}
 551
 552			/* delete the stale device */
 553			fs_devices->num_devices--;
 554			list_del(&device->dev_list);
 555			btrfs_free_device(device);
 556
 557			freed = true;
 558		}
 559		mutex_unlock(&fs_devices->device_list_mutex);
 560
 561		if (fs_devices->num_devices == 0) {
 562			btrfs_sysfs_remove_fsid(fs_devices);
 563			list_del(&fs_devices->fs_list);
 564			free_fs_devices(fs_devices);
 565		}
 566	}
 567
 568	/* If there is at least one freed device return 0. */
 569	if (freed)
 570		return 0;
 571
 572	return ret;
 573}
 574
 575static struct btrfs_fs_devices *find_fsid_by_device(
 576					struct btrfs_super_block *disk_super,
 577					dev_t devt, bool *same_fsid_diff_dev)
 578{
 579	struct btrfs_fs_devices *fsid_fs_devices;
 580	struct btrfs_fs_devices *devt_fs_devices;
 581	const bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
 582					BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
 583	bool found_by_devt = false;
 584
 585	/* Find the fs_device by the usual method, if found use it. */
 586	fsid_fs_devices = find_fsid(disk_super->fsid,
 587		    has_metadata_uuid ? disk_super->metadata_uuid : NULL);
 588
 589	/* The temp_fsid feature is supported only with single device filesystem. */
 590	if (btrfs_super_num_devices(disk_super) != 1)
 591		return fsid_fs_devices;
 592
 593	/*
 594	 * A seed device is an integral component of the sprout device, which
 595	 * functions as a multi-device filesystem. So, temp-fsid feature is
 596	 * not supported.
 597	 */
 598	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING)
 599		return fsid_fs_devices;
 600
 601	/* Try to find a fs_devices by matching devt. */
 602	list_for_each_entry(devt_fs_devices, &fs_uuids, fs_list) {
 603		struct btrfs_device *device;
 604
 605		list_for_each_entry(device, &devt_fs_devices->devices, dev_list) {
 606			if (device->devt == devt) {
 607				found_by_devt = true;
 608				break;
 609			}
 610		}
 611		if (found_by_devt)
 612			break;
 613	}
 614
 615	if (found_by_devt) {
 616		/* Existing device. */
 617		if (fsid_fs_devices == NULL) {
 618			if (devt_fs_devices->opened == 0) {
 619				/* Stale device. */
 620				return NULL;
 621			} else {
 622				/* temp_fsid is mounting a subvol. */
 623				return devt_fs_devices;
 624			}
 625		} else {
 626			/* Regular or temp_fsid device mounting a subvol. */
 627			return devt_fs_devices;
 628		}
 629	} else {
 630		/* New device. */
 631		if (fsid_fs_devices == NULL) {
 632			return NULL;
 633		} else {
 634			/* sb::fsid is already used create a new temp_fsid. */
 635			*same_fsid_diff_dev = true;
 636			return NULL;
 637		}
 638	}
 639
 640	/* Not reached. */
 641}
 642
 643/*
 644 * This is only used on mount, and we are protected from competing things
 645 * messing with our fs_devices by the uuid_mutex, thus we do not need the
 646 * fs_devices->device_list_mutex here.
 647 */
 648static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
 649			struct btrfs_device *device, blk_mode_t flags,
 650			void *holder)
 651{
 652	struct file *bdev_file;
 653	struct btrfs_super_block *disk_super;
 654	u64 devid;
 655	int ret;
 656
 657	if (device->bdev)
 658		return -EINVAL;
 659	if (!device->name)
 660		return -EINVAL;
 661
 662	ret = btrfs_get_bdev_and_sb(rcu_dereference_raw(device->name), flags, holder, 1,
 663				    &bdev_file, &disk_super);
 664	if (ret)
 665		return ret;
 666
 667	devid = btrfs_stack_device_id(&disk_super->dev_item);
 668	if (devid != device->devid)
 669		goto error_free_page;
 670
 671	if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
 672		goto error_free_page;
 673
 674	device->generation = btrfs_super_generation(disk_super);
 675
 676	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
 677		if (btrfs_super_incompat_flags(disk_super) &
 678		    BTRFS_FEATURE_INCOMPAT_METADATA_UUID) {
 679			btrfs_err(NULL,
 680				  "invalid seeding and uuid-changed device detected");
 681			goto error_free_page;
 682		}
 683
 684		clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
 685		fs_devices->seeding = true;
 686	} else {
 687		if (bdev_read_only(file_bdev(bdev_file)))
 688			clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
 689		else
 690			set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
 691	}
 692
 693	if (!bdev_nonrot(file_bdev(bdev_file)))
 694		fs_devices->rotating = true;
 695
 696	if (bdev_max_discard_sectors(file_bdev(bdev_file)))
 697		fs_devices->discardable = true;
 698
 699	device->bdev_file = bdev_file;
 700	device->bdev = file_bdev(bdev_file);
 701	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
 702
 703	if (device->devt != device->bdev->bd_dev) {
 704		btrfs_warn(NULL,
 705			   "device %s maj:min changed from %d:%d to %d:%d",
 706			   rcu_dereference_raw(device->name), MAJOR(device->devt),
 707			   MINOR(device->devt), MAJOR(device->bdev->bd_dev),
 708			   MINOR(device->bdev->bd_dev));
 709
 710		device->devt = device->bdev->bd_dev;
 711	}
 712
 713	fs_devices->open_devices++;
 714	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
 715	    device->devid != BTRFS_DEV_REPLACE_DEVID) {
 716		fs_devices->rw_devices++;
 717		list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
 718	}
 719	btrfs_release_disk_super(disk_super);
 720
 721	return 0;
 722
 723error_free_page:
 724	btrfs_release_disk_super(disk_super);
 725	bdev_fput(bdev_file);
 726
 727	return -EINVAL;
 728}
 729
 730const u8 *btrfs_sb_fsid_ptr(const struct btrfs_super_block *sb)
 731{
 732	bool has_metadata_uuid = (btrfs_super_incompat_flags(sb) &
 733				  BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
 734
 735	return has_metadata_uuid ? sb->metadata_uuid : sb->fsid;
 736}
 737
 738static bool is_same_device(struct btrfs_device *device, const char *new_path)
 739{
 740	struct path old = { .mnt = NULL, .dentry = NULL };
 741	struct path new = { .mnt = NULL, .dentry = NULL };
 742	char AUTO_KFREE(old_path);
 743	bool is_same = false;
 744	int ret;
 745
 746	if (!device->name)
 747		goto out;
 748
 749	old_path = kzalloc(PATH_MAX, GFP_NOFS);
 750	if (!old_path)
 751		goto out;
 752
 753	rcu_read_lock();
 754	ret = strscpy(old_path, rcu_dereference(device->name), PATH_MAX);
 755	rcu_read_unlock();
 756	if (ret < 0)
 757		goto out;
 758
 759	ret = kern_path(old_path, LOOKUP_FOLLOW, &old);
 760	if (ret)
 761		goto out;
 762	ret = kern_path(new_path, LOOKUP_FOLLOW, &new);
 763	if (ret)
 764		goto out;
 765	if (path_equal(&old, &new))
 766		is_same = true;
 767out:
 768	path_put(&old);
 769	path_put(&new);
 770	return is_same;
 771}
 772
 773/*
 774 * Add new device to list of registered devices
 775 *
 776 * Returns:
 777 * device pointer which was just added or updated when successful
 778 * error pointer when failed
 779 */
 780static noinline struct btrfs_device *device_list_add(const char *path,
 781			   struct btrfs_super_block *disk_super,
 782			   bool *new_device_added)
 783{
 784	struct btrfs_device *device;
 785	struct btrfs_fs_devices *fs_devices = NULL;
 786	const char *name;
 787	u64 found_transid = btrfs_super_generation(disk_super);
 788	u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
 789	dev_t path_devt;
 790	int ret;
 791	bool same_fsid_diff_dev = false;
 792	bool has_metadata_uuid = (btrfs_super_incompat_flags(disk_super) &
 793		BTRFS_FEATURE_INCOMPAT_METADATA_UUID);
 794
 795	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
 796		btrfs_err(NULL,
 797"device %s has incomplete metadata_uuid change, please use btrfstune to complete",
 798			  path);
 799		return ERR_PTR(-EAGAIN);
 800	}
 801
 802	ret = lookup_bdev(path, &path_devt);
 803	if (ret) {
 804		btrfs_err(NULL, "failed to lookup block device for path %s: %d",
 805			  path, ret);
 806		return ERR_PTR(ret);
 807	}
 808
 809	fs_devices = find_fsid_by_device(disk_super, path_devt, &same_fsid_diff_dev);
 810
 811	if (!fs_devices) {
 812		fs_devices = alloc_fs_devices(disk_super->fsid);
 813		if (IS_ERR(fs_devices))
 814			return ERR_CAST(fs_devices);
 815
 816		if (has_metadata_uuid)
 817			memcpy(fs_devices->metadata_uuid,
 818			       disk_super->metadata_uuid, BTRFS_FSID_SIZE);
 819
 820		if (same_fsid_diff_dev) {
 821			generate_random_uuid(fs_devices->fsid);
 822			fs_devices->temp_fsid = true;
 823			btrfs_info(NULL, "device %s (%d:%d) using temp-fsid %pU",
 824				path, MAJOR(path_devt), MINOR(path_devt),
 825				fs_devices->fsid);
 826		}
 827
 828		mutex_lock(&fs_devices->device_list_mutex);
 829		list_add(&fs_devices->fs_list, &fs_uuids);
 830
 831		device = NULL;
 832	} else {
 833		struct btrfs_dev_lookup_args args = {
 834			.devid = devid,
 835			.uuid = disk_super->dev_item.uuid,
 836		};
 837
 838		mutex_lock(&fs_devices->device_list_mutex);
 839		device = btrfs_find_device(fs_devices, &args);
 840
 841		if (found_transid > fs_devices->latest_generation) {
 842			memcpy(fs_devices->fsid, disk_super->fsid,
 843					BTRFS_FSID_SIZE);
 844			memcpy(fs_devices->metadata_uuid,
 845			       btrfs_sb_fsid_ptr(disk_super), BTRFS_FSID_SIZE);
 846		}
 847	}
 848
 849	if (!device) {
 850		unsigned int nofs_flag;
 851
 852		if (fs_devices->opened) {
 853			btrfs_err(NULL,
 854"device %s (%d:%d) belongs to fsid %pU, and the fs is already mounted, scanned by %s (%d)",
 855				  path, MAJOR(path_devt), MINOR(path_devt),
 856				  fs_devices->fsid, current->comm,
 857				  task_pid_nr(current));
 858			mutex_unlock(&fs_devices->device_list_mutex);
 859			return ERR_PTR(-EBUSY);
 860		}
 861
 862		nofs_flag = memalloc_nofs_save();
 863		device = btrfs_alloc_device(NULL, &devid,
 864					    disk_super->dev_item.uuid, path);
 865		memalloc_nofs_restore(nofs_flag);
 866		if (IS_ERR(device)) {
 867			mutex_unlock(&fs_devices->device_list_mutex);
 868			/* we can safely leave the fs_devices entry around */
 869			return device;
 870		}
 871
 872		device->devt = path_devt;
 873
 874		list_add_rcu(&device->dev_list, &fs_devices->devices);
 875		fs_devices->num_devices++;
 876
 877		device->fs_devices = fs_devices;
 878		*new_device_added = true;
 879
 880		if (disk_super->label[0])
 881			pr_info(
 882"BTRFS: device label %s devid %llu transid %llu %s (%d:%d) scanned by %s (%d)\n",
 883				disk_super->label, devid, found_transid, path,
 884				MAJOR(path_devt), MINOR(path_devt),
 885				current->comm, task_pid_nr(current));
 886		else
 887			pr_info(
 888"BTRFS: device fsid %pU devid %llu transid %llu %s (%d:%d) scanned by %s (%d)\n",
 889				disk_super->fsid, devid, found_transid, path,
 890				MAJOR(path_devt), MINOR(path_devt),
 891				current->comm, task_pid_nr(current));
 892
 893	} else if (!device->name || !is_same_device(device, path)) {
 894		const char *old_name;
 895
 896		/*
 897		 * When FS is already mounted.
 898		 * 1. If you are here and if the device->name is NULL that
 899		 *    means this device was missing at time of FS mount.
 900		 * 2. If you are here and if the device->name is different
 901		 *    from 'path' that means either
 902		 *      a. The same device disappeared and reappeared with
 903		 *         different name. or
 904		 *      b. The missing-disk-which-was-replaced, has
 905		 *         reappeared now.
 906		 *
 907		 * We must allow 1 and 2a above. But 2b would be a spurious
 908		 * and unintentional.
 909		 *
 910		 * Further in case of 1 and 2a above, the disk at 'path'
 911		 * would have missed some transaction when it was away and
 912		 * in case of 2a the stale bdev has to be updated as well.
 913		 * 2b must not be allowed at all time.
 914		 */
 915
 916		/*
 917		 * For now, we do allow update to btrfs_fs_device through the
 918		 * btrfs dev scan cli after FS has been mounted.  We're still
 919		 * tracking a problem where systems fail mount by subvolume id
 920		 * when we reject replacement on a mounted FS.
 921		 */
 922		if (!fs_devices->opened && found_transid < device->generation) {
 923			/*
 924			 * That is if the FS is _not_ mounted and if you
 925			 * are here, that means there is more than one
 926			 * disk with same uuid and devid.We keep the one
 927			 * with larger generation number or the last-in if
 928			 * generation are equal.
 929			 */
 930			mutex_unlock(&fs_devices->device_list_mutex);
 931			btrfs_err(NULL,
 932"device %s already registered with a higher generation, found %llu expect %llu",
 933				  path, found_transid, device->generation);
 934			return ERR_PTR(-EEXIST);
 935		}
 936
 937		/*
 938		 * We are going to replace the device path for a given devid,
 939		 * make sure it's the same device if the device is mounted
 940		 *
 941		 * NOTE: the device->fs_info may not be reliable here so pass
 942		 * in a NULL to message helpers instead. This avoids a possible
 943		 * use-after-free when the fs_info and fs_info->sb are already
 944		 * torn down.
 945		 */
 946		if (device->bdev) {
 947			if (device->devt != path_devt) {
 948				mutex_unlock(&fs_devices->device_list_mutex);
 949				btrfs_warn(NULL,
 950	"duplicate device %s devid %llu generation %llu scanned by %s (%d)",
 951						  path, devid, found_transid,
 952						  current->comm,
 953						  task_pid_nr(current));
 954				return ERR_PTR(-EEXIST);
 955			}
 956			btrfs_info(NULL,
 957	"devid %llu device path %s changed to %s scanned by %s (%d)",
 958					  devid, btrfs_dev_name(device),
 959					  path, current->comm,
 960					  task_pid_nr(current));
 961		}
 962
 963		name = kstrdup(path, GFP_NOFS);
 964		if (!name) {
 965			mutex_unlock(&fs_devices->device_list_mutex);
 966			return ERR_PTR(-ENOMEM);
 967		}
 968		rcu_read_lock();
 969		old_name = rcu_dereference(device->name);
 970		rcu_read_unlock();
 971		rcu_assign_pointer(device->name, name);
 972		kfree_rcu_mightsleep(old_name);
 973
 974		if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
 975			fs_devices->missing_devices--;
 976			clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
 977		}
 978		device->devt = path_devt;
 979	}
 980
 981	/*
 982	 * Unmount does not free the btrfs_device struct but would zero
 983	 * generation along with most of the other members. So just update
 984	 * it back. We need it to pick the disk with largest generation
 985	 * (as above).
 986	 */
 987	if (!fs_devices->opened) {
 988		device->generation = found_transid;
 989		fs_devices->latest_generation = max_t(u64, found_transid,
 990						fs_devices->latest_generation);
 991	}
 992
 993	fs_devices->total_devices = btrfs_super_num_devices(disk_super);
 994
 995	mutex_unlock(&fs_devices->device_list_mutex);
 996	return device;
 997}
 998
 999static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
1000{
1001	struct btrfs_fs_devices *fs_devices;
1002	struct btrfs_device *device;
1003	struct btrfs_device *orig_dev;
1004	int ret = 0;
1005
1006	lockdep_assert_held(&uuid_mutex);
1007
1008	fs_devices = alloc_fs_devices(orig->fsid);
1009	if (IS_ERR(fs_devices))
1010		return fs_devices;
1011
1012	fs_devices->total_devices = orig->total_devices;
1013
1014	list_for_each_entry(orig_dev, &orig->devices, dev_list) {
1015		const char *dev_path = NULL;
1016
1017		/*
1018		 * This is ok to do without RCU read locked because we hold the
1019		 * uuid mutex so nothing we touch in here is going to disappear.
1020		 */
1021		if (orig_dev->name)
1022			dev_path = rcu_dereference_raw(orig_dev->name);
1023
1024		device = btrfs_alloc_device(NULL, &orig_dev->devid,
1025					    orig_dev->uuid, dev_path);
1026		if (IS_ERR(device)) {
1027			ret = PTR_ERR(device);
1028			goto error;
1029		}
1030
1031		if (orig_dev->zone_info) {
1032			struct btrfs_zoned_device_info *zone_info;
1033
1034			zone_info = btrfs_clone_dev_zone_info(orig_dev);
1035			if (!zone_info) {
1036				btrfs_free_device(device);
1037				ret = -ENOMEM;
1038				goto error;
1039			}
1040			device->zone_info = zone_info;
1041		}
1042
1043		list_add(&device->dev_list, &fs_devices->devices);
1044		device->fs_devices = fs_devices;
1045		fs_devices->num_devices++;
1046	}
1047	return fs_devices;
1048error:
1049	free_fs_devices(fs_devices);
1050	return ERR_PTR(ret);
1051}
1052
1053static void __btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices,
1054				      struct btrfs_device **latest_dev)
1055{
1056	struct btrfs_device *device, *next;
1057
1058	/* This is the initialized path, it is safe to release the devices. */
1059	list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
1060		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state)) {
1061			if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
1062				      &device->dev_state) &&
1063			    !test_bit(BTRFS_DEV_STATE_MISSING,
1064				      &device->dev_state) &&
1065			    (!*latest_dev ||
1066			     device->generation > (*latest_dev)->generation)) {
1067				*latest_dev = device;
1068			}
1069			continue;
1070		}
1071
1072		/*
1073		 * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
1074		 * in btrfs_init_dev_replace() so just continue.
1075		 */
1076		if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1077			continue;
1078
1079		if (device->bdev_file) {
1080			bdev_fput(device->bdev_file);
1081			device->bdev = NULL;
1082			device->bdev_file = NULL;
1083			fs_devices->open_devices--;
1084		}
1085		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1086			list_del_init(&device->dev_alloc_list);
1087			clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1088			fs_devices->rw_devices--;
1089		}
1090		list_del_init(&device->dev_list);
1091		fs_devices->num_devices--;
1092		btrfs_free_device(device);
1093	}
1094
1095}
1096
1097/*
1098 * After we have read the system tree and know devids belonging to this
1099 * filesystem, remove the device which does not belong there.
1100 */
1101void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices)
1102{
1103	struct btrfs_device *latest_dev = NULL;
1104	struct btrfs_fs_devices *seed_dev;
1105
1106	mutex_lock(&uuid_mutex);
1107	__btrfs_free_extra_devids(fs_devices, &latest_dev);
1108
1109	list_for_each_entry(seed_dev, &fs_devices->seed_list, seed_list)
1110		__btrfs_free_extra_devids(seed_dev, &latest_dev);
1111
1112	fs_devices->latest_dev = latest_dev;
1113
1114	mutex_unlock(&uuid_mutex);
1115}
1116
1117static void btrfs_close_bdev(struct btrfs_device *device)
1118{
1119	if (!device->bdev)
1120		return;
1121
1122	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1123		sync_blockdev(device->bdev);
1124		invalidate_bdev(device->bdev);
1125	}
1126
1127	bdev_fput(device->bdev_file);
1128}
1129
1130static void btrfs_close_one_device(struct btrfs_device *device)
1131{
1132	struct btrfs_fs_devices *fs_devices = device->fs_devices;
1133
1134	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1135	    device->devid != BTRFS_DEV_REPLACE_DEVID) {
1136		list_del_init(&device->dev_alloc_list);
1137		fs_devices->rw_devices--;
1138	}
1139
1140	if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1141		clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1142
1143	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
1144		clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
1145		fs_devices->missing_devices--;
1146	}
1147
1148	btrfs_close_bdev(device);
1149	if (device->bdev) {
1150		fs_devices->open_devices--;
1151		device->bdev = NULL;
1152		device->bdev_file = NULL;
1153	}
1154	clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
1155	btrfs_destroy_dev_zone_info(device);
1156
1157	device->fs_info = NULL;
1158	atomic_set(&device->dev_stats_ccnt, 0);
1159	btrfs_extent_io_tree_release(&device->alloc_state);
1160
1161	/*
1162	 * Reset the flush error record. We might have a transient flush error
1163	 * in this mount, and if so we aborted the current transaction and set
1164	 * the fs to an error state, guaranteeing no super blocks can be further
1165	 * committed. However that error might be transient and if we unmount the
1166	 * filesystem and mount it again, we should allow the mount to succeed
1167	 * (btrfs_check_rw_degradable() should not fail) - if after mounting the
1168	 * filesystem again we still get flush errors, then we will again abort
1169	 * any transaction and set the error state, guaranteeing no commits of
1170	 * unsafe super blocks.
1171	 */
1172	device->last_flush_error = 0;
1173
1174	/* Verify the device is back in a pristine state  */
1175	WARN_ON(test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state));
1176	WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1177	WARN_ON(!list_empty(&device->dev_alloc_list));
1178	WARN_ON(!list_empty(&device->post_commit_list));
1179}
1180
1181static void close_fs_devices(struct btrfs_fs_devices *fs_devices)
1182{
1183	struct btrfs_device *device, *tmp;
1184
1185	lockdep_assert_held(&uuid_mutex);
1186
1187	if (--fs_devices->opened > 0)
1188		return;
1189
1190	list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list)
1191		btrfs_close_one_device(device);
1192
1193	WARN_ON(fs_devices->open_devices);
1194	WARN_ON(fs_devices->rw_devices);
1195	fs_devices->opened = 0;
1196	fs_devices->seeding = false;
1197	fs_devices->fs_info = NULL;
1198}
1199
1200void btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1201{
1202	LIST_HEAD(list);
1203	struct btrfs_fs_devices *tmp;
1204
1205	mutex_lock(&uuid_mutex);
1206	close_fs_devices(fs_devices);
1207	if (!fs_devices->opened && !fs_devices->holding) {
1208		list_splice_init(&fs_devices->seed_list, &list);
1209
1210		/*
1211		 * If the struct btrfs_fs_devices is not assembled with any
1212		 * other device, it can be re-initialized during the next mount
1213		 * without the needing device-scan step. Therefore, it can be
1214		 * fully freed.
1215		 */
1216		if (fs_devices->num_devices == 1) {
1217			list_del(&fs_devices->fs_list);
1218			free_fs_devices(fs_devices);
1219		}
1220	}
1221
1222
1223	list_for_each_entry_safe(fs_devices, tmp, &list, seed_list) {
1224		close_fs_devices(fs_devices);
1225		list_del(&fs_devices->seed_list);
1226		free_fs_devices(fs_devices);
1227	}
1228	mutex_unlock(&uuid_mutex);
1229}
1230
1231static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1232				blk_mode_t flags, void *holder)
1233{
1234	struct btrfs_device *device;
1235	struct btrfs_device *latest_dev = NULL;
1236	struct btrfs_device *tmp_device;
1237	s64 __maybe_unused value = 0;
1238	int ret = 0;
1239
1240	list_for_each_entry_safe(device, tmp_device, &fs_devices->devices,
1241				 dev_list) {
1242		int ret2;
1243
1244		ret2 = btrfs_open_one_device(fs_devices, device, flags, holder);
1245		if (ret2 == 0 &&
1246		    (!latest_dev || device->generation > latest_dev->generation)) {
1247			latest_dev = device;
1248		} else if (ret2 == -ENODATA) {
1249			fs_devices->num_devices--;
1250			list_del(&device->dev_list);
1251			btrfs_free_device(device);
1252		}
1253		if (ret == 0 && ret2 != 0)
1254			ret = ret2;
1255	}
1256
1257	if (fs_devices->open_devices == 0) {
1258		if (ret)
1259			return ret;
1260		return -EINVAL;
1261	}
1262
1263	fs_devices->opened = 1;
1264	fs_devices->latest_dev = latest_dev;
1265	fs_devices->total_rw_bytes = 0;
1266	fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_REGULAR;
1267#ifdef CONFIG_BTRFS_EXPERIMENTAL
1268	fs_devices->rr_min_contig_read = BTRFS_DEFAULT_RR_MIN_CONTIG_READ;
1269	fs_devices->read_devid = latest_dev->devid;
1270	fs_devices->read_policy = btrfs_read_policy_to_enum(btrfs_get_mod_read_policy(),
1271							    &value);
1272	if (fs_devices->read_policy == BTRFS_READ_POLICY_RR)
1273		fs_devices->collect_fs_stats = true;
1274
1275	if (value) {
1276		if (fs_devices->read_policy == BTRFS_READ_POLICY_RR)
1277			fs_devices->rr_min_contig_read = value;
1278		if (fs_devices->read_policy == BTRFS_READ_POLICY_DEVID)
1279			fs_devices->read_devid = value;
1280	}
1281#else
1282	fs_devices->read_policy = BTRFS_READ_POLICY_PID;
1283#endif
1284
1285	return 0;
1286}
1287
1288static int devid_cmp(void *priv, const struct list_head *a,
1289		     const struct list_head *b)
1290{
1291	const struct btrfs_device *dev1, *dev2;
1292
1293	dev1 = list_entry(a, struct btrfs_device, dev_list);
1294	dev2 = list_entry(b, struct btrfs_device, dev_list);
1295
1296	if (dev1->devid < dev2->devid)
1297		return -1;
1298	else if (dev1->devid > dev2->devid)
1299		return 1;
1300	return 0;
1301}
1302
1303int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1304		       blk_mode_t flags, void *holder)
1305{
1306	int ret;
1307
1308	lockdep_assert_held(&uuid_mutex);
1309	/*
1310	 * The device_list_mutex cannot be taken here in case opening the
1311	 * underlying device takes further locks like open_mutex.
1312	 *
1313	 * We also don't need the lock here as this is called during mount and
1314	 * exclusion is provided by uuid_mutex
1315	 */
1316
1317	if (fs_devices->opened) {
1318		fs_devices->opened++;
1319		ret = 0;
1320	} else {
1321		list_sort(NULL, &fs_devices->devices, devid_cmp);
1322		ret = open_fs_devices(fs_devices, flags, holder);
1323	}
1324
1325	return ret;
1326}
1327
1328void btrfs_release_disk_super(struct btrfs_super_block *super)
1329{
1330	struct page *page = virt_to_page(super);
1331
1332	put_page(page);
1333}
1334
1335struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
1336						int copy_num, bool drop_cache)
1337{
1338	struct btrfs_super_block *super;
1339	struct page *page;
1340	u64 bytenr, bytenr_orig;
1341	struct address_space *mapping = bdev->bd_mapping;
1342	int ret;
1343
1344	bytenr_orig = btrfs_sb_offset(copy_num);
1345	ret = btrfs_sb_log_location_bdev(bdev, copy_num, READ, &bytenr);
1346	if (ret < 0) {
1347		if (ret == -ENOENT)
1348			ret = -EINVAL;
1349		return ERR_PTR(ret);
1350	}
1351
1352	if (bytenr + BTRFS_SUPER_INFO_SIZE >= bdev_nr_bytes(bdev))
1353		return ERR_PTR(-EINVAL);
1354
1355	if (drop_cache) {
1356		/* This should only be called with the primary sb. */
1357		ASSERT(copy_num == 0);
1358
1359		/*
1360		 * Drop the page of the primary superblock, so later read will
1361		 * always read from the device.
1362		 */
1363		invalidate_inode_pages2_range(mapping, bytenr >> PAGE_SHIFT,
1364				      (bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
1365	}
1366
1367	filemap_invalidate_lock(mapping);
1368	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
1369	filemap_invalidate_unlock(mapping);
1370	if (IS_ERR(page))
1371		return ERR_CAST(page);
1372
1373	super = page_address(page);
1374	if (btrfs_super_magic(super) != BTRFS_MAGIC ||
1375	    btrfs_super_bytenr(super) != bytenr_orig) {
1376		btrfs_release_disk_super(super);
1377		return ERR_PTR(-EINVAL);
1378	}
1379
1380	/*
1381	 * Make sure the last byte of label is properly NUL terminated.  We use
1382	 * '%s' to print the label, if not properly NUL terminated we can access
1383	 * beyond the label.
1384	 */
1385	if (super->label[0] && super->label[BTRFS_LABEL_SIZE - 1])
1386		super->label[BTRFS_LABEL_SIZE - 1] = 0;
1387
1388	return super;
1389}
1390
1391int btrfs_forget_devices(dev_t devt)
1392{
1393	int ret;
1394
1395	mutex_lock(&uuid_mutex);
1396	ret = btrfs_free_stale_devices(devt, NULL);
1397	mutex_unlock(&uuid_mutex);
1398
1399	return ret;
1400}
1401
1402static bool btrfs_skip_registration(struct btrfs_super_block *disk_super,
1403				    const char *path, dev_t devt,
1404				    bool mount_arg_dev)
1405{
1406	struct btrfs_fs_devices *fs_devices;
1407
1408	/*
1409	 * Do not skip device registration for mounted devices with matching
1410	 * maj:min but different paths. Booting without initrd relies on
1411	 * /dev/root initially, later replaced with the actual root device.
1412	 * A successful scan ensures grub2-probe selects the correct device.
1413	 */
1414	list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
1415		struct btrfs_device *device;
1416
1417		mutex_lock(&fs_devices->device_list_mutex);
1418
1419		if (!fs_devices->opened) {
1420			mutex_unlock(&fs_devices->device_list_mutex);
1421			continue;
1422		}
1423
1424		list_for_each_entry(device, &fs_devices->devices, dev_list) {
1425			if (device->bdev && (device->bdev->bd_dev == devt) &&
1426			    strcmp(rcu_dereference_raw(device->name), path) != 0) {
1427				mutex_unlock(&fs_devices->device_list_mutex);
1428
1429				/* Do not skip registration. */
1430				return false;
1431			}
1432		}
1433		mutex_unlock(&fs_devices->device_list_mutex);
1434	}
1435
1436	if (!mount_arg_dev && btrfs_super_num_devices(disk_super) == 1 &&
1437	    !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING))
1438		return true;
1439
1440	return false;
1441}
1442
1443/*
1444 * Look for a btrfs signature on a device. This may be called out of the mount path
1445 * and we are not allowed to call set_blocksize during the scan. The superblock
1446 * is read via pagecache.
1447 *
1448 * With @mount_arg_dev it's a scan during mount time that will always register
1449 * the device or return an error. Multi-device and seeding devices are registered
1450 * in both cases.
1451 */
1452struct btrfs_device *btrfs_scan_one_device(const char *path,
1453					   bool mount_arg_dev)
1454{
1455	struct btrfs_super_block *disk_super;
1456	bool new_device_added = false;
1457	struct btrfs_device *device = NULL;
1458	struct file *bdev_file;
1459	dev_t devt;
1460
1461	lockdep_assert_held(&uuid_mutex);
1462
1463	/*
1464	 * Avoid an exclusive open here, as the systemd-udev may initiate the
1465	 * device scan which may race with the user's mount or mkfs command,
1466	 * resulting in failure.
1467	 * Since the device scan is solely for reading purposes, there is no
1468	 * need for an exclusive open. Additionally, the devices are read again
1469	 * during the mount process. It is ok to get some inconsistent
1470	 * values temporarily, as the device paths of the fsid are the only
1471	 * required information for assembling the volume.
1472	 */
1473	bdev_file = bdev_file_open_by_path(path, BLK_OPEN_READ, NULL, NULL);
1474	if (IS_ERR(bdev_file))
1475		return ERR_CAST(bdev_file);
1476
1477	disk_super = btrfs_read_disk_super(file_bdev(bdev_file), 0, false);
1478	if (IS_ERR(disk_super)) {
1479		device = ERR_CAST(disk_super);
1480		goto error_bdev_put;
1481	}
1482
1483	devt = file_bdev(bdev_file)->bd_dev;
1484	if (btrfs_skip_registration(disk_super, path, devt, mount_arg_dev)) {
1485		btrfs_debug(NULL, "skip registering single non-seed device %s (%d:%d)",
1486			  path, MAJOR(devt), MINOR(devt));
1487
1488		btrfs_free_stale_devices(devt, NULL);
1489
1490		device = NULL;
1491		goto free_disk_super;
1492	}
1493
1494	device = device_list_add(path, disk_super, &new_device_added);
1495	if (!IS_ERR(device) && new_device_added)
1496		btrfs_free_stale_devices(device->devt, device);
1497
1498free_disk_super:
1499	btrfs_release_disk_super(disk_super);
1500
1501error_bdev_put:
1502	bdev_fput(bdev_file);
1503
1504	return device;
1505}
1506
1507/*
1508 * Find the first pending extent intersecting a range.
1509 *
1510 * @device:         the device to search
1511 * @start:          start of the range to check
1512 * @len:            length of the range to check
1513 * @pending_start:  output pointer for the start of the found pending extent
1514 * @pending_end:    output pointer for the end of the found pending extent (inclusive)
1515 *
1516 * Search for a pending chunk allocation that intersects the half-open range
1517 * [start, start + len).
1518 *
1519 * Return: true if a pending extent was found, false otherwise.
1520 * If the return value is true, store the first pending extent in
1521 * [*pending_start, *pending_end]. Otherwise, the two output variables
1522 * may still be modified, to something outside the range and should not
1523 * be used.
1524 */
1525static bool first_pending_extent(struct btrfs_device *device, u64 start, u64 len,
1526				 u64 *pending_start, u64 *pending_end)
1527{
1528	lockdep_assert_held(&device->fs_info->chunk_mutex);
1529
1530	if (btrfs_find_first_extent_bit(&device->alloc_state, start,
1531					pending_start, pending_end,
1532					CHUNK_ALLOCATED, NULL)) {
1533
1534		if (in_range(*pending_start, start, len) ||
1535		    in_range(start, *pending_start, *pending_end + 1 - *pending_start)) {
1536			return true;
1537		}
1538	}
1539	return false;
1540}
1541
1542/*
1543 * Find the first real hole accounting for pending extents.
1544 *
1545 * @device:         the device containing the candidate hole
1546 * @start:          input/output pointer for the hole start position
1547 * @len:            input/output pointer for the hole length
1548 * @min_hole_size:  the size of hole we are looking for
1549 *
1550 * Given a potential hole specified by [*start, *start + *len), check for pending
1551 * chunk allocations within that range. If pending extents are found, the hole is
1552 * adjusted to represent the first true free space that is large enough when
1553 * accounting for pending chunks.
1554 *
1555 * Note that this function must handle various cases involving non consecutive
1556 * pending extents.
1557 *
1558 * Returns: true if a suitable hole was found and false otherwise.
1559 * If the return value is true, then *start and *len are set to represent the hole.
1560 * If the return value is false, then *start is set to the largest hole we
1561 * found and *len is set to its length.
1562 * If there are no holes at all, then *start is set to the end of the range and
1563 * *len is set to 0.
1564 */
1565static bool find_hole_in_pending_extents(struct btrfs_device *device, u64 *start,
1566					 u64 *len, u64 min_hole_size)
1567{
1568	u64 pending_start, pending_end;
1569	u64 end;
1570	u64 max_hole_start = 0;
1571	u64 max_hole_len = 0;
1572
1573	lockdep_assert_held(&device->fs_info->chunk_mutex);
1574
1575	if (*len == 0)
1576		return false;
1577
1578	end = *start + *len - 1;
1579
1580	/*
1581	 * Loop until we either see a large enough hole or check every pending
1582	 * extent overlapping the candidate hole.
1583	 * At every hole that we observe, record it if it is the new max.
1584	 * At the end of the iteration, set the output variables to the max hole.
1585	 */
1586	while (true) {
1587		if (first_pending_extent(device, *start, *len, &pending_start, &pending_end)) {
1588			/*
1589			 * Case 1: the pending extent overlaps the start of
1590			 * candidate hole. That means the true hole is after the
1591			 * pending extent, but we need to find the next pending
1592			 * extent to properly size the hole. In the next loop,
1593			 * we will reduce to case 2 or 3.
1594			 * e.g.,
1595			 *
1596			 *   |----pending A----|    real hole     |----pending B----|
1597			 *            |           candidate hole        |
1598			 *         *start                              end
1599			 */
1600			if (pending_start <= *start) {
1601				*start = pending_end + 1;
1602				goto next;
1603			}
1604			/*
1605			 * Case 2: The pending extent starts after *start (and overlaps
1606			 * [*start, end), so the first hole just goes up to the start
1607			 * of the pending extent.
1608			 * e.g.,
1609			 *
1610			 *   |    real hole    |----pending A----|
1611			 *   |       candidate hole     |
1612			 * *start                      end
1613			 */
1614			*len = pending_start - *start;
1615			if (*len > max_hole_len) {
1616				max_hole_start = *start;
1617				max_hole_len = *len;
1618			}
1619			if (*len >= min_hole_size)
1620				break;
1621			/*
1622			 * If the hole wasn't big enough, then we advance past
1623			 * the pending extent and keep looking.
1624			 */
1625			*start = pending_end + 1;
1626			goto next;
1627		} else {
1628			/*
1629			 * Case 3: There is no pending extent overlapping the
1630			 * range [*start, *start + *len - 1], so the only remaining
1631			 * hole is the remaining range.
1632			 * e.g.,
1633			 *
1634			 *   |       candidate hole           |
1635			 *   |          real hole             |
1636			 * *start                            end
1637			 */
1638
1639			if (*len > max_hole_len) {
1640				max_hole_start = *start;
1641				max_hole_len = *len;
1642			}
1643			break;
1644		}
1645next:
1646		if (*start > end)
1647			break;
1648		*len = end - *start + 1;
1649	}
1650	if (max_hole_len) {
1651		*start = max_hole_start;
1652		*len = max_hole_len;
1653	} else {
1654		*start = end + 1;
1655		*len = 0;
1656	}
1657	return max_hole_len >= min_hole_size;
1658}
1659
1660static u64 dev_extent_search_start(struct btrfs_device *device)
1661{
1662	switch (device->fs_devices->chunk_alloc_policy) {
1663	default:
1664		btrfs_warn_unknown_chunk_allocation(device->fs_devices->chunk_alloc_policy);
1665		fallthrough;
1666	case BTRFS_CHUNK_ALLOC_REGULAR:
1667		return BTRFS_DEVICE_RANGE_RESERVED;
1668	case BTRFS_CHUNK_ALLOC_ZONED:
1669		/*
1670		 * We don't care about the starting region like regular
1671		 * allocator, because we anyway use/reserve the first two zones
1672		 * for superblock logging.
1673		 */
1674		return 0;
1675	}
1676}
1677
1678static bool dev_extent_hole_check_zoned(struct btrfs_device *device,
1679					u64 *hole_start, u64 *hole_size,
1680					u64 num_bytes)
1681{
1682	u64 zone_size = device->zone_info->zone_size;
1683	u64 pos;
1684	int ret;
1685	bool changed = false;
1686
1687	ASSERT(IS_ALIGNED(*hole_start, zone_size),
1688	       "hole_start=%llu zone_size=%llu", *hole_start, zone_size);
1689
1690	while (*hole_size > 0) {
1691		pos = btrfs_find_allocatable_zones(device, *hole_start,
1692						   *hole_start + *hole_size,
1693						   num_bytes);
1694		if (pos != *hole_start) {
1695			*hole_size = *hole_start + *hole_size - pos;
1696			*hole_start = pos;
1697			changed = true;
1698			if (*hole_size < num_bytes)
1699				break;
1700		}
1701
1702		ret = btrfs_ensure_empty_zones(device, pos, num_bytes);
1703
1704		/* Range is ensured to be empty */
1705		if (!ret)
1706			return changed;
1707
1708		/* Given hole range was invalid (outside of device) */
1709		if (ret == -ERANGE) {
1710			*hole_start += *hole_size;
1711			*hole_size = 0;
1712			return true;
1713		}
1714
1715		*hole_start += zone_size;
1716		*hole_size -= zone_size;
1717		changed = true;
1718	}
1719
1720	return changed;
1721}
1722
1723/*
1724 * Validate and adjust a hole for chunk allocation
1725 *
1726 * @device:      the device containing the candidate hole
1727 * @hole_start:  input/output pointer for the hole start position
1728 * @hole_size:   input/output pointer for the hole size
1729 * @num_bytes:   minimum allocation size required
1730 *
1731 * Check if the specified hole is suitable for allocation and adjust it if
1732 * necessary. The hole may be modified to skip over pending chunk allocations
1733 * and to satisfy stricter zoned requirements on zoned filesystems.
1734 *
1735 * For regular (non-zoned) allocation, if the hole after adjustment is smaller
1736 * than @num_bytes, the search continues past additional pending extents until
1737 * either a sufficiently large hole is found or no more pending extents exist.
1738 *
1739 * Return: true if a suitable hole was found and false otherwise.
1740 * If the return value is true, then *hole_start and *hole_size are set to
1741 * represent the hole we found.
1742 * If the return value is false, then *hole_start is set to the largest
1743 * hole we found and *hole_size is set to its length.
1744 * If there are no holes at all, then *hole_start is set to the end of the range
1745 * and *hole_size is set to 0.
1746 */
1747static bool dev_extent_hole_check(struct btrfs_device *device, u64 *hole_start,
1748				  u64 *hole_size, u64 num_bytes)
1749{
1750	bool found = false;
1751	const u64 hole_end = *hole_start + *hole_size - 1;
1752
1753	ASSERT(*hole_size > 0);
1754
1755again:
1756	*hole_size = hole_end - *hole_start + 1;
1757	found = find_hole_in_pending_extents(device, hole_start, hole_size, num_bytes);
1758	if (!found)
1759		return found;
1760	ASSERT(*hole_size >= num_bytes);
1761
1762	switch (device->fs_devices->chunk_alloc_policy) {
1763	default:
1764		btrfs_warn_unknown_chunk_allocation(device->fs_devices->chunk_alloc_policy);
1765		fallthrough;
1766	case BTRFS_CHUNK_ALLOC_REGULAR:
1767		return found;
1768	case BTRFS_CHUNK_ALLOC_ZONED:
1769		if (dev_extent_hole_check_zoned(device, hole_start, hole_size, num_bytes))
1770			goto again;
1771		break;
1772	}
1773
1774	return found;
1775}
1776
1777/*
1778 * Find free space in the specified device.
1779 *
1780 * @device:	  the device which we search the free space in
1781 * @num_bytes:	  the size of the free space that we need
1782 * @search_start: the position from which to begin the search
1783 * @start:	  store the start of the free space.
1784 * @len:	  the size of the free space. that we find, or the size
1785 *		  of the max free space if we don't find suitable free space
1786 *
1787 * This does a pretty simple search, the expectation is that it is called very
1788 * infrequently and that a given device has a small number of extents.
1789 *
1790 * @start is used to store the start of the free space if we find. But if we
1791 * don't find suitable free space, it will be used to store the start position
1792 * of the max free space.
1793 *
1794 * @len is used to store the size of the free space that we find.
1795 * But if we don't find suitable free space, it is used to store the size of
1796 * the max free space.
1797 *
1798 * NOTE: This function will search *commit* root of device tree, and does extra
1799 * check to ensure dev extents are not double allocated.
1800 * This makes the function safe to allocate dev extents but may not report
1801 * correct usable device space, as device extent freed in current transaction
1802 * is not reported as available.
1803 */
1804static int find_free_dev_extent(struct btrfs_device *device, u64 num_bytes,
1805				u64 *start, u64 *len)
1806{
1807	struct btrfs_fs_info *fs_info = device->fs_info;
1808	struct btrfs_root *root = fs_info->dev_root;
1809	struct btrfs_key key;
1810	struct btrfs_dev_extent *dev_extent;
1811	BTRFS_PATH_AUTO_FREE(path);
1812	u64 search_start;
1813	u64 hole_size;
1814	u64 max_hole_start;
1815	u64 max_hole_size = 0;
1816	u64 extent_end;
1817	u64 search_end = device->total_bytes;
1818	int ret;
1819	int slot;
1820	struct extent_buffer *l;
1821
1822	search_start = dev_extent_search_start(device);
1823	max_hole_start = search_start;
1824
1825	WARN_ON(device->zone_info &&
1826		!IS_ALIGNED(num_bytes, device->zone_info->zone_size));
1827
1828	path = btrfs_alloc_path();
1829	if (!path) {
1830		ret = -ENOMEM;
1831		goto out;
1832	}
1833
1834	if (search_start >= search_end ||
1835		test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1836		ret = -ENOSPC;
1837		goto out;
1838	}
1839
1840	path->reada = READA_FORWARD;
1841	path->search_commit_root = true;
1842	path->skip_locking = true;
1843
1844	key.objectid = device->devid;
1845	key.type = BTRFS_DEV_EXTENT_KEY;
1846	key.offset = search_start;
1847
1848	ret = btrfs_search_backwards(root, &key, path);
1849	if (ret < 0)
1850		goto out;
1851
1852	while (search_start < search_end) {
1853		l = path->nodes[0];
1854		slot = path->slots[0];
1855		if (slot >= btrfs_header_nritems(l)) {
1856			ret = btrfs_next_leaf(root, path);
1857			if (ret == 0)
1858				continue;
1859			if (ret < 0)
1860				goto out;
1861
1862			break;
1863		}
1864		btrfs_item_key_to_cpu(l, &key, slot);
1865
1866		if (key.objectid < device->devid)
1867			goto next;
1868
1869		if (key.objectid > device->devid)
1870			break;
1871
1872		if (key.type != BTRFS_DEV_EXTENT_KEY)
1873			goto next;
1874
1875		if (key.offset > search_end)
1876			break;
1877
1878		if (key.offset > search_start) {
1879			hole_size = key.offset - search_start;
1880			dev_extent_hole_check(device, &search_start, &hole_size,
1881					      num_bytes);
1882
1883			if (hole_size > max_hole_size) {
1884				max_hole_start = search_start;
1885				max_hole_size = hole_size;
1886			}
1887
1888			/*
1889			 * If this free space is greater than which we need,
1890			 * it must be the max free space that we have found
1891			 * until now, so max_hole_start must point to the start
1892			 * of this free space and the length of this free space
1893			 * is stored in max_hole_size. Thus, we return
1894			 * max_hole_start and max_hole_size and go back to the
1895			 * caller.
1896			 */
1897			if (hole_size >= num_bytes) {
1898				ret = 0;
1899				goto out;
1900			}
1901		}
1902
1903		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1904		extent_end = key.offset + btrfs_dev_extent_length(l,
1905								  dev_extent);
1906		if (extent_end > search_start)
1907			search_start = extent_end;
1908next:
1909		path->slots[0]++;
1910		cond_resched();
1911	}
1912
1913	/*
1914	 * At this point, search_start should be the end of
1915	 * allocated dev extents, and when shrinking the device,
1916	 * search_end may be smaller than search_start.
1917	 */
1918	if (search_end > search_start) {
1919		hole_size = search_end - search_start;
1920		dev_extent_hole_check(device, &search_start, &hole_size, num_bytes);
1921
1922		if (hole_size > max_hole_size) {
1923			max_hole_start = search_start;
1924			max_hole_size = hole_size;
1925		}
1926	}
1927
1928	/* See above. */
1929	if (max_hole_size < num_bytes)
1930		ret = -ENOSPC;
1931	else
1932		ret = 0;
1933
1934	ASSERT(max_hole_start + max_hole_size <= search_end,
1935	       "max_hole_start=%llu max_hole_size=%llu search_end=%llu",
1936	       max_hole_start, max_hole_size, search_end);
1937out:
1938	*start = max_hole_start;
1939	if (len)
1940		*len = max_hole_size;
1941	return ret;
1942}
1943
1944static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1945			  struct btrfs_device *device,
1946			  u64 start, u64 *dev_extent_len)
1947{
1948	struct btrfs_fs_info *fs_info = device->fs_info;
1949	struct btrfs_root *root = fs_info->dev_root;
1950	int ret;
1951	BTRFS_PATH_AUTO_FREE(path);
1952	struct btrfs_key key;
1953	struct btrfs_key found_key;
1954	struct extent_buffer *leaf = NULL;
1955	struct btrfs_dev_extent *extent = NULL;
1956
1957	path = btrfs_alloc_path();
1958	if (!path)
1959		return -ENOMEM;
1960
1961	key.objectid = device->devid;
1962	key.type = BTRFS_DEV_EXTENT_KEY;
1963	key.offset = start;
1964again:
1965	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1966	if (ret > 0) {
1967		ret = btrfs_previous_item(root, path, key.objectid,
1968					  BTRFS_DEV_EXTENT_KEY);
1969		if (ret)
1970			return ret;
1971		leaf = path->nodes[0];
1972		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1973		extent = btrfs_item_ptr(leaf, path->slots[0],
1974					struct btrfs_dev_extent);
1975		BUG_ON(found_key.offset > start || found_key.offset +
1976		       btrfs_dev_extent_length(leaf, extent) < start);
1977		key = found_key;
1978		btrfs_release_path(path);
1979		goto again;
1980	} else if (ret == 0) {
1981		leaf = path->nodes[0];
1982		extent = btrfs_item_ptr(leaf, path->slots[0],
1983					struct btrfs_dev_extent);
1984	} else {
1985		return ret;
1986	}
1987
1988	*dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1989
1990	ret = btrfs_del_item(trans, root, path);
1991	if (ret == 0)
1992		set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1993	return ret;
1994}
1995
1996static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1997{
1998	struct rb_node *n;
1999	u64 ret = 0;
2000
2001	read_lock(&fs_info->mapping_tree_lock);
2002	n = rb_last(&fs_info->mapping_tree.rb_root);
2003	if (n) {
2004		struct btrfs_chunk_map *map;
2005
2006		map = rb_entry(n, struct btrfs_chunk_map, rb_node);
2007		ret = map->start + map->chunk_len;
2008	}
2009	read_unlock(&fs_info->mapping_tree_lock);
2010
2011	return ret;
2012}
2013
2014static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
2015				    u64 *devid_ret)
2016{
2017	int ret;
2018	struct btrfs_key key;
2019	struct btrfs_key found_key;
2020	BTRFS_PATH_AUTO_FREE(path);
2021
2022	path = btrfs_alloc_path();
2023	if (!path)
2024		return -ENOMEM;
2025
2026	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2027	key.type = BTRFS_DEV_ITEM_KEY;
2028	key.offset = (u64)-1;
2029
2030	ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
2031	if (ret < 0)
2032		return ret;
2033
2034	if (unlikely(ret == 0)) {
2035		/* Corruption */
2036		btrfs_err(fs_info, "corrupted chunk tree devid -1 matched");
2037		return -EUCLEAN;
2038	}
2039
2040	ret = btrfs_previous_item(fs_info->chunk_root, path,
2041				  BTRFS_DEV_ITEMS_OBJECTID,
2042				  BTRFS_DEV_ITEM_KEY);
2043	if (ret) {
2044		*devid_ret = 1;
2045	} else {
2046		btrfs_item_key_to_cpu(path->nodes[0], &found_key,
2047				      path->slots[0]);
2048		*devid_ret = found_key.offset + 1;
2049	}
2050	return 0;
2051}
2052
2053/*
2054 * the device information is stored in the chunk root
2055 * the btrfs_device struct should be fully filled in
2056 */
2057static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
2058			    struct btrfs_device *device)
2059{
2060	int ret;
2061	BTRFS_PATH_AUTO_FREE(path);
2062	struct btrfs_dev_item *dev_item;
2063	struct extent_buffer *leaf;
2064	struct btrfs_key key;
2065	unsigned long ptr;
2066
2067	path = btrfs_alloc_path();
2068	if (!path)
2069		return -ENOMEM;
2070
2071	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2072	key.type = BTRFS_DEV_ITEM_KEY;
2073	key.offset = device->devid;
2074
2075	btrfs_reserve_chunk_metadata(trans, true);
2076	ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
2077				      &key, sizeof(*dev_item));
2078	btrfs_trans_release_chunk_metadata(trans);
2079	if (ret)
2080		return ret;
2081
2082	leaf = path->nodes[0];
2083	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2084
2085	btrfs_set_device_id(leaf, dev_item, device->devid);
2086	btrfs_set_device_generation(leaf, dev_item, 0);
2087	btrfs_set_device_type(leaf, dev_item, device->type);
2088	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2089	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2090	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2091	btrfs_set_device_total_bytes(leaf, dev_item,
2092				     btrfs_device_get_disk_total_bytes(device));
2093	btrfs_set_device_bytes_used(leaf, dev_item,
2094				    btrfs_device_get_bytes_used(device));
2095	btrfs_set_device_group(leaf, dev_item, 0);
2096	btrfs_set_device_seek_speed(leaf, dev_item, 0);
2097	btrfs_set_device_bandwidth(leaf, dev_item, 0);
2098	btrfs_set_device_start_offset(leaf, dev_item, 0);
2099
2100	ptr = btrfs_device_uuid(dev_item);
2101	write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
2102	ptr = btrfs_device_fsid(dev_item);
2103	write_extent_buffer(leaf, trans->fs_info->fs_devices->metadata_uuid,
2104			    ptr, BTRFS_FSID_SIZE);
2105
2106	return 0;
2107}
2108
2109/*
2110 * Function to update ctime/mtime for a given device path.
2111 * Mainly used for ctime/mtime based probe like libblkid.
2112 *
2113 * We don't care about errors here, this is just to be kind to userspace.
2114 */
2115static void update_dev_time(const char *device_path)
2116{
2117	struct path path;
2118
2119	if (!kern_path(device_path, LOOKUP_FOLLOW, &path)) {
2120		vfs_utimes(&path, NULL);
2121		path_put(&path);
2122	}
2123}
2124
2125static int btrfs_rm_dev_item(struct btrfs_trans_handle *trans,
2126			     struct btrfs_device *device)
2127{
2128	struct btrfs_root *root = device->fs_info->chunk_root;
2129	int ret;
2130	BTRFS_PATH_AUTO_FREE(path);
2131	struct btrfs_key key;
2132
2133	path = btrfs_alloc_path();
2134	if (!path)
2135		return -ENOMEM;
2136
2137	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2138	key.type = BTRFS_DEV_ITEM_KEY;
2139	key.offset = device->devid;
2140
2141	btrfs_reserve_chunk_metadata(trans, false);
2142	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2143	btrfs_trans_release_chunk_metadata(trans);
2144	if (ret > 0)
2145		return -ENOENT;
2146	if (ret < 0)
2147		return ret;
2148
2149	return btrfs_del_item(trans, root, path);
2150}
2151
2152/*
2153 * Verify that @num_devices satisfies the RAID profile constraints in the whole
2154 * filesystem. It's up to the caller to adjust that number regarding eg. device
2155 * replace.
2156 */
2157static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
2158		u64 num_devices)
2159{
2160	u64 all_avail;
2161	unsigned seq;
2162	int i;
2163
2164	do {
2165		seq = read_seqbegin(&fs_info->profiles_lock);
2166
2167		all_avail = fs_info->avail_data_alloc_bits |
2168			    fs_info->avail_system_alloc_bits |
2169			    fs_info->avail_metadata_alloc_bits;
2170	} while (read_seqretry(&fs_info->profiles_lock, seq));
2171
2172	for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2173		if (!(all_avail & btrfs_raid_array[i].bg_flag))
2174			continue;
2175
2176		if (num_devices < btrfs_raid_array[i].devs_min)
2177			return btrfs_raid_array[i].mindev_error;
2178	}
2179
2180	return 0;
2181}
2182
2183static struct btrfs_device * btrfs_find_next_active_device(
2184		struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
2185{
2186	struct btrfs_device *next_device;
2187
2188	list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
2189		if (next_device != device &&
2190		    !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
2191		    && next_device->bdev)
2192			return next_device;
2193	}
2194
2195	return NULL;
2196}
2197
2198/*
2199 * Helper function to check if the given device is part of s_bdev / latest_dev
2200 * and replace it with the provided or the next active device, in the context
2201 * where this function called, there should be always be another device (or
2202 * this_dev) which is active.
2203 */
2204void __cold btrfs_assign_next_active_device(struct btrfs_device *device,
2205					    struct btrfs_device *next_device)
2206{
2207	struct btrfs_fs_info *fs_info = device->fs_info;
2208
2209	if (!next_device)
2210		next_device = btrfs_find_next_active_device(fs_info->fs_devices,
2211							    device);
2212	ASSERT(next_device);
2213
2214	if (fs_info->sb->s_bdev &&
2215			(fs_info->sb->s_bdev == device->bdev))
2216		fs_info->sb->s_bdev = next_device->bdev;
2217
2218	if (fs_info->fs_devices->latest_dev->bdev == device->bdev)
2219		fs_info->fs_devices->latest_dev = next_device;
2220}
2221
2222/*
2223 * Return btrfs_fs_devices::num_devices excluding the device that's being
2224 * currently replaced.
2225 */
2226static u64 btrfs_num_devices(struct btrfs_fs_info *fs_info)
2227{
2228	u64 num_devices = fs_info->fs_devices->num_devices;
2229
2230	down_read(&fs_info->dev_replace.rwsem);
2231	if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
2232		ASSERT(num_devices > 1, "num_devices=%llu", num_devices);
2233		num_devices--;
2234	}
2235	up_read(&fs_info->dev_replace.rwsem);
2236
2237	return num_devices;
2238}
2239
2240static void btrfs_scratch_superblock(struct btrfs_fs_info *fs_info,
2241				     struct block_device *bdev, int copy_num)
2242{
2243	struct btrfs_super_block *disk_super;
2244	const size_t len = sizeof(disk_super->magic);
2245	const u64 bytenr = btrfs_sb_offset(copy_num);
2246	int ret;
2247
2248	disk_super = btrfs_read_disk_super(bdev, copy_num, false);
2249	if (IS_ERR(disk_super))
2250		return;
2251
2252	memset(&disk_super->magic, 0, len);
2253	folio_mark_dirty(virt_to_folio(disk_super));
2254	btrfs_release_disk_super(disk_super);
2255
2256	ret = sync_blockdev_range(bdev, bytenr, bytenr + len - 1);
2257	if (ret)
2258		btrfs_warn(fs_info, "error clearing superblock number %d (%d)",
2259			copy_num, ret);
2260}
2261
2262void btrfs_scratch_superblocks(struct btrfs_fs_info *fs_info, struct btrfs_device *device)
2263{
2264	int copy_num;
2265	struct block_device *bdev = device->bdev;
2266
2267	if (!bdev)
2268		return;
2269
2270	for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX; copy_num++) {
2271		if (bdev_is_zoned(bdev))
2272			btrfs_reset_sb_log_zones(bdev, copy_num);
2273		else
2274			btrfs_scratch_superblock(fs_info, bdev, copy_num);
2275	}
2276
2277	/* Notify udev that device has changed */
2278	btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
2279
2280	/* Update ctime/mtime for device path for libblkid */
2281	update_dev_time(rcu_dereference_raw(device->name));
2282}
2283
2284int btrfs_rm_device(struct btrfs_fs_info *fs_info,
2285		    struct btrfs_dev_lookup_args *args,
2286		    struct file **bdev_file)
2287{
2288	struct btrfs_trans_handle *trans;
2289	struct btrfs_device *device;
2290	struct btrfs_fs_devices *cur_devices;
2291	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2292	u64 num_devices;
2293	int ret = 0;
2294
2295	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
2296		btrfs_err(fs_info, "device remove not supported on extent tree v2 yet");
2297		return -EINVAL;
2298	}
2299
2300	/*
2301	 * The device list in fs_devices is accessed without locks (neither
2302	 * uuid_mutex nor device_list_mutex) as it won't change on a mounted
2303	 * filesystem and another device rm cannot run.
2304	 */
2305	num_devices = btrfs_num_devices(fs_info);
2306
2307	ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
2308	if (ret)
2309		return ret;
2310
2311	device = btrfs_find_device(fs_info->fs_devices, args);
2312	if (!device) {
2313		if (args->missing)
2314			ret = BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2315		else
2316			ret = -ENOENT;
2317		return ret;
2318	}
2319
2320	if (btrfs_pinned_by_swapfile(fs_info, device)) {
2321		btrfs_warn(fs_info,
2322		  "cannot remove device %s (devid %llu) due to active swapfile",
2323				  btrfs_dev_name(device), device->devid);
2324		return -ETXTBSY;
2325	}
2326
2327	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
2328		return BTRFS_ERROR_DEV_TGT_REPLACE;
2329
2330	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
2331	    fs_info->fs_devices->rw_devices == 1)
2332		return BTRFS_ERROR_DEV_ONLY_WRITABLE;
2333
2334	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2335		mutex_lock(&fs_info->chunk_mutex);
2336		list_del_init(&device->dev_alloc_list);
2337		device->fs_devices->rw_devices--;
2338		mutex_unlock(&fs_info->chunk_mutex);
2339	}
2340
2341	ret = btrfs_shrink_device(device, 0);
2342	if (ret)
2343		goto error_undo;
2344
2345	trans = btrfs_start_transaction(fs_info->chunk_root, 0);
2346	if (IS_ERR(trans)) {
2347		ret = PTR_ERR(trans);
2348		goto error_undo;
2349	}
2350
2351	ret = btrfs_rm_dev_item(trans, device);
2352	if (unlikely(ret)) {
2353		/* Any error in dev item removal is critical */
2354		btrfs_crit(fs_info,
2355			   "failed to remove device item for devid %llu: %d",
2356			   device->devid, ret);
2357		btrfs_abort_transaction(trans, ret);
2358		btrfs_end_transaction(trans);
2359		return ret;
2360	}
2361
2362	clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2363	btrfs_scrub_cancel_dev(device);
2364
2365	/*
2366	 * the device list mutex makes sure that we don't change
2367	 * the device list while someone else is writing out all
2368	 * the device supers. Whoever is writing all supers, should
2369	 * lock the device list mutex before getting the number of
2370	 * devices in the super block (super_copy). Conversely,
2371	 * whoever updates the number of devices in the super block
2372	 * (super_copy) should hold the device list mutex.
2373	 */
2374
2375	/*
2376	 * In normal cases the cur_devices == fs_devices. But in case
2377	 * of deleting a seed device, the cur_devices should point to
2378	 * its own fs_devices listed under the fs_devices->seed_list.
2379	 */
2380	cur_devices = device->fs_devices;
2381	mutex_lock(&fs_devices->device_list_mutex);
2382	list_del_rcu(&device->dev_list);
2383
2384	cur_devices->num_devices--;
2385	cur_devices->total_devices--;
2386	/* Update total_devices of the parent fs_devices if it's seed */
2387	if (cur_devices != fs_devices)
2388		fs_devices->total_devices--;
2389
2390	if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2391		cur_devices->missing_devices--;
2392
2393	btrfs_assign_next_active_device(device, NULL);
2394
2395	if (device->bdev_file) {
2396		cur_devices->open_devices--;
2397		/* remove sysfs entry */
2398		btrfs_sysfs_remove_device(device);
2399	}
2400
2401	num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2402	btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2403	mutex_unlock(&fs_devices->device_list_mutex);
2404
2405	/*
2406	 * At this point, the device is zero sized and detached from the
2407	 * devices list.  All that's left is to zero out the old supers and
2408	 * free the device.
2409	 *
2410	 * We cannot call btrfs_close_bdev() here because we're holding the sb
2411	 * write lock, and bdev_fput() on the block device will pull in the
2412	 * ->open_mutex on the block device and it's dependencies.  Instead
2413	 *  just flush the device and let the caller do the final bdev_release.
2414	 */
2415	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2416		btrfs_scratch_superblocks(fs_info, device);
2417		if (device->bdev) {
2418			sync_blockdev(device->bdev);
2419			invalidate_bdev(device->bdev);
2420		}
2421	}
2422
2423	*bdev_file = device->bdev_file;
2424	synchronize_rcu();
2425	btrfs_free_device(device);
2426
2427	/*
2428	 * This can happen if cur_devices is the private seed devices list.  We
2429	 * cannot call close_fs_devices() here because it expects the uuid_mutex
2430	 * to be held, but in fact we don't need that for the private
2431	 * seed_devices, we can simply decrement cur_devices->opened and then
2432	 * remove it from our list and free the fs_devices.
2433	 */
2434	if (cur_devices->num_devices == 0) {
2435		list_del_init(&cur_devices->seed_list);
2436		ASSERT(cur_devices->opened == 1, "opened=%d", cur_devices->opened);
2437		cur_devices->opened--;
2438		free_fs_devices(cur_devices);
2439	}
2440
2441	ret = btrfs_commit_transaction(trans);
2442
2443	return ret;
2444
2445error_undo:
2446	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2447		mutex_lock(&fs_info->chunk_mutex);
2448		list_add(&device->dev_alloc_list,
2449			 &fs_devices->alloc_list);
2450		device->fs_devices->rw_devices++;
2451		mutex_unlock(&fs_info->chunk_mutex);
2452	}
2453	return ret;
2454}
2455
2456void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2457{
2458	struct btrfs_fs_devices *fs_devices;
2459
2460	lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2461
2462	/*
2463	 * in case of fs with no seed, srcdev->fs_devices will point
2464	 * to fs_devices of fs_info. However when the dev being replaced is
2465	 * a seed dev it will point to the seed's local fs_devices. In short
2466	 * srcdev will have its correct fs_devices in both the cases.
2467	 */
2468	fs_devices = srcdev->fs_devices;
2469
2470	list_del_rcu(&srcdev->dev_list);
2471	list_del(&srcdev->dev_alloc_list);
2472	fs_devices->num_devices--;
2473	if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2474		fs_devices->missing_devices--;
2475
2476	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2477		fs_devices->rw_devices--;
2478
2479	if (srcdev->bdev)
2480		fs_devices->open_devices--;
2481}
2482
2483void btrfs_rm_dev_replace_free_srcdev(struct btrfs_device *srcdev)
2484{
2485	struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2486
2487	mutex_lock(&uuid_mutex);
2488
2489	btrfs_close_bdev(srcdev);
2490	synchronize_rcu();
2491	btrfs_free_device(srcdev);
2492
2493	/* if this is no devs we rather delete the fs_devices */
2494	if (!fs_devices->num_devices) {
2495		/*
2496		 * On a mounted FS, num_devices can't be zero unless it's a
2497		 * seed. In case of a seed device being replaced, the replace
2498		 * target added to the sprout FS, so there will be no more
2499		 * device left under the seed FS.
2500		 */
2501		ASSERT(fs_devices->seeding);
2502
2503		list_del_init(&fs_devices->seed_list);
2504		close_fs_devices(fs_devices);
2505		free_fs_devices(fs_devices);
2506	}
2507	mutex_unlock(&uuid_mutex);
2508}
2509
2510void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2511{
2512	struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2513
2514	mutex_lock(&fs_devices->device_list_mutex);
2515
2516	btrfs_sysfs_remove_device(tgtdev);
2517
2518	if (tgtdev->bdev)
2519		fs_devices->open_devices--;
2520
2521	fs_devices->num_devices--;
2522
2523	btrfs_assign_next_active_device(tgtdev, NULL);
2524
2525	list_del_rcu(&tgtdev->dev_list);
2526
2527	mutex_unlock(&fs_devices->device_list_mutex);
2528
2529	btrfs_scratch_superblocks(tgtdev->fs_info, tgtdev);
2530
2531	btrfs_close_bdev(tgtdev);
2532	synchronize_rcu();
2533	btrfs_free_device(tgtdev);
2534}
2535
2536/*
2537 * Populate args from device at path.
2538 *
2539 * @fs_info:	the filesystem
2540 * @args:	the args to populate
2541 * @path:	the path to the device
2542 *
2543 * This will read the super block of the device at @path and populate @args with
2544 * the devid, fsid, and uuid.  This is meant to be used for ioctls that need to
2545 * lookup a device to operate on, but need to do it before we take any locks.
2546 * This properly handles the special case of "missing" that a user may pass in,
2547 * and does some basic sanity checks.  The caller must make sure that @path is
2548 * properly NUL terminated before calling in, and must call
2549 * btrfs_put_dev_args_from_path() in order to free up the temporary fsid and
2550 * uuid buffers.
2551 *
2552 * Return: 0 for success, -errno for failure
2553 */
2554int btrfs_get_dev_args_from_path(struct btrfs_fs_info *fs_info,
2555				 struct btrfs_dev_lookup_args *args,
2556				 const char *path)
2557{
2558	struct btrfs_super_block *disk_super;
2559	struct file *bdev_file;
2560	int ret;
2561
2562	if (!path || !path[0])
2563		return -EINVAL;
2564	if (!strcmp(path, "missing")) {
2565		args->missing = true;
2566		return 0;
2567	}
2568
2569	args->uuid = kzalloc(BTRFS_UUID_SIZE, GFP_KERNEL);
2570	args->fsid = kzalloc(BTRFS_FSID_SIZE, GFP_KERNEL);
2571	if (!args->uuid || !args->fsid) {
2572		btrfs_put_dev_args_from_path(args);
2573		return -ENOMEM;
2574	}
2575
2576	ret = btrfs_get_bdev_and_sb(path, BLK_OPEN_READ, NULL, 0,
2577				    &bdev_file, &disk_super);
2578	if (ret) {
2579		btrfs_put_dev_args_from_path(args);
2580		return ret;
2581	}
2582
2583	args->devid = btrfs_stack_device_id(&disk_super->dev_item);
2584	memcpy(args->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE);
2585	if (btrfs_fs_incompat(fs_info, METADATA_UUID))
2586		memcpy(args->fsid, disk_super->metadata_uuid, BTRFS_FSID_SIZE);
2587	else
2588		memcpy(args->fsid, disk_super->fsid, BTRFS_FSID_SIZE);
2589	btrfs_release_disk_super(disk_super);
2590	bdev_fput(bdev_file);
2591	return 0;
2592}
2593
2594/*
2595 * Only use this jointly with btrfs_get_dev_args_from_path() because we will
2596 * allocate our ->uuid and ->fsid pointers, everybody else uses local variables
2597 * that don't need to be freed.
2598 */
2599void btrfs_put_dev_args_from_path(struct btrfs_dev_lookup_args *args)
2600{
2601	kfree(args->uuid);
2602	kfree(args->fsid);
2603	args->uuid = NULL;
2604	args->fsid = NULL;
2605}
2606
2607struct btrfs_device *btrfs_find_device_by_devspec(
2608		struct btrfs_fs_info *fs_info, u64 devid,
2609		const char *device_path)
2610{
2611	BTRFS_DEV_LOOKUP_ARGS(args);
2612	struct btrfs_device *device;
2613	int ret;
2614
2615	if (devid) {
2616		args.devid = devid;
2617		device = btrfs_find_device(fs_info->fs_devices, &args);
2618		if (!device)
2619			return ERR_PTR(-ENOENT);
2620		return device;
2621	}
2622
2623	ret = btrfs_get_dev_args_from_path(fs_info, &args, device_path);
2624	if (ret)
2625		return ERR_PTR(ret);
2626	device = btrfs_find_device(fs_info->fs_devices, &args);
2627	btrfs_put_dev_args_from_path(&args);
2628	if (!device)
2629		return ERR_PTR(-ENOENT);
2630	return device;
2631}
2632
2633static struct btrfs_fs_devices *btrfs_init_sprout(struct btrfs_fs_info *fs_info)
2634{
2635	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2636	struct btrfs_fs_devices *old_devices;
2637	struct btrfs_fs_devices *seed_devices;
2638
2639	lockdep_assert_held(&uuid_mutex);
2640	if (!fs_devices->seeding)
2641		return ERR_PTR(-EINVAL);
2642
2643	/*
2644	 * Private copy of the seed devices, anchored at
2645	 * fs_info->fs_devices->seed_list
2646	 */
2647	seed_devices = alloc_fs_devices(NULL);
2648	if (IS_ERR(seed_devices))
2649		return seed_devices;
2650
2651	/*
2652	 * It's necessary to retain a copy of the original seed fs_devices in
2653	 * fs_uuids so that filesystems which have been seeded can successfully
2654	 * reference the seed device from open_seed_devices. This also supports
2655	 * multiple fs seed.
2656	 */
2657	old_devices = clone_fs_devices(fs_devices);
2658	if (IS_ERR(old_devices)) {
2659		kfree(seed_devices);
2660		return old_devices;
2661	}
2662
2663	list_add(&old_devices->fs_list, &fs_uuids);
2664
2665	memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2666	seed_devices->opened = 1;
2667	INIT_LIST_HEAD(&seed_devices->devices);
2668	INIT_LIST_HEAD(&seed_devices->alloc_list);
2669	mutex_init(&seed_devices->device_list_mutex);
2670
2671	return seed_devices;
2672}
2673
2674/*
2675 * Splice seed devices into the sprout fs_devices.
2676 * Generate a new fsid for the sprouted read-write filesystem.
2677 */
2678static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
2679			       struct btrfs_fs_devices *seed_devices)
2680{
2681	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2682	struct btrfs_super_block *disk_super = fs_info->super_copy;
2683	struct btrfs_device *device;
2684	u64 super_flags;
2685
2686	/*
2687	 * We are updating the fsid, the thread leading to device_list_add()
2688	 * could race, so uuid_mutex is needed.
2689	 */
2690	lockdep_assert_held(&uuid_mutex);
2691
2692	/*
2693	 * The threads listed below may traverse dev_list but can do that without
2694	 * device_list_mutex:
2695	 * - All device ops and balance - as we are in btrfs_exclop_start.
2696	 * - Various dev_list readers - are using RCU.
2697	 * - btrfs_ioctl_fitrim() - is using RCU.
2698	 *
2699	 * For-read threads as below are using device_list_mutex:
2700	 * - Readonly scrub btrfs_scrub_dev()
2701	 * - Readonly scrub btrfs_scrub_progress()
2702	 * - btrfs_get_dev_stats()
2703	 */
2704	lockdep_assert_held(&fs_devices->device_list_mutex);
2705
2706	list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2707			      synchronize_rcu);
2708	list_for_each_entry(device, &seed_devices->devices, dev_list)
2709		device->fs_devices = seed_devices;
2710
2711	fs_devices->seeding = false;
2712	fs_devices->num_devices = 0;
2713	fs_devices->open_devices = 0;
2714	fs_devices->missing_devices = 0;
2715	fs_devices->rotating = false;
2716	list_add(&seed_devices->seed_list, &fs_devices->seed_list);
2717
2718	generate_random_uuid(fs_devices->fsid);
2719	memcpy(fs_devices->metadata_uuid, fs_devices->fsid, BTRFS_FSID_SIZE);
2720	memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2721
2722	super_flags = btrfs_super_flags(disk_super) &
2723		      ~BTRFS_SUPER_FLAG_SEEDING;
2724	btrfs_set_super_flags(disk_super, super_flags);
2725}
2726
2727/*
2728 * Store the expected generation for seed devices in device items.
2729 */
2730static int btrfs_finish_sprout(struct btrfs_trans_handle *trans)
2731{
2732	BTRFS_DEV_LOOKUP_ARGS(args);
2733	struct btrfs_fs_info *fs_info = trans->fs_info;
2734	struct btrfs_root *root = fs_info->chunk_root;
2735	BTRFS_PATH_AUTO_FREE(path);
2736	struct extent_buffer *leaf;
2737	struct btrfs_dev_item *dev_item;
2738	struct btrfs_device *device;
2739	struct btrfs_key key;
2740	u8 fs_uuid[BTRFS_FSID_SIZE];
2741	u8 dev_uuid[BTRFS_UUID_SIZE];
2742	int ret;
2743
2744	path = btrfs_alloc_path();
2745	if (!path)
2746		return -ENOMEM;
2747
2748	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2749	key.type = BTRFS_DEV_ITEM_KEY;
2750	key.offset = 0;
2751
2752	while (1) {
2753		btrfs_reserve_chunk_metadata(trans, false);
2754		ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2755		btrfs_trans_release_chunk_metadata(trans);
2756		if (ret < 0)
2757			return ret;
2758
2759		leaf = path->nodes[0];
2760next_slot:
2761		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2762			ret = btrfs_next_leaf(root, path);
2763			if (ret > 0)
2764				break;
2765			if (ret < 0)
2766				return ret;
2767			leaf = path->nodes[0];
2768			btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2769			btrfs_release_path(path);
2770			continue;
2771		}
2772
2773		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2774		if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2775		    key.type != BTRFS_DEV_ITEM_KEY)
2776			break;
2777
2778		dev_item = btrfs_item_ptr(leaf, path->slots[0],
2779					  struct btrfs_dev_item);
2780		args.devid = btrfs_device_id(leaf, dev_item);
2781		read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2782				   BTRFS_UUID_SIZE);
2783		read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2784				   BTRFS_FSID_SIZE);
2785		args.uuid = dev_uuid;
2786		args.fsid = fs_uuid;
2787		device = btrfs_find_device(fs_info->fs_devices, &args);
2788		BUG_ON(!device); /* Logic error */
2789
2790		if (device->fs_devices->seeding)
2791			btrfs_set_device_generation(leaf, dev_item,
2792						    device->generation);
2793
2794		path->slots[0]++;
2795		goto next_slot;
2796	}
2797	return 0;
2798}
2799
2800int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2801{
2802	struct btrfs_root *root = fs_info->dev_root;
2803	struct btrfs_trans_handle *trans;
2804	struct btrfs_device *device;
2805	struct file *bdev_file;
2806	struct super_block *sb = fs_info->sb;
2807	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2808	struct btrfs_fs_devices *seed_devices = NULL;
2809	u64 orig_super_total_bytes;
2810	u64 orig_super_num_devices;
2811	int ret = 0;
2812	bool seeding_dev = false;
2813	bool locked = false;
2814
2815	if (sb_rdonly(sb) && !fs_devices->seeding)
2816		return -EROFS;
2817
2818	bdev_file = bdev_file_open_by_path(device_path, BLK_OPEN_WRITE,
2819					   fs_info->sb, &fs_holder_ops);
2820	if (IS_ERR(bdev_file))
2821		return PTR_ERR(bdev_file);
2822
2823	if (!btrfs_check_device_zone_type(fs_info, file_bdev(bdev_file))) {
2824		ret = -EINVAL;
2825		goto error;
2826	}
2827
2828	if (bdev_nr_bytes(file_bdev(bdev_file)) <= BTRFS_DEVICE_RANGE_RESERVED) {
2829		ret = -EINVAL;
2830		goto error;
2831	}
2832
2833	if (fs_devices->seeding) {
2834		seeding_dev = true;
2835		down_write(&sb->s_umount);
2836		mutex_lock(&uuid_mutex);
2837		locked = true;
2838	}
2839
2840	sync_blockdev(file_bdev(bdev_file));
2841
2842	rcu_read_lock();
2843	list_for_each_entry_rcu(device, &fs_devices->devices, dev_list) {
2844		if (device->bdev == file_bdev(bdev_file)) {
2845			ret = -EEXIST;
2846			rcu_read_unlock();
2847			goto error;
2848		}
2849	}
2850	rcu_read_unlock();
2851
2852	device = btrfs_alloc_device(fs_info, NULL, NULL, device_path);
2853	if (IS_ERR(device)) {
2854		/* we can safely leave the fs_devices entry around */
2855		ret = PTR_ERR(device);
2856		goto error;
2857	}
2858
2859	device->fs_info = fs_info;
2860	device->bdev_file = bdev_file;
2861	device->bdev = file_bdev(bdev_file);
2862	ret = lookup_bdev(device_path, &device->devt);
2863	if (ret)
2864		goto error_free_device;
2865
2866	ret = btrfs_get_dev_zone_info(device, false);
2867	if (ret)
2868		goto error_free_device;
2869
2870	trans = btrfs_start_transaction(root, 0);
2871	if (IS_ERR(trans)) {
2872		ret = PTR_ERR(trans);
2873		goto error_free_zone;
2874	}
2875
2876	set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2877	device->generation = trans->transid;
2878	device->io_width = fs_info->sectorsize;
2879	device->io_align = fs_info->sectorsize;
2880	device->sector_size = fs_info->sectorsize;
2881	device->total_bytes =
2882		round_down(bdev_nr_bytes(device->bdev), fs_info->sectorsize);
2883	device->disk_total_bytes = device->total_bytes;
2884	device->commit_total_bytes = device->total_bytes;
2885	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2886	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2887	device->dev_stats_valid = 1;
2888	set_blocksize(device->bdev_file, BTRFS_BDEV_BLOCKSIZE);
2889
2890	if (seeding_dev) {
2891		/* GFP_KERNEL allocation must not be under device_list_mutex */
2892		seed_devices = btrfs_init_sprout(fs_info);
2893		if (IS_ERR(seed_devices)) {
2894			ret = PTR_ERR(seed_devices);
2895			btrfs_abort_transaction(trans, ret);
2896			goto error_trans;
2897		}
2898	}
2899
2900	mutex_lock(&fs_devices->device_list_mutex);
2901	if (seeding_dev) {
2902		btrfs_setup_sprout(fs_info, seed_devices);
2903		btrfs_assign_next_active_device(fs_info->fs_devices->latest_dev,
2904						device);
2905	}
2906
2907	device->fs_devices = fs_devices;
2908
2909	mutex_lock(&fs_info->chunk_mutex);
2910	list_add_rcu(&device->dev_list, &fs_devices->devices);
2911	list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2912	fs_devices->num_devices++;
2913	fs_devices->open_devices++;
2914	fs_devices->rw_devices++;
2915	fs_devices->total_devices++;
2916	fs_devices->total_rw_bytes += device->total_bytes;
2917
2918	atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2919
2920	if (!bdev_nonrot(device->bdev))
2921		fs_devices->rotating = true;
2922
2923	orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2924	btrfs_set_super_total_bytes(fs_info->super_copy,
2925		round_down(orig_super_total_bytes + device->total_bytes,
2926			   fs_info->sectorsize));
2927
2928	orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2929	btrfs_set_super_num_devices(fs_info->super_copy,
2930				    orig_super_num_devices + 1);
2931
2932	/*
2933	 * we've got more storage, clear any full flags on the space
2934	 * infos
2935	 */
2936	btrfs_clear_space_info_full(fs_info);
2937
2938	mutex_unlock(&fs_info->chunk_mutex);
2939
2940	/* Add sysfs device entry */
2941	btrfs_sysfs_add_device(device);
2942
2943	mutex_unlock(&fs_devices->device_list_mutex);
2944
2945	if (seeding_dev) {
2946		mutex_lock(&fs_info->chunk_mutex);
2947		ret = init_first_rw_device(trans);
2948		mutex_unlock(&fs_info->chunk_mutex);
2949		if (unlikely(ret)) {
2950			btrfs_abort_transaction(trans, ret);
2951			goto error_sysfs;
2952		}
2953	}
2954
2955	ret = btrfs_add_dev_item(trans, device);
2956	if (unlikely(ret)) {
2957		btrfs_abort_transaction(trans, ret);
2958		goto error_sysfs;
2959	}
2960
2961	if (seeding_dev) {
2962		ret = btrfs_finish_sprout(trans);
2963		if (unlikely(ret)) {
2964			btrfs_abort_transaction(trans, ret);
2965			goto error_sysfs;
2966		}
2967
2968		/*
2969		 * fs_devices now represents the newly sprouted filesystem and
2970		 * its fsid has been changed by btrfs_sprout_splice().
2971		 */
2972		btrfs_sysfs_update_sprout_fsid(fs_devices);
2973	}
2974
2975	ret = btrfs_commit_transaction(trans);
2976
2977	if (seeding_dev) {
2978		mutex_unlock(&uuid_mutex);
2979		up_write(&sb->s_umount);
2980		locked = false;
2981
2982		if (ret) /* transaction commit */
2983			return ret;
2984
2985		ret = btrfs_relocate_sys_chunks(fs_info);
2986		if (ret < 0)
2987			btrfs_handle_fs_error(fs_info, ret,
2988				    "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2989		trans = btrfs_attach_transaction(root);
2990		if (IS_ERR(trans)) {
2991			if (PTR_ERR(trans) == -ENOENT)
2992				return 0;
2993			ret = PTR_ERR(trans);
2994			trans = NULL;
2995			goto error_sysfs;
2996		}
2997		ret = btrfs_commit_transaction(trans);
2998	}
2999
3000	/*
3001	 * Now that we have written a new super block to this device, check all
3002	 * other fs_devices list if device_path alienates any other scanned
3003	 * device.
3004	 * We can ignore the return value as it typically returns -EINVAL and
3005	 * only succeeds if the device was an alien.
3006	 */
3007	btrfs_forget_devices(device->devt);
3008
3009	/* Update ctime/mtime for blkid or udev */
3010	update_dev_time(device_path);
3011
3012	return ret;
3013
3014error_sysfs:
3015	btrfs_sysfs_remove_device(device);
3016	mutex_lock(&fs_info->fs_devices->device_list_mutex);
3017	mutex_lock(&fs_info->chunk_mutex);
3018	list_del_rcu(&device->dev_list);
3019	list_del(&device->dev_alloc_list);
3020	fs_info->fs_devices->num_devices--;
3021	fs_info->fs_devices->open_devices--;
3022	fs_info->fs_devices->rw_devices--;
3023	fs_info->fs_devices->total_devices--;
3024	fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
3025	atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
3026	btrfs_set_super_total_bytes(fs_info->super_copy,
3027				    orig_super_total_bytes);
3028	btrfs_set_super_num_devices(fs_info->super_copy,
3029				    orig_super_num_devices);
3030	mutex_unlock(&fs_info->chunk_mutex);
3031	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
3032error_trans:
3033	if (trans)
3034		btrfs_end_transaction(trans);
3035error_free_zone:
3036	btrfs_destroy_dev_zone_info(device);
3037error_free_device:
3038	btrfs_free_device(device);
3039error:
3040	bdev_fput(bdev_file);
3041	if (locked) {
3042		mutex_unlock(&uuid_mutex);
3043		up_write(&sb->s_umount);
3044	}
3045	return ret;
3046}
3047
3048static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
3049					struct btrfs_device *device)
3050{
3051	int ret;
3052	BTRFS_PATH_AUTO_FREE(path);
3053	struct btrfs_root *root = device->fs_info->chunk_root;
3054	struct btrfs_dev_item *dev_item;
3055	struct extent_buffer *leaf;
3056	struct btrfs_key key;
3057
3058	path = btrfs_alloc_path();
3059	if (!path)
3060		return -ENOMEM;
3061
3062	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
3063	key.type = BTRFS_DEV_ITEM_KEY;
3064	key.offset = device->devid;
3065
3066	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
3067	if (ret < 0)
3068		return ret;
3069
3070	if (ret > 0)
3071		return -ENOENT;
3072
3073	leaf = path->nodes[0];
3074	dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
3075
3076	btrfs_set_device_id(leaf, dev_item, device->devid);
3077	btrfs_set_device_type(leaf, dev_item, device->type);
3078	btrfs_set_device_io_align(leaf, dev_item, device->io_align);
3079	btrfs_set_device_io_width(leaf, dev_item, device->io_width);
3080	btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
3081	btrfs_set_device_total_bytes(leaf, dev_item,
3082				     btrfs_device_get_disk_total_bytes(device));
3083	btrfs_set_device_bytes_used(leaf, dev_item,
3084				    btrfs_device_get_bytes_used(device));
3085	return ret;
3086}
3087
3088int btrfs_grow_device(struct btrfs_trans_handle *trans,
3089		      struct btrfs_device *device, u64 new_size)
3090{
3091	struct btrfs_fs_info *fs_info = device->fs_info;
3092	struct btrfs_super_block *super_copy = fs_info->super_copy;
3093	u64 old_total;
3094	u64 diff;
3095	int ret;
3096
3097	if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
3098		return -EACCES;
3099
3100	new_size = round_down(new_size, fs_info->sectorsize);
3101
3102	mutex_lock(&fs_info->chunk_mutex);
3103	old_total = btrfs_super_total_bytes(super_copy);
3104	diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
3105
3106	if (new_size <= device->total_bytes ||
3107	    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
3108		mutex_unlock(&fs_info->chunk_mutex);
3109		return -EINVAL;
3110	}
3111
3112	btrfs_set_super_total_bytes(super_copy,
3113			round_down(old_total + diff, fs_info->sectorsize));
3114	device->fs_devices->total_rw_bytes += diff;
3115	atomic64_add(diff, &fs_info->free_chunk_space);
3116
3117	btrfs_device_set_total_bytes(device, new_size);
3118	btrfs_device_set_disk_total_bytes(device, new_size);
3119	btrfs_clear_space_info_full(device->fs_info);
3120	if (list_empty(&device->post_commit_list))
3121		list_add_tail(&device->post_commit_list,
3122			      &trans->transaction->dev_update_list);
3123	mutex_unlock(&fs_info->chunk_mutex);
3124
3125	btrfs_reserve_chunk_metadata(trans, false);
3126	ret = btrfs_update_device(trans, device);
3127	btrfs_trans_release_chunk_metadata(trans);
3128
3129	return ret;
3130}
3131
3132static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3133{
3134	struct btrfs_fs_info *fs_info = trans->fs_info;
3135	struct btrfs_root *root = fs_info->chunk_root;
3136	int ret;
3137	BTRFS_PATH_AUTO_FREE(path);
3138	struct btrfs_key key;
3139
3140	path = btrfs_alloc_path();
3141	if (!path)
3142		return -ENOMEM;
3143
3144	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3145	key.type = BTRFS_CHUNK_ITEM_KEY;
3146	key.offset = chunk_offset;
3147
3148	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3149	if (ret < 0)
3150		return ret;
3151	if (unlikely(ret > 0)) {
3152		/* Logic error or corruption */
3153		btrfs_err(fs_info, "failed to lookup chunk %llu when freeing",
3154			  chunk_offset);
3155		btrfs_abort_transaction(trans, -ENOENT);
3156		return -EUCLEAN;
3157	}
3158
3159	ret = btrfs_del_item(trans, root, path);
3160	if (unlikely(ret < 0)) {
3161		btrfs_err(fs_info, "failed to delete chunk %llu item", chunk_offset);
3162		btrfs_abort_transaction(trans, ret);
3163		return ret;
3164	}
3165	return ret;
3166}
3167
3168static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
3169{
3170	struct btrfs_super_block *super_copy = fs_info->super_copy;
3171	struct btrfs_disk_key *disk_key;
3172	struct btrfs_chunk *chunk;
3173	u8 *ptr;
3174	int ret = 0;
3175	u32 num_stripes;
3176	u32 array_size;
3177	u32 len = 0;
3178	u32 cur;
3179	struct btrfs_key key;
3180
3181	lockdep_assert_held(&fs_info->chunk_mutex);
3182	array_size = btrfs_super_sys_array_size(super_copy);
3183
3184	ptr = super_copy->sys_chunk_array;
3185	cur = 0;
3186
3187	while (cur < array_size) {
3188		disk_key = (struct btrfs_disk_key *)ptr;
3189		btrfs_disk_key_to_cpu(&key, disk_key);
3190
3191		len = sizeof(*disk_key);
3192
3193		if (key.type == BTRFS_CHUNK_ITEM_KEY) {
3194			chunk = (struct btrfs_chunk *)(ptr + len);
3195			num_stripes = btrfs_stack_chunk_num_stripes(chunk);
3196			len += btrfs_chunk_item_size(num_stripes);
3197		} else {
3198			ret = -EIO;
3199			break;
3200		}
3201		if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
3202		    key.offset == chunk_offset) {
3203			memmove(ptr, ptr + len, array_size - (cur + len));
3204			array_size -= len;
3205			btrfs_set_super_sys_array_size(super_copy, array_size);
3206		} else {
3207			ptr += len;
3208			cur += len;
3209		}
3210	}
3211	return ret;
3212}
3213
3214struct btrfs_chunk_map *btrfs_find_chunk_map_nolock(struct btrfs_fs_info *fs_info,
3215						    u64 logical, u64 length)
3216{
3217	struct rb_node *node = fs_info->mapping_tree.rb_root.rb_node;
3218	struct rb_node *prev = NULL;
3219	struct rb_node *orig_prev;
3220	struct btrfs_chunk_map *map;
3221	struct btrfs_chunk_map *prev_map = NULL;
3222
3223	while (node) {
3224		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
3225		prev = node;
3226		prev_map = map;
3227
3228		if (logical < map->start) {
3229			node = node->rb_left;
3230		} else if (logical >= map->start + map->chunk_len) {
3231			node = node->rb_right;
3232		} else {
3233			refcount_inc(&map->refs);
3234			return map;
3235		}
3236	}
3237
3238	if (!prev)
3239		return NULL;
3240
3241	orig_prev = prev;
3242	while (prev && logical >= prev_map->start + prev_map->chunk_len) {
3243		prev = rb_next(prev);
3244		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3245	}
3246
3247	if (!prev) {
3248		prev = orig_prev;
3249		prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3250		while (prev && logical < prev_map->start) {
3251			prev = rb_prev(prev);
3252			prev_map = rb_entry(prev, struct btrfs_chunk_map, rb_node);
3253		}
3254	}
3255
3256	if (prev) {
3257		u64 end = logical + length;
3258
3259		/*
3260		 * Caller can pass a U64_MAX length when it wants to get any
3261		 * chunk starting at an offset of 'logical' or higher, so deal
3262		 * with underflow by resetting the end offset to U64_MAX.
3263		 */
3264		if (end < logical)
3265			end = U64_MAX;
3266
3267		if (end > prev_map->start &&
3268		    logical < prev_map->start + prev_map->chunk_len) {
3269			refcount_inc(&prev_map->refs);
3270			return prev_map;
3271		}
3272	}
3273
3274	return NULL;
3275}
3276
3277struct btrfs_chunk_map *btrfs_find_chunk_map(struct btrfs_fs_info *fs_info,
3278					     u64 logical, u64 length)
3279{
3280	struct btrfs_chunk_map *map;
3281
3282	read_lock(&fs_info->mapping_tree_lock);
3283	map = btrfs_find_chunk_map_nolock(fs_info, logical, length);
3284	read_unlock(&fs_info->mapping_tree_lock);
3285
3286	return map;
3287}
3288
3289/*
3290 * Find the mapping containing the given logical extent.
3291 *
3292 * @logical: Logical block offset in bytes.
3293 * @length: Length of extent in bytes.
3294 *
3295 * Return: Chunk mapping or ERR_PTR.
3296 */
3297struct btrfs_chunk_map *btrfs_get_chunk_map(struct btrfs_fs_info *fs_info,
3298					    u64 logical, u64 length)
3299{
3300	struct btrfs_chunk_map *map;
3301
3302	map = btrfs_find_chunk_map(fs_info, logical, length);
3303
3304	if (unlikely(!map)) {
3305		btrfs_crit(fs_info,
3306			   "unable to find chunk map for logical %llu length %llu",
3307			   logical, length);
3308		return ERR_PTR(-EINVAL);
3309	}
3310
3311	if (unlikely(map->start > logical || map->start + map->chunk_len <= logical)) {
3312		btrfs_crit(fs_info,
3313			   "found a bad chunk map, wanted %llu-%llu, found %llu-%llu",
3314			   logical, logical + length, map->start,
3315			   map->start + map->chunk_len);
3316		btrfs_free_chunk_map(map);
3317		return ERR_PTR(-EINVAL);
3318	}
3319
3320	/* Callers are responsible for dropping the reference. */
3321	return map;
3322}
3323
3324static int remove_chunk_item(struct btrfs_trans_handle *trans,
3325			     struct btrfs_chunk_map *map, u64 chunk_offset)
3326{
3327	int i;
3328
3329	/*
3330	 * Removing chunk items and updating the device items in the chunks btree
3331	 * requires holding the chunk_mutex.
3332	 * See the comment at btrfs_chunk_alloc() for the details.
3333	 */
3334	lockdep_assert_held(&trans->fs_info->chunk_mutex);
3335
3336	for (i = 0; i < map->num_stripes; i++) {
3337		int ret;
3338
3339		ret = btrfs_update_device(trans, map->stripes[i].dev);
3340		if (ret)
3341			return ret;
3342	}
3343
3344	return btrfs_free_chunk(trans, chunk_offset);
3345}
3346
3347int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
3348{
3349	struct btrfs_fs_info *fs_info = trans->fs_info;
3350	struct btrfs_chunk_map *map;
3351	u64 dev_extent_len = 0;
3352	int i, ret = 0;
3353	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3354
3355	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
3356	if (IS_ERR(map)) {
3357		/*
3358		 * This is a logic error, but we don't want to just rely on the
3359		 * user having built with ASSERT enabled, so if ASSERT doesn't
3360		 * do anything we still error out.
3361		 */
3362		DEBUG_WARN("errr %ld reading chunk map at offset %llu",
3363			   PTR_ERR(map), chunk_offset);
3364		return PTR_ERR(map);
3365	}
3366
3367	/*
3368	 * First delete the device extent items from the devices btree.
3369	 * We take the device_list_mutex to avoid racing with the finishing phase
3370	 * of a device replace operation. See the comment below before acquiring
3371	 * fs_info->chunk_mutex. Note that here we do not acquire the chunk_mutex
3372	 * because that can result in a deadlock when deleting the device extent
3373	 * items from the devices btree - COWing an extent buffer from the btree
3374	 * may result in allocating a new metadata chunk, which would attempt to
3375	 * lock again fs_info->chunk_mutex.
3376	 */
3377	mutex_lock(&fs_devices->device_list_mutex);
3378	for (i = 0; i < map->num_stripes; i++) {
3379		struct btrfs_device *device = map->stripes[i].dev;
3380		ret = btrfs_free_dev_extent(trans, device,
3381					    map->stripes[i].physical,
3382					    &dev_extent_len);
3383		if (unlikely(ret)) {
3384			mutex_unlock(&fs_devices->device_list_mutex);
3385			btrfs_abort_transaction(trans, ret);
3386			goto out;
3387		}
3388
3389		if (device->bytes_used > 0) {
3390			mutex_lock(&fs_info->chunk_mutex);
3391			btrfs_device_set_bytes_used(device,
3392					device->bytes_used - dev_extent_len);
3393			atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
3394			btrfs_clear_space_info_full(fs_info);
3395
3396			if (list_empty(&device->post_commit_list)) {
3397				list_add_tail(&device->post_commit_list,
3398					      &trans->transaction->dev_update_list);
3399			}
3400
3401			mutex_unlock(&fs_info->chunk_mutex);
3402		}
3403	}
3404	mutex_unlock(&fs_devices->device_list_mutex);
3405
3406	/*
3407	 * We acquire fs_info->chunk_mutex for 2 reasons:
3408	 *
3409	 * 1) Just like with the first phase of the chunk allocation, we must
3410	 *    reserve system space, do all chunk btree updates and deletions, and
3411	 *    update the system chunk array in the superblock while holding this
3412	 *    mutex. This is for similar reasons as explained on the comment at
3413	 *    the top of btrfs_chunk_alloc();
3414	 *
3415	 * 2) Prevent races with the final phase of a device replace operation
3416	 *    that replaces the device object associated with the map's stripes,
3417	 *    because the device object's id can change at any time during that
3418	 *    final phase of the device replace operation
3419	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
3420	 *    replaced device and then see it with an ID of
3421	 *    BTRFS_DEV_REPLACE_DEVID, which would cause a failure when updating
3422	 *    the device item, which does not exists on the chunk btree.
3423	 *    The finishing phase of device replace acquires both the
3424	 *    device_list_mutex and the chunk_mutex, in that order, so we are
3425	 *    safe by just acquiring the chunk_mutex.
3426	 */
3427	trans->removing_chunk = true;
3428	mutex_lock(&fs_info->chunk_mutex);
3429
3430	check_system_chunk(trans, map->type);
3431
3432	ret = remove_chunk_item(trans, map, chunk_offset);
3433	/*
3434	 * Normally we should not get -ENOSPC since we reserved space before
3435	 * through the call to check_system_chunk().
3436	 *
3437	 * Despite our system space_info having enough free space, we may not
3438	 * be able to allocate extents from its block groups, because all have
3439	 * an incompatible profile, which will force us to allocate a new system
3440	 * block group with the right profile, or right after we called
3441	 * check_system_space() above, a scrub turned the only system block group
3442	 * with enough free space into RO mode.
3443	 * This is explained with more detail at do_chunk_alloc().
3444	 *
3445	 * So if we get -ENOSPC, allocate a new system chunk and retry once.
3446	 */
3447	if (ret == -ENOSPC) {
3448		const u64 sys_flags = btrfs_system_alloc_profile(fs_info);
3449		struct btrfs_block_group *sys_bg;
3450		struct btrfs_space_info *space_info;
3451
3452		space_info = btrfs_find_space_info(fs_info, sys_flags);
3453		if (unlikely(!space_info)) {
3454			ret = -EINVAL;
3455			btrfs_abort_transaction(trans, ret);
3456			goto out;
3457		}
3458
3459		sys_bg = btrfs_create_chunk(trans, space_info, sys_flags);
3460		if (IS_ERR(sys_bg)) {
3461			ret = PTR_ERR(sys_bg);
3462			btrfs_abort_transaction(trans, ret);
3463			goto out;
3464		}
3465
3466		ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3467		if (unlikely(ret)) {
3468			btrfs_abort_transaction(trans, ret);
3469			goto out;
3470		}
3471
3472		ret = remove_chunk_item(trans, map, chunk_offset);
3473		if (unlikely(ret)) {
3474			btrfs_abort_transaction(trans, ret);
3475			goto out;
3476		}
3477	} else if (unlikely(ret)) {
3478		btrfs_abort_transaction(trans, ret);
3479		goto out;
3480	}
3481
3482	trace_btrfs_chunk_free(fs_info, map, chunk_offset, map->chunk_len);
3483
3484	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
3485		ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
3486		if (unlikely(ret)) {
3487			btrfs_abort_transaction(trans, ret);
3488			goto out;
3489		}
3490	}
3491
3492	mutex_unlock(&fs_info->chunk_mutex);
3493	trans->removing_chunk = false;
3494
3495	/*
3496	 * We are done with chunk btree updates and deletions, so release the
3497	 * system space we previously reserved (with check_system_chunk()).
3498	 */
3499	btrfs_trans_release_chunk_metadata(trans);
3500
3501	ret = btrfs_remove_block_group(trans, map);
3502	if (unlikely(ret)) {
3503		btrfs_abort_transaction(trans, ret);
3504		goto out;
3505	}
3506
3507out:
3508	if (trans->removing_chunk) {
3509		mutex_unlock(&fs_info->chunk_mutex);
3510		trans->removing_chunk = false;
3511	}
3512	/* once for us */
3513	btrfs_free_chunk_map(map);
3514	return ret;
3515}
3516
3517int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3518			 bool verbose)
3519{
3520	struct btrfs_root *root = fs_info->chunk_root;
3521	struct btrfs_trans_handle *trans;
3522	struct btrfs_block_group *block_group;
3523	u64 length;
3524	int ret;
3525
3526	if (btrfs_fs_incompat(fs_info, EXTENT_TREE_V2)) {
3527		btrfs_err(fs_info,
3528			  "relocate: not supported on extent tree v2 yet");
3529		return -EINVAL;
3530	}
3531
3532	/*
3533	 * Prevent races with automatic removal of unused block groups.
3534	 * After we relocate and before we remove the chunk with offset
3535	 * chunk_offset, automatic removal of the block group can kick in,
3536	 * resulting in a failure when calling btrfs_remove_chunk() below.
3537	 *
3538	 * Make sure to acquire this mutex before doing a tree search (dev
3539	 * or chunk trees) to find chunks. Otherwise the cleaner kthread might
3540	 * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
3541	 * we release the path used to search the chunk/dev tree and before
3542	 * the current task acquires this mutex and calls us.
3543	 */
3544	lockdep_assert_held(&fs_info->reclaim_bgs_lock);
3545
3546	/* step one, relocate all the extents inside this chunk */
3547	btrfs_scrub_pause(fs_info);
3548	ret = btrfs_relocate_block_group(fs_info, chunk_offset, true);
3549	btrfs_scrub_continue(fs_info);
3550	if (ret) {
3551		/*
3552		 * If we had a transaction abort, stop all running scrubs.
3553		 * See transaction.c:cleanup_transaction() why we do it here.
3554		 */
3555		if (BTRFS_FS_ERROR(fs_info))
3556			btrfs_scrub_cancel(fs_info);
3557		return ret;
3558	}
3559
3560	block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
3561	if (!block_group)
3562		return -ENOENT;
3563	btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
3564	length = block_group->length;
3565	btrfs_put_block_group(block_group);
3566
3567	/*
3568	 * On a zoned file system, discard the whole block group, this will
3569	 * trigger a REQ_OP_ZONE_RESET operation on the device zone. If
3570	 * resetting the zone fails, don't treat it as a fatal problem from the
3571	 * filesystem's point of view.
3572	 */
3573	if (btrfs_is_zoned(fs_info)) {
3574		ret = btrfs_discard_extent(fs_info, chunk_offset, length, NULL);
3575		if (ret)
3576			btrfs_info(fs_info,
3577				"failed to reset zone %llu after relocation",
3578				chunk_offset);
3579	}
3580
3581	trans = btrfs_start_trans_remove_block_group(root->fs_info,
3582						     chunk_offset);
3583	if (IS_ERR(trans)) {
3584		ret = PTR_ERR(trans);
3585		btrfs_handle_fs_error(root->fs_info, ret, NULL);
3586		return ret;
3587	}
3588
3589	/*
3590	 * step two, delete the device extents and the
3591	 * chunk tree entries
3592	 */
3593	ret = btrfs_remove_chunk(trans, chunk_offset);
3594	btrfs_end_transaction(trans);
3595	return ret;
3596}
3597
3598static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
3599{
3600	struct btrfs_root *chunk_root = fs_info->chunk_root;
3601	BTRFS_PATH_AUTO_FREE(path);
3602	struct extent_buffer *leaf;
3603	struct btrfs_chunk *chunk;
3604	struct btrfs_key key;
3605	struct btrfs_key found_key;
3606	u64 chunk_type;
3607	bool retried = false;
3608	int failed = 0;
3609	int ret;
3610
3611	path = btrfs_alloc_path();
3612	if (!path)
3613		return -ENOMEM;
3614
3615again:
3616	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3617	key.type = BTRFS_CHUNK_ITEM_KEY;
3618	key.offset = (u64)-1;
3619
3620	while (1) {
3621		mutex_lock(&fs_info->reclaim_bgs_lock);
3622		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3623		if (ret < 0) {
3624			mutex_unlock(&fs_info->reclaim_bgs_lock);
3625			return ret;
3626		}
3627		if (unlikely(ret == 0)) {
3628			/*
3629			 * On the first search we would find chunk tree with
3630			 * offset -1, which is not possible. On subsequent
3631			 * loops this would find an existing item on an invalid
3632			 * offset (one less than the previous one, wrong
3633			 * alignment and size).
3634			 */
3635			mutex_unlock(&fs_info->reclaim_bgs_lock);
3636			return -EUCLEAN;
3637		}
3638
3639		ret = btrfs_previous_item(chunk_root, path, key.objectid,
3640					  key.type);
3641		if (ret)
3642			mutex_unlock(&fs_info->reclaim_bgs_lock);
3643		if (ret < 0)
3644			return ret;
3645		if (ret > 0)
3646			break;
3647
3648		leaf = path->nodes[0];
3649		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3650
3651		chunk = btrfs_item_ptr(leaf, path->slots[0],
3652				       struct btrfs_chunk);
3653		chunk_type = btrfs_chunk_type(leaf, chunk);
3654		btrfs_release_path(path);
3655
3656		if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3657			ret = btrfs_relocate_chunk(fs_info, found_key.offset,
3658						   true);
3659			if (ret == -ENOSPC)
3660				failed++;
3661			else
3662				BUG_ON(ret);
3663		}
3664		mutex_unlock(&fs_info->reclaim_bgs_lock);
3665
3666		if (found_key.offset == 0)
3667			break;
3668		key.offset = found_key.offset - 1;
3669	}
3670	ret = 0;
3671	if (failed && !retried) {
3672		failed = 0;
3673		retried = true;
3674		goto again;
3675	} else if (WARN_ON(failed && retried)) {
3676		ret = -ENOSPC;
3677	}
3678	return ret;
3679}
3680
3681/*
3682 * return 1 : allocate a data chunk successfully,
3683 * return <0: errors during allocating a data chunk,
3684 * return 0 : no need to allocate a data chunk.
3685 */
3686static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3687				      u64 chunk_offset)
3688{
3689	struct btrfs_block_group *cache;
3690	u64 bytes_used;
3691	u64 chunk_type;
3692
3693	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3694	ASSERT(cache);
3695	chunk_type = cache->flags;
3696	btrfs_put_block_group(cache);
3697
3698	if (!(chunk_type & BTRFS_BLOCK_GROUP_DATA))
3699		return 0;
3700
3701	spin_lock(&fs_info->data_sinfo->lock);
3702	bytes_used = fs_info->data_sinfo->bytes_used;
3703	spin_unlock(&fs_info->data_sinfo->lock);
3704
3705	if (!bytes_used) {
3706		struct btrfs_trans_handle *trans;
3707		int ret;
3708
3709		trans =	btrfs_join_transaction(fs_info->tree_root);
3710		if (IS_ERR(trans))
3711			return PTR_ERR(trans);
3712
3713		ret = btrfs_force_chunk_alloc(trans, BTRFS_BLOCK_GROUP_DATA);
3714		btrfs_end_transaction(trans);
3715		if (ret < 0)
3716			return ret;
3717		return 1;
3718	}
3719
3720	return 0;
3721}
3722
3723static void btrfs_disk_balance_args_to_cpu(struct btrfs_balance_args *cpu,
3724					   const struct btrfs_disk_balance_args *disk)
3725{
3726	memset(cpu, 0, sizeof(*cpu));
3727
3728	cpu->profiles = le64_to_cpu(disk->profiles);
3729	cpu->usage = le64_to_cpu(disk->usage);
3730	cpu->devid = le64_to_cpu(disk->devid);
3731	cpu->pstart = le64_to_cpu(disk->pstart);
3732	cpu->pend = le64_to_cpu(disk->pend);
3733	cpu->vstart = le64_to_cpu(disk->vstart);
3734	cpu->vend = le64_to_cpu(disk->vend);
3735	cpu->target = le64_to_cpu(disk->target);
3736	cpu->flags = le64_to_cpu(disk->flags);
3737	cpu->limit = le64_to_cpu(disk->limit);
3738	cpu->stripes_min = le32_to_cpu(disk->stripes_min);
3739	cpu->stripes_max = le32_to_cpu(disk->stripes_max);
3740}
3741
3742static void btrfs_cpu_balance_args_to_disk(struct btrfs_disk_balance_args *disk,
3743					   const struct btrfs_balance_args *cpu)
3744{
3745	memset(disk, 0, sizeof(*disk));
3746
3747	disk->profiles = cpu_to_le64(cpu->profiles);
3748	disk->usage = cpu_to_le64(cpu->usage);
3749	disk->devid = cpu_to_le64(cpu->devid);
3750	disk->pstart = cpu_to_le64(cpu->pstart);
3751	disk->pend = cpu_to_le64(cpu->pend);
3752	disk->vstart = cpu_to_le64(cpu->vstart);
3753	disk->vend = cpu_to_le64(cpu->vend);
3754	disk->target = cpu_to_le64(cpu->target);
3755	disk->flags = cpu_to_le64(cpu->flags);
3756	disk->limit = cpu_to_le64(cpu->limit);
3757	disk->stripes_min = cpu_to_le32(cpu->stripes_min);
3758	disk->stripes_max = cpu_to_le32(cpu->stripes_max);
3759}
3760
3761static int insert_balance_item(struct btrfs_fs_info *fs_info,
3762			       struct btrfs_balance_control *bctl)
3763{
3764	struct btrfs_root *root = fs_info->tree_root;
3765	struct btrfs_trans_handle *trans;
3766	struct btrfs_balance_item *item;
3767	struct btrfs_disk_balance_args disk_bargs;
3768	struct btrfs_path *path;
3769	struct extent_buffer *leaf;
3770	struct btrfs_key key;
3771	int ret, err;
3772
3773	path = btrfs_alloc_path();
3774	if (!path)
3775		return -ENOMEM;
3776
3777	trans = btrfs_start_transaction(root, 0);
3778	if (IS_ERR(trans)) {
3779		btrfs_free_path(path);
3780		return PTR_ERR(trans);
3781	}
3782
3783	key.objectid = BTRFS_BALANCE_OBJECTID;
3784	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3785	key.offset = 0;
3786
3787	ret = btrfs_insert_empty_item(trans, root, path, &key,
3788				      sizeof(*item));
3789	if (ret)
3790		goto out;
3791
3792	leaf = path->nodes[0];
3793	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3794
3795	memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3796
3797	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3798	btrfs_set_balance_data(leaf, item, &disk_bargs);
3799	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3800	btrfs_set_balance_meta(leaf, item, &disk_bargs);
3801	btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3802	btrfs_set_balance_sys(leaf, item, &disk_bargs);
3803	btrfs_set_balance_flags(leaf, item, bctl->flags);
3804out:
3805	btrfs_free_path(path);
3806	err = btrfs_commit_transaction(trans);
3807	if (err && !ret)
3808		ret = err;
3809	return ret;
3810}
3811
3812static int del_balance_item(struct btrfs_fs_info *fs_info)
3813{
3814	struct btrfs_root *root = fs_info->tree_root;
3815	struct btrfs_trans_handle *trans;
3816	struct btrfs_path *path;
3817	struct btrfs_key key;
3818	int ret, err;
3819
3820	path = btrfs_alloc_path();
3821	if (!path)
3822		return -ENOMEM;
3823
3824	trans = btrfs_start_transaction_fallback_global_rsv(root, 0);
3825	if (IS_ERR(trans)) {
3826		btrfs_free_path(path);
3827		return PTR_ERR(trans);
3828	}
3829
3830	key.objectid = BTRFS_BALANCE_OBJECTID;
3831	key.type = BTRFS_TEMPORARY_ITEM_KEY;
3832	key.offset = 0;
3833
3834	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3835	if (ret < 0)
3836		goto out;
3837	if (ret > 0) {
3838		ret = -ENOENT;
3839		goto out;
3840	}
3841
3842	ret = btrfs_del_item(trans, root, path);
3843out:
3844	btrfs_free_path(path);
3845	err = btrfs_commit_transaction(trans);
3846	if (err && !ret)
3847		ret = err;
3848	return ret;
3849}
3850
3851/*
3852 * This is a heuristic used to reduce the number of chunks balanced on
3853 * resume after balance was interrupted.
3854 */
3855static void update_balance_args(struct btrfs_balance_control *bctl)
3856{
3857	/*
3858	 * Turn on soft mode for chunk types that were being converted.
3859	 */
3860	if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3861		bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3862	if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3863		bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3864	if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3865		bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3866
3867	/*
3868	 * Turn on usage filter if is not already used.  The idea is
3869	 * that chunks that we have already balanced should be
3870	 * reasonably full.  Don't do it for chunks that are being
3871	 * converted - that will keep us from relocating unconverted
3872	 * (albeit full) chunks.
3873	 */
3874	if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3875	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3876	    !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3877		bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3878		bctl->data.usage = 90;
3879	}
3880	if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3881	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3882	    !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3883		bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3884		bctl->sys.usage = 90;
3885	}
3886	if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3887	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3888	    !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3889		bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3890		bctl->meta.usage = 90;
3891	}
3892}
3893
3894/*
3895 * Clear the balance status in fs_info and delete the balance item from disk.
3896 */
3897static void reset_balance_state(struct btrfs_fs_info *fs_info)
3898{
3899	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3900	int ret;
3901
3902	ASSERT(fs_info->balance_ctl);
3903
3904	spin_lock(&fs_info->balance_lock);
3905	fs_info->balance_ctl = NULL;
3906	spin_unlock(&fs_info->balance_lock);
3907
3908	kfree(bctl);
3909	ret = del_balance_item(fs_info);
3910	if (ret)
3911		btrfs_handle_fs_error(fs_info, ret, NULL);
3912}
3913
3914/*
3915 * Balance filters.  Return 1 if chunk should be filtered out
3916 * (should not be balanced).
3917 */
3918static bool chunk_profiles_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
3919{
3920	chunk_type = chunk_to_extended(chunk_type) &
3921				BTRFS_EXTENDED_PROFILE_MASK;
3922
3923	if (bargs->profiles & chunk_type)
3924		return false;
3925
3926	return true;
3927}
3928
3929static bool chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3930				     struct btrfs_balance_args *bargs)
3931{
3932	struct btrfs_block_group *cache;
3933	u64 chunk_used;
3934	u64 user_thresh_min;
3935	u64 user_thresh_max;
3936	bool ret = true;
3937
3938	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3939	chunk_used = cache->used;
3940
3941	if (bargs->usage_min == 0)
3942		user_thresh_min = 0;
3943	else
3944		user_thresh_min = mult_perc(cache->length, bargs->usage_min);
3945
3946	if (bargs->usage_max == 0)
3947		user_thresh_max = 1;
3948	else if (bargs->usage_max > 100)
3949		user_thresh_max = cache->length;
3950	else
3951		user_thresh_max = mult_perc(cache->length, bargs->usage_max);
3952
3953	if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3954		ret = false;
3955
3956	btrfs_put_block_group(cache);
3957	return ret;
3958}
3959
3960static bool chunk_usage_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3961			       struct btrfs_balance_args *bargs)
3962{
3963	struct btrfs_block_group *cache;
3964	u64 chunk_used, user_thresh;
3965	bool ret = true;
3966
3967	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3968	chunk_used = cache->used;
3969
3970	if (bargs->usage_min == 0)
3971		user_thresh = 1;
3972	else if (bargs->usage > 100)
3973		user_thresh = cache->length;
3974	else
3975		user_thresh = mult_perc(cache->length, bargs->usage);
3976
3977	if (chunk_used < user_thresh)
3978		ret = false;
3979
3980	btrfs_put_block_group(cache);
3981	return ret;
3982}
3983
3984static bool chunk_devid_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
3985			       struct btrfs_balance_args *bargs)
3986{
3987	struct btrfs_stripe *stripe;
3988	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3989	int i;
3990
3991	for (i = 0; i < num_stripes; i++) {
3992		stripe = btrfs_stripe_nr(chunk, i);
3993		if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3994			return false;
3995	}
3996
3997	return true;
3998}
3999
4000static u64 calc_data_stripes(u64 type, int num_stripes)
4001{
4002	const int index = btrfs_bg_flags_to_raid_index(type);
4003	const int ncopies = btrfs_raid_array[index].ncopies;
4004	const int nparity = btrfs_raid_array[index].nparity;
4005
4006	return (num_stripes - nparity) / ncopies;
4007}
4008
4009/* [pstart, pend) */
4010static bool chunk_drange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4011				struct btrfs_balance_args *bargs)
4012{
4013	struct btrfs_stripe *stripe;
4014	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4015	u64 stripe_offset;
4016	u64 stripe_length;
4017	u64 type;
4018	int factor;
4019	int i;
4020
4021	if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
4022		return false;
4023
4024	type = btrfs_chunk_type(leaf, chunk);
4025	factor = calc_data_stripes(type, num_stripes);
4026
4027	for (i = 0; i < num_stripes; i++) {
4028		stripe = btrfs_stripe_nr(chunk, i);
4029		if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
4030			continue;
4031
4032		stripe_offset = btrfs_stripe_offset(leaf, stripe);
4033		stripe_length = btrfs_chunk_length(leaf, chunk);
4034		stripe_length = div_u64(stripe_length, factor);
4035
4036		if (stripe_offset < bargs->pend &&
4037		    stripe_offset + stripe_length > bargs->pstart)
4038			return false;
4039	}
4040
4041	return true;
4042}
4043
4044/* [vstart, vend) */
4045static bool chunk_vrange_filter(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4046				u64 chunk_offset, struct btrfs_balance_args *bargs)
4047{
4048	if (chunk_offset < bargs->vend &&
4049	    chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
4050		/* at least part of the chunk is inside this vrange */
4051		return false;
4052
4053	return true;
4054}
4055
4056static bool chunk_stripes_range_filter(struct extent_buffer *leaf,
4057				       struct btrfs_chunk *chunk,
4058				       struct btrfs_balance_args *bargs)
4059{
4060	int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
4061
4062	if (bargs->stripes_min <= num_stripes
4063			&& num_stripes <= bargs->stripes_max)
4064		return false;
4065
4066	return true;
4067}
4068
4069static bool chunk_soft_convert_filter(u64 chunk_type, struct btrfs_balance_args *bargs)
4070{
4071	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4072		return false;
4073
4074	chunk_type = chunk_to_extended(chunk_type) &
4075				BTRFS_EXTENDED_PROFILE_MASK;
4076
4077	if (bargs->target == chunk_type)
4078		return true;
4079
4080	return false;
4081}
4082
4083static bool should_balance_chunk(struct extent_buffer *leaf, struct btrfs_chunk *chunk,
4084				 u64 chunk_offset)
4085{
4086	struct btrfs_fs_info *fs_info = leaf->fs_info;
4087	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4088	struct btrfs_balance_args *bargs = NULL;
4089	u64 chunk_type = btrfs_chunk_type(leaf, chunk);
4090
4091	/* type filter */
4092	if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
4093	      (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
4094		return false;
4095	}
4096
4097	if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4098		bargs = &bctl->data;
4099	else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4100		bargs = &bctl->sys;
4101	else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4102		bargs = &bctl->meta;
4103
4104	/* profiles filter */
4105	if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
4106	    chunk_profiles_filter(chunk_type, bargs)) {
4107		return false;
4108	}
4109
4110	/* usage filter */
4111	if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
4112	    chunk_usage_filter(fs_info, chunk_offset, bargs)) {
4113		return false;
4114	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
4115	    chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
4116		return false;
4117	}
4118
4119	/* devid filter */
4120	if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
4121	    chunk_devid_filter(leaf, chunk, bargs)) {
4122		return false;
4123	}
4124
4125	/* drange filter, makes sense only with devid filter */
4126	if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
4127	    chunk_drange_filter(leaf, chunk, bargs)) {
4128		return false;
4129	}
4130
4131	/* vrange filter */
4132	if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
4133	    chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
4134		return false;
4135	}
4136
4137	/* stripes filter */
4138	if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
4139	    chunk_stripes_range_filter(leaf, chunk, bargs)) {
4140		return false;
4141	}
4142
4143	/* soft profile changing mode */
4144	if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
4145	    chunk_soft_convert_filter(chunk_type, bargs)) {
4146		return false;
4147	}
4148
4149	/*
4150	 * limited by count, must be the last filter
4151	 */
4152	if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
4153		if (bargs->limit == 0)
4154			return false;
4155		else
4156			bargs->limit--;
4157	} else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
4158		/*
4159		 * Same logic as the 'limit' filter; the minimum cannot be
4160		 * determined here because we do not have the global information
4161		 * about the count of all chunks that satisfy the filters.
4162		 */
4163		if (bargs->limit_max == 0)
4164			return false;
4165		else
4166			bargs->limit_max--;
4167	}
4168
4169	return true;
4170}
4171
4172static int __btrfs_balance(struct btrfs_fs_info *fs_info)
4173{
4174	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4175	struct btrfs_root *chunk_root = fs_info->chunk_root;
4176	u64 chunk_type;
4177	struct btrfs_chunk *chunk;
4178	BTRFS_PATH_AUTO_FREE(path);
4179	struct btrfs_key key;
4180	struct btrfs_key found_key;
4181	struct extent_buffer *leaf;
4182	int slot;
4183	int ret;
4184	int enospc_errors = 0;
4185	bool counting = true;
4186	/* The single value limit and min/max limits use the same bytes in the */
4187	u64 limit_data = bctl->data.limit;
4188	u64 limit_meta = bctl->meta.limit;
4189	u64 limit_sys = bctl->sys.limit;
4190	u32 count_data = 0;
4191	u32 count_meta = 0;
4192	u32 count_sys = 0;
4193	int chunk_reserved = 0;
4194
4195	path = btrfs_alloc_path();
4196	if (!path) {
4197		ret = -ENOMEM;
4198		goto error;
4199	}
4200
4201	/* zero out stat counters */
4202	spin_lock(&fs_info->balance_lock);
4203	memset(&bctl->stat, 0, sizeof(bctl->stat));
4204	spin_unlock(&fs_info->balance_lock);
4205again:
4206	if (!counting) {
4207		/*
4208		 * The single value limit and min/max limits use the same bytes
4209		 * in the
4210		 */
4211		bctl->data.limit = limit_data;
4212		bctl->meta.limit = limit_meta;
4213		bctl->sys.limit = limit_sys;
4214	}
4215	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4216	key.type = BTRFS_CHUNK_ITEM_KEY;
4217	key.offset = (u64)-1;
4218
4219	while (1) {
4220		if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
4221		    atomic_read(&fs_info->balance_cancel_req)) {
4222			ret = -ECANCELED;
4223			goto error;
4224		}
4225
4226		mutex_lock(&fs_info->reclaim_bgs_lock);
4227		ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
4228		if (ret < 0) {
4229			mutex_unlock(&fs_info->reclaim_bgs_lock);
4230			goto error;
4231		}
4232
4233		/*
4234		 * this shouldn't happen, it means the last relocate
4235		 * failed
4236		 */
4237		if (unlikely(ret == 0)) {
4238			btrfs_err(fs_info,
4239				  "unexpected exact match of CHUNK_ITEM in chunk tree, offset 0x%llx",
4240				  key.offset);
4241			mutex_unlock(&fs_info->reclaim_bgs_lock);
4242			ret = -EUCLEAN;
4243			goto error;
4244		}
4245
4246		ret = btrfs_previous_item(chunk_root, path, 0,
4247					  BTRFS_CHUNK_ITEM_KEY);
4248		if (ret) {
4249			mutex_unlock(&fs_info->reclaim_bgs_lock);
4250			ret = 0;
4251			break;
4252		}
4253
4254		leaf = path->nodes[0];
4255		slot = path->slots[0];
4256		btrfs_item_key_to_cpu(leaf, &found_key, slot);
4257
4258		if (found_key.objectid != key.objectid) {
4259			mutex_unlock(&fs_info->reclaim_bgs_lock);
4260			break;
4261		}
4262
4263		chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
4264		chunk_type = btrfs_chunk_type(leaf, chunk);
4265
4266		if (!counting) {
4267			spin_lock(&fs_info->balance_lock);
4268			bctl->stat.considered++;
4269			spin_unlock(&fs_info->balance_lock);
4270		}
4271
4272		ret = should_balance_chunk(leaf, chunk, found_key.offset);
4273
4274		btrfs_release_path(path);
4275		if (!ret) {
4276			mutex_unlock(&fs_info->reclaim_bgs_lock);
4277			goto loop;
4278		}
4279
4280		if (counting) {
4281			mutex_unlock(&fs_info->reclaim_bgs_lock);
4282			spin_lock(&fs_info->balance_lock);
4283			bctl->stat.expected++;
4284			spin_unlock(&fs_info->balance_lock);
4285
4286			if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
4287				count_data++;
4288			else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
4289				count_sys++;
4290			else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
4291				count_meta++;
4292
4293			goto loop;
4294		}
4295
4296		/*
4297		 * Apply limit_min filter, no need to check if the LIMITS
4298		 * filter is used, limit_min is 0 by default
4299		 */
4300		if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
4301					count_data < bctl->data.limit_min)
4302				|| ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
4303					count_meta < bctl->meta.limit_min)
4304				|| ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
4305					count_sys < bctl->sys.limit_min)) {
4306			mutex_unlock(&fs_info->reclaim_bgs_lock);
4307			goto loop;
4308		}
4309
4310		if (!chunk_reserved) {
4311			/*
4312			 * We may be relocating the only data chunk we have,
4313			 * which could potentially end up with losing data's
4314			 * raid profile, so lets allocate an empty one in
4315			 * advance.
4316			 */
4317			ret = btrfs_may_alloc_data_chunk(fs_info,
4318							 found_key.offset);
4319			if (ret < 0) {
4320				mutex_unlock(&fs_info->reclaim_bgs_lock);
4321				goto error;
4322			} else if (ret == 1) {
4323				chunk_reserved = 1;
4324			}
4325		}
4326
4327		ret = btrfs_relocate_chunk(fs_info, found_key.offset, true);
4328		mutex_unlock(&fs_info->reclaim_bgs_lock);
4329		if (ret == -ENOSPC) {
4330			enospc_errors++;
4331		} else if (ret == -ETXTBSY) {
4332			btrfs_info(fs_info,
4333	   "skipping relocation of block group %llu due to active swapfile",
4334				   found_key.offset);
4335			ret = 0;
4336		} else if (ret) {
4337			goto error;
4338		} else {
4339			spin_lock(&fs_info->balance_lock);
4340			bctl->stat.completed++;
4341			spin_unlock(&fs_info->balance_lock);
4342		}
4343loop:
4344		if (found_key.offset == 0)
4345			break;
4346		key.offset = found_key.offset - 1;
4347	}
4348
4349	if (counting) {
4350		btrfs_release_path(path);
4351		counting = false;
4352		goto again;
4353	}
4354error:
4355	if (enospc_errors) {
4356		btrfs_info(fs_info, "%d enospc errors during balance",
4357			   enospc_errors);
4358		if (!ret)
4359			ret = -ENOSPC;
4360	}
4361
4362	return ret;
4363}
4364
4365/*
4366 * See if a given profile is valid and reduced.
4367 *
4368 * @flags:     profile to validate
4369 * @extended:  if true @flags is treated as an extended profile
4370 */
4371static int alloc_profile_is_valid(u64 flags, bool extended)
4372{
4373	u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
4374			       BTRFS_BLOCK_GROUP_PROFILE_MASK);
4375
4376	flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
4377
4378	/* 1) check that all other bits are zeroed */
4379	if (flags & ~mask)
4380		return 0;
4381
4382	/* 2) see if profile is reduced */
4383	if (flags == 0)
4384		return !extended; /* "0" is valid for usual profiles */
4385
4386	return has_single_bit_set(flags);
4387}
4388
4389/*
4390 * Validate target profile against allowed profiles and return true if it's OK.
4391 * Otherwise print the error message and return false.
4392 */
4393static inline int validate_convert_profile(struct btrfs_fs_info *fs_info,
4394		const struct btrfs_balance_args *bargs,
4395		u64 allowed, const char *type)
4396{
4397	if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
4398		return true;
4399
4400	/* Profile is valid and does not have bits outside of the allowed set */
4401	if (alloc_profile_is_valid(bargs->target, 1) &&
4402	    (bargs->target & ~allowed) == 0)
4403		return true;
4404
4405	btrfs_err(fs_info, "balance: invalid convert %s profile %s",
4406			type, btrfs_bg_type_to_raid_name(bargs->target));
4407	return false;
4408}
4409
4410/*
4411 * Fill @buf with textual description of balance filter flags @bargs, up to
4412 * @size_buf including the terminating null. The output may be trimmed if it
4413 * does not fit into the provided buffer.
4414 */
4415static void describe_balance_args(struct btrfs_balance_args *bargs, char *buf,
4416				 u32 size_buf)
4417{
4418	int ret;
4419	u32 size_bp = size_buf;
4420	char *bp = buf;
4421	u64 flags = bargs->flags;
4422	char tmp_buf[128] = {'\0'};
4423
4424	if (!flags)
4425		return;
4426
4427#define CHECK_APPEND_NOARG(a)						\
4428	do {								\
4429		ret = snprintf(bp, size_bp, (a));			\
4430		if (ret < 0 || ret >= size_bp)				\
4431			goto out_overflow;				\
4432		size_bp -= ret;						\
4433		bp += ret;						\
4434	} while (0)
4435
4436#define CHECK_APPEND_1ARG(a, v1)					\
4437	do {								\
4438		ret = snprintf(bp, size_bp, (a), (v1));			\
4439		if (ret < 0 || ret >= size_bp)				\
4440			goto out_overflow;				\
4441		size_bp -= ret;						\
4442		bp += ret;						\
4443	} while (0)
4444
4445#define CHECK_APPEND_2ARG(a, v1, v2)					\
4446	do {								\
4447		ret = snprintf(bp, size_bp, (a), (v1), (v2));		\
4448		if (ret < 0 || ret >= size_bp)				\
4449			goto out_overflow;				\
4450		size_bp -= ret;						\
4451		bp += ret;						\
4452	} while (0)
4453
4454	if (flags & BTRFS_BALANCE_ARGS_CONVERT)
4455		CHECK_APPEND_1ARG("convert=%s,",
4456				  btrfs_bg_type_to_raid_name(bargs->target));
4457
4458	if (flags & BTRFS_BALANCE_ARGS_SOFT)
4459		CHECK_APPEND_NOARG("soft,");
4460
4461	if (flags & BTRFS_BALANCE_ARGS_PROFILES) {
4462		btrfs_describe_block_groups(bargs->profiles, tmp_buf,
4463					    sizeof(tmp_buf));
4464		CHECK_APPEND_1ARG("profiles=%s,", tmp_buf);
4465	}
4466
4467	if (flags & BTRFS_BALANCE_ARGS_USAGE)
4468		CHECK_APPEND_1ARG("usage=%llu,", bargs->usage);
4469
4470	if (flags & BTRFS_BALANCE_ARGS_USAGE_RANGE)
4471		CHECK_APPEND_2ARG("usage=%u..%u,",
4472				  bargs->usage_min, bargs->usage_max);
4473
4474	if (flags & BTRFS_BALANCE_ARGS_DEVID)
4475		CHECK_APPEND_1ARG("devid=%llu,", bargs->devid);
4476
4477	if (flags & BTRFS_BALANCE_ARGS_DRANGE)
4478		CHECK_APPEND_2ARG("drange=%llu..%llu,",
4479				  bargs->pstart, bargs->pend);
4480
4481	if (flags & BTRFS_BALANCE_ARGS_VRANGE)
4482		CHECK_APPEND_2ARG("vrange=%llu..%llu,",
4483				  bargs->vstart, bargs->vend);
4484
4485	if (flags & BTRFS_BALANCE_ARGS_LIMIT)
4486		CHECK_APPEND_1ARG("limit=%llu,", bargs->limit);
4487
4488	if (flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)
4489		CHECK_APPEND_2ARG("limit=%u..%u,",
4490				bargs->limit_min, bargs->limit_max);
4491
4492	if (flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE)
4493		CHECK_APPEND_2ARG("stripes=%u..%u,",
4494				  bargs->stripes_min, bargs->stripes_max);
4495
4496#undef CHECK_APPEND_2ARG
4497#undef CHECK_APPEND_1ARG
4498#undef CHECK_APPEND_NOARG
4499
4500out_overflow:
4501
4502	if (size_bp < size_buf)
4503		buf[size_buf - size_bp - 1] = '\0'; /* remove last , */
4504	else
4505		buf[0] = '\0';
4506}
4507
4508static void describe_balance_start_or_resume(struct btrfs_fs_info *fs_info)
4509{
4510	u32 size_buf = 1024;
4511	char tmp_buf[192] = {'\0'};
4512	char AUTO_KFREE(buf);
4513	char *bp;
4514	u32 size_bp = size_buf;
4515	int ret;
4516	struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4517
4518	buf = kzalloc(size_buf, GFP_KERNEL);
4519	if (!buf)
4520		return;
4521
4522	bp = buf;
4523
4524#define CHECK_APPEND_1ARG(a, v1)					\
4525	do {								\
4526		ret = snprintf(bp, size_bp, (a), (v1));			\
4527		if (ret < 0 || ret >= size_bp)				\
4528			goto out_overflow;				\
4529		size_bp -= ret;						\
4530		bp += ret;						\
4531	} while (0)
4532
4533	if (bctl->flags & BTRFS_BALANCE_FORCE)
4534		CHECK_APPEND_1ARG("%s", "-f ");
4535
4536	if (bctl->flags & BTRFS_BALANCE_DATA) {
4537		describe_balance_args(&bctl->data, tmp_buf, sizeof(tmp_buf));
4538		CHECK_APPEND_1ARG("-d%s ", tmp_buf);
4539	}
4540
4541	if (bctl->flags & BTRFS_BALANCE_METADATA) {
4542		describe_balance_args(&bctl->meta, tmp_buf, sizeof(tmp_buf));
4543		CHECK_APPEND_1ARG("-m%s ", tmp_buf);
4544	}
4545
4546	if (bctl->flags & BTRFS_BALANCE_SYSTEM) {
4547		describe_balance_args(&bctl->sys, tmp_buf, sizeof(tmp_buf));
4548		CHECK_APPEND_1ARG("-s%s ", tmp_buf);
4549	}
4550
4551#undef CHECK_APPEND_1ARG
4552
4553out_overflow:
4554
4555	if (size_bp < size_buf)
4556		buf[size_buf - size_bp - 1] = '\0'; /* remove last " " */
4557	btrfs_info(fs_info, "balance: %s %s",
4558		   (bctl->flags & BTRFS_BALANCE_RESUME) ?
4559		   "resume" : "start", buf);
4560}
4561
4562/*
4563 * Should be called with balance mutex held
4564 */
4565int btrfs_balance(struct btrfs_fs_info *fs_info,
4566		  struct btrfs_balance_control *bctl,
4567		  struct btrfs_ioctl_balance_args *bargs)
4568{
4569	u64 meta_target, data_target;
4570	u64 allowed;
4571	int mixed = 0;
4572	int ret;
4573	u64 num_devices;
4574	unsigned seq;
4575	bool reducing_redundancy;
4576	bool paused = false;
4577	int i;
4578
4579	if (btrfs_fs_closing(fs_info) ||
4580	    atomic_read(&fs_info->balance_pause_req) ||
4581	    btrfs_should_cancel_balance(fs_info)) {
4582		ret = -EINVAL;
4583		goto out;
4584	}
4585
4586	allowed = btrfs_super_incompat_flags(fs_info->super_copy);
4587	if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
4588		mixed = 1;
4589
4590	/*
4591	 * In case of mixed groups both data and meta should be picked,
4592	 * and identical options should be given for both of them.
4593	 */
4594	allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
4595	if (mixed && (bctl->flags & allowed)) {
4596		if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
4597		    !(bctl->flags & BTRFS_BALANCE_METADATA) ||
4598		    memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
4599			btrfs_err(fs_info,
4600	  "balance: mixed groups data and metadata options must be the same");
4601			ret = -EINVAL;
4602			goto out;
4603		}
4604	}
4605
4606	/*
4607	 * rw_devices will not change at the moment, device add/delete/replace
4608	 * are exclusive
4609	 */
4610	num_devices = fs_info->fs_devices->rw_devices;
4611
4612	/*
4613	 * SINGLE profile on-disk has no profile bit, but in-memory we have a
4614	 * special bit for it, to make it easier to distinguish.  Thus we need
4615	 * to set it manually, or balance would refuse the profile.
4616	 */
4617	allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE;
4618	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++)
4619		if (num_devices >= btrfs_raid_array[i].devs_min)
4620			allowed |= btrfs_raid_array[i].bg_flag;
4621
4622	if (!validate_convert_profile(fs_info, &bctl->data, allowed, "data") ||
4623	    !validate_convert_profile(fs_info, &bctl->meta, allowed, "metadata") ||
4624	    !validate_convert_profile(fs_info, &bctl->sys,  allowed, "system")) {
4625		ret = -EINVAL;
4626		goto out;
4627	}
4628
4629	/*
4630	 * Allow to reduce metadata or system integrity only if force set for
4631	 * profiles with redundancy (copies, parity)
4632	 */
4633	allowed = 0;
4634	for (i = 0; i < ARRAY_SIZE(btrfs_raid_array); i++) {
4635		if (btrfs_raid_array[i].ncopies >= 2 ||
4636		    btrfs_raid_array[i].tolerated_failures >= 1)
4637			allowed |= btrfs_raid_array[i].bg_flag;
4638	}
4639	do {
4640		seq = read_seqbegin(&fs_info->profiles_lock);
4641
4642		if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4643		     (fs_info->avail_system_alloc_bits & allowed) &&
4644		     !(bctl->sys.target & allowed)) ||
4645		    ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
4646		     (fs_info->avail_metadata_alloc_bits & allowed) &&
4647		     !(bctl->meta.target & allowed)))
4648			reducing_redundancy = true;
4649		else
4650			reducing_redundancy = false;
4651
4652		/* if we're not converting, the target field is uninitialized */
4653		meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4654			bctl->meta.target : fs_info->avail_metadata_alloc_bits;
4655		data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
4656			bctl->data.target : fs_info->avail_data_alloc_bits;
4657	} while (read_seqretry(&fs_info->profiles_lock, seq));
4658
4659	if (reducing_redundancy) {
4660		if (bctl->flags & BTRFS_BALANCE_FORCE) {
4661			btrfs_info(fs_info,
4662			   "balance: force reducing metadata redundancy");
4663		} else {
4664			btrfs_err(fs_info,
4665	"balance: reduces metadata redundancy, use --force if you want this");
4666			ret = -EINVAL;
4667			goto out;
4668		}
4669	}
4670
4671	if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
4672		btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
4673		btrfs_warn(fs_info,
4674	"balance: metadata profile %s has lower redundancy than data profile %s",
4675				btrfs_bg_type_to_raid_name(meta_target),
4676				btrfs_bg_type_to_raid_name(data_target));
4677	}
4678
4679	ret = insert_balance_item(fs_info, bctl);
4680	if (ret && ret != -EEXIST)
4681		goto out;
4682
4683	if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
4684		BUG_ON(ret == -EEXIST);
4685		BUG_ON(fs_info->balance_ctl);
4686		spin_lock(&fs_info->balance_lock);
4687		fs_info->balance_ctl = bctl;
4688		spin_unlock(&fs_info->balance_lock);
4689	} else {
4690		BUG_ON(ret != -EEXIST);
4691		spin_lock(&fs_info->balance_lock);
4692		update_balance_args(bctl);
4693		spin_unlock(&fs_info->balance_lock);
4694	}
4695
4696	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4697	set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4698	describe_balance_start_or_resume(fs_info);
4699	mutex_unlock(&fs_info->balance_mutex);
4700
4701	ret = __btrfs_balance(fs_info);
4702
4703	mutex_lock(&fs_info->balance_mutex);
4704	if (ret == -ECANCELED && atomic_read(&fs_info->balance_pause_req)) {
4705		btrfs_info(fs_info, "balance: paused");
4706		btrfs_exclop_balance(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED);
4707		paused = true;
4708	}
4709	/*
4710	 * Balance can be canceled by:
4711	 *
4712	 * - Regular cancel request
4713	 *   Then ret == -ECANCELED and balance_cancel_req > 0
4714	 *
4715	 * - Fatal signal to "btrfs" process
4716	 *   Either the signal caught by wait_reserve_ticket() and callers
4717	 *   got -EINTR, or caught by btrfs_should_cancel_balance() and
4718	 *   got -ECANCELED.
4719	 *   Either way, in this case balance_cancel_req = 0, and
4720	 *   ret == -EINTR or ret == -ECANCELED.
4721	 *
4722	 * So here we only check the return value to catch canceled balance.
4723	 */
4724	else if (ret == -ECANCELED || ret == -EINTR)
4725		btrfs_info(fs_info, "balance: canceled");
4726	else
4727		btrfs_info(fs_info, "balance: ended with status: %d", ret);
4728
4729	clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
4730
4731	if (bargs) {
4732		memset(bargs, 0, sizeof(*bargs));
4733		btrfs_update_ioctl_balance_args(fs_info, bargs);
4734	}
4735
4736	/* We didn't pause, we can clean everything up. */
4737	if (!paused) {
4738		reset_balance_state(fs_info);
4739		btrfs_exclop_finish(fs_info);
4740	}
4741
4742	wake_up(&fs_info->balance_wait_q);
4743
4744	return ret;
4745out:
4746	if (bctl->flags & BTRFS_BALANCE_RESUME)
4747		reset_balance_state(fs_info);
4748	else
4749		kfree(bctl);
4750	btrfs_exclop_finish(fs_info);
4751
4752	return ret;
4753}
4754
4755static int balance_kthread(void *data)
4756{
4757	struct btrfs_fs_info *fs_info = data;
4758	int ret = 0;
4759
4760	guard(super_write)(fs_info->sb);
4761
4762	mutex_lock(&fs_info->balance_mutex);
4763	if (fs_info->balance_ctl)
4764		ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
4765	mutex_unlock(&fs_info->balance_mutex);
4766
4767	return ret;
4768}
4769
4770int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
4771{
4772	struct task_struct *tsk;
4773
4774	mutex_lock(&fs_info->balance_mutex);
4775	if (!fs_info->balance_ctl) {
4776		mutex_unlock(&fs_info->balance_mutex);
4777		return 0;
4778	}
4779	mutex_unlock(&fs_info->balance_mutex);
4780
4781	if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
4782		btrfs_info(fs_info, "balance: resume skipped");
4783		return 0;
4784	}
4785
4786	spin_lock(&fs_info->super_lock);
4787	ASSERT(fs_info->exclusive_operation == BTRFS_EXCLOP_BALANCE_PAUSED,
4788	       "exclusive_operation=%d", fs_info->exclusive_operation);
4789	fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
4790	spin_unlock(&fs_info->super_lock);
4791	/*
4792	 * A ro->rw remount sequence should continue with the paused balance
4793	 * regardless of who pauses it, system or the user as of now, so set
4794	 * the resume flag.
4795	 */
4796	spin_lock(&fs_info->balance_lock);
4797	fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4798	spin_unlock(&fs_info->balance_lock);
4799
4800	tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4801	return PTR_ERR_OR_ZERO(tsk);
4802}
4803
4804int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4805{
4806	struct btrfs_balance_control *bctl;
4807	struct btrfs_balance_item *item;
4808	struct btrfs_disk_balance_args disk_bargs;
4809	BTRFS_PATH_AUTO_FREE(path);
4810	struct extent_buffer *leaf;
4811	struct btrfs_key key;
4812	int ret;
4813
4814	path = btrfs_alloc_path();
4815	if (!path)
4816		return -ENOMEM;
4817
4818	key.objectid = BTRFS_BALANCE_OBJECTID;
4819	key.type = BTRFS_TEMPORARY_ITEM_KEY;
4820	key.offset = 0;
4821
4822	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4823	if (ret < 0)
4824		return ret;
4825	if (ret > 0) { /* ret = -ENOENT; */
4826		return 0;
4827	}
4828
4829	bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4830	if (!bctl)
4831		return -ENOMEM;
4832
4833	leaf = path->nodes[0];
4834	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4835
4836	bctl->flags = btrfs_balance_flags(leaf, item);
4837	bctl->flags |= BTRFS_BALANCE_RESUME;
4838
4839	btrfs_balance_data(leaf, item, &disk_bargs);
4840	btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4841	btrfs_balance_meta(leaf, item, &disk_bargs);
4842	btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4843	btrfs_balance_sys(leaf, item, &disk_bargs);
4844	btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4845
4846	/*
4847	 * This should never happen, as the paused balance state is recovered
4848	 * during mount without any chance of other exclusive ops to collide.
4849	 *
4850	 * This gives the exclusive op status to balance and keeps in paused
4851	 * state until user intervention (cancel or umount). If the ownership
4852	 * cannot be assigned, show a message but do not fail. The balance
4853	 * is in a paused state and must have fs_info::balance_ctl properly
4854	 * set up.
4855	 */
4856	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE_PAUSED))
4857		btrfs_warn(fs_info,
4858	"balance: cannot set exclusive op status, resume manually");
4859
4860	btrfs_release_path(path);
4861
4862	mutex_lock(&fs_info->balance_mutex);
4863	BUG_ON(fs_info->balance_ctl);
4864	spin_lock(&fs_info->balance_lock);
4865	fs_info->balance_ctl = bctl;
4866	spin_unlock(&fs_info->balance_lock);
4867	mutex_unlock(&fs_info->balance_mutex);
4868	return ret;
4869}
4870
4871int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4872{
4873	int ret = 0;
4874
4875	mutex_lock(&fs_info->balance_mutex);
4876	if (!fs_info->balance_ctl) {
4877		mutex_unlock(&fs_info->balance_mutex);
4878		return -ENOTCONN;
4879	}
4880
4881	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4882		atomic_inc(&fs_info->balance_pause_req);
4883		mutex_unlock(&fs_info->balance_mutex);
4884
4885		wait_event(fs_info->balance_wait_q,
4886			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4887
4888		mutex_lock(&fs_info->balance_mutex);
4889		/* we are good with balance_ctl ripped off from under us */
4890		BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4891		atomic_dec(&fs_info->balance_pause_req);
4892	} else {
4893		ret = -ENOTCONN;
4894	}
4895
4896	mutex_unlock(&fs_info->balance_mutex);
4897	return ret;
4898}
4899
4900int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4901{
4902	mutex_lock(&fs_info->balance_mutex);
4903	if (!fs_info->balance_ctl) {
4904		mutex_unlock(&fs_info->balance_mutex);
4905		return -ENOTCONN;
4906	}
4907
4908	/*
4909	 * A paused balance with the item stored on disk can be resumed at
4910	 * mount time if the mount is read-write. Otherwise it's still paused
4911	 * and we must not allow cancelling as it deletes the item.
4912	 */
4913	if (sb_rdonly(fs_info->sb)) {
4914		mutex_unlock(&fs_info->balance_mutex);
4915		return -EROFS;
4916	}
4917
4918	atomic_inc(&fs_info->balance_cancel_req);
4919	/*
4920	 * if we are running just wait and return, balance item is
4921	 * deleted in btrfs_balance in this case
4922	 */
4923	if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4924		mutex_unlock(&fs_info->balance_mutex);
4925		wait_event(fs_info->balance_wait_q,
4926			   !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4927		mutex_lock(&fs_info->balance_mutex);
4928	} else {
4929		mutex_unlock(&fs_info->balance_mutex);
4930		/*
4931		 * Lock released to allow other waiters to continue, we'll
4932		 * reexamine the status again.
4933		 */
4934		mutex_lock(&fs_info->balance_mutex);
4935
4936		if (fs_info->balance_ctl) {
4937			reset_balance_state(fs_info);
4938			btrfs_exclop_finish(fs_info);
4939			btrfs_info(fs_info, "balance: canceled");
4940		}
4941	}
4942
4943	ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4944	atomic_dec(&fs_info->balance_cancel_req);
4945	mutex_unlock(&fs_info->balance_mutex);
4946	return 0;
4947}
4948
4949/*
4950 * shrinking a device means finding all of the device extents past
4951 * the new size, and then following the back refs to the chunks.
4952 * The chunk relocation code actually frees the device extent
4953 */
4954int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4955{
4956	struct btrfs_fs_info *fs_info = device->fs_info;
4957	struct btrfs_root *root = fs_info->dev_root;
4958	struct btrfs_trans_handle *trans;
4959	struct btrfs_dev_extent *dev_extent = NULL;
4960	struct btrfs_path *path;
4961	u64 length;
4962	u64 chunk_offset;
4963	int ret;
4964	int slot;
4965	int failed = 0;
4966	bool retried = false;
4967	struct extent_buffer *l;
4968	struct btrfs_key key;
4969	struct btrfs_super_block *super_copy = fs_info->super_copy;
4970	u64 old_total = btrfs_super_total_bytes(super_copy);
4971	u64 old_size = btrfs_device_get_total_bytes(device);
4972	u64 diff;
4973	u64 start;
4974	u64 free_diff = 0;
4975	u64 pending_start, pending_end;
4976
4977	new_size = round_down(new_size, fs_info->sectorsize);
4978	start = new_size;
4979	diff = round_down(old_size - new_size, fs_info->sectorsize);
4980
4981	if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4982		return -EINVAL;
4983
4984	path = btrfs_alloc_path();
4985	if (!path)
4986		return -ENOMEM;
4987
4988	path->reada = READA_BACK;
4989
4990	trans = btrfs_start_transaction(root, 0);
4991	if (IS_ERR(trans)) {
4992		btrfs_free_path(path);
4993		return PTR_ERR(trans);
4994	}
4995
4996	mutex_lock(&fs_info->chunk_mutex);
4997
4998	btrfs_device_set_total_bytes(device, new_size);
4999	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5000		device->fs_devices->total_rw_bytes -= diff;
5001
5002		/*
5003		 * The new free_chunk_space is new_size - used, so we have to
5004		 * subtract the delta of the old free_chunk_space which included
5005		 * old_size - used.  If used > new_size then just subtract this
5006		 * entire device's free space.
5007		 */
5008		if (device->bytes_used < new_size)
5009			free_diff = (old_size - device->bytes_used) -
5010				    (new_size - device->bytes_used);
5011		else
5012			free_diff = old_size - device->bytes_used;
5013		atomic64_sub(free_diff, &fs_info->free_chunk_space);
5014	}
5015
5016	/*
5017	 * Once the device's size has been set to the new size, ensure all
5018	 * in-memory chunks are synced to disk so that the loop below sees them
5019	 * and relocates them accordingly.
5020	 */
5021	if (first_pending_extent(device, start, diff, &pending_start, &pending_end)) {
5022		mutex_unlock(&fs_info->chunk_mutex);
5023		ret = btrfs_commit_transaction(trans);
5024		if (ret)
5025			goto done;
5026	} else {
5027		mutex_unlock(&fs_info->chunk_mutex);
5028		btrfs_end_transaction(trans);
5029	}
5030
5031again:
5032	key.objectid = device->devid;
5033	key.type = BTRFS_DEV_EXTENT_KEY;
5034	key.offset = (u64)-1;
5035
5036	do {
5037		mutex_lock(&fs_info->reclaim_bgs_lock);
5038		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5039		if (ret < 0) {
5040			mutex_unlock(&fs_info->reclaim_bgs_lock);
5041			goto done;
5042		}
5043
5044		ret = btrfs_previous_item(root, path, 0, key.type);
5045		if (ret) {
5046			mutex_unlock(&fs_info->reclaim_bgs_lock);
5047			if (ret < 0)
5048				goto done;
5049			ret = 0;
5050			btrfs_release_path(path);
5051			break;
5052		}
5053
5054		l = path->nodes[0];
5055		slot = path->slots[0];
5056		btrfs_item_key_to_cpu(l, &key, path->slots[0]);
5057
5058		if (key.objectid != device->devid) {
5059			mutex_unlock(&fs_info->reclaim_bgs_lock);
5060			btrfs_release_path(path);
5061			break;
5062		}
5063
5064		dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
5065		length = btrfs_dev_extent_length(l, dev_extent);
5066
5067		if (key.offset + length <= new_size) {
5068			mutex_unlock(&fs_info->reclaim_bgs_lock);
5069			btrfs_release_path(path);
5070			break;
5071		}
5072
5073		chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
5074		btrfs_release_path(path);
5075
5076		/*
5077		 * We may be relocating the only data chunk we have,
5078		 * which could potentially end up with losing data's
5079		 * raid profile, so lets allocate an empty one in
5080		 * advance.
5081		 */
5082		ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
5083		if (ret < 0) {
5084			mutex_unlock(&fs_info->reclaim_bgs_lock);
5085			goto done;
5086		}
5087
5088		ret = btrfs_relocate_chunk(fs_info, chunk_offset, true);
5089		mutex_unlock(&fs_info->reclaim_bgs_lock);
5090		if (ret == -ENOSPC) {
5091			failed++;
5092		} else if (ret) {
5093			if (ret == -ETXTBSY) {
5094				btrfs_warn(fs_info,
5095		   "could not shrink block group %llu due to active swapfile",
5096					   chunk_offset);
5097			}
5098			goto done;
5099		}
5100	} while (key.offset-- > 0);
5101
5102	if (failed && !retried) {
5103		failed = 0;
5104		retried = true;
5105		goto again;
5106	} else if (failed && retried) {
5107		ret = -ENOSPC;
5108		goto done;
5109	}
5110
5111	/* Shrinking succeeded, else we would be at "done". */
5112	trans = btrfs_start_transaction(root, 0);
5113	if (IS_ERR(trans)) {
5114		ret = PTR_ERR(trans);
5115		goto done;
5116	}
5117
5118	mutex_lock(&fs_info->chunk_mutex);
5119	/* Clear all state bits beyond the shrunk device size */
5120	btrfs_clear_extent_bit(&device->alloc_state, new_size, (u64)-1,
5121			       CHUNK_STATE_MASK, NULL);
5122
5123	btrfs_device_set_disk_total_bytes(device, new_size);
5124	if (list_empty(&device->post_commit_list))
5125		list_add_tail(&device->post_commit_list,
5126			      &trans->transaction->dev_update_list);
5127
5128	WARN_ON(diff > old_total);
5129	btrfs_set_super_total_bytes(super_copy,
5130			round_down(old_total - diff, fs_info->sectorsize));
5131	mutex_unlock(&fs_info->chunk_mutex);
5132
5133	btrfs_reserve_chunk_metadata(trans, false);
5134	/* Now btrfs_update_device() will change the on-disk size. */
5135	ret = btrfs_update_device(trans, device);
5136	btrfs_trans_release_chunk_metadata(trans);
5137	if (unlikely(ret < 0)) {
5138		btrfs_abort_transaction(trans, ret);
5139		btrfs_end_transaction(trans);
5140	} else {
5141		ret = btrfs_commit_transaction(trans);
5142	}
5143done:
5144	btrfs_free_path(path);
5145	if (ret) {
5146		mutex_lock(&fs_info->chunk_mutex);
5147		btrfs_device_set_total_bytes(device, old_size);
5148		if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5149			device->fs_devices->total_rw_bytes += diff;
5150			atomic64_add(free_diff, &fs_info->free_chunk_space);
5151		}
5152		mutex_unlock(&fs_info->chunk_mutex);
5153	}
5154	return ret;
5155}
5156
5157static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
5158			   struct btrfs_key *key,
5159			   struct btrfs_chunk *chunk, int item_size)
5160{
5161	struct btrfs_super_block *super_copy = fs_info->super_copy;
5162	struct btrfs_disk_key disk_key;
5163	u32 array_size;
5164	u8 *ptr;
5165
5166	lockdep_assert_held(&fs_info->chunk_mutex);
5167
5168	array_size = btrfs_super_sys_array_size(super_copy);
5169	if (array_size + item_size + sizeof(disk_key)
5170			> BTRFS_SYSTEM_CHUNK_ARRAY_SIZE)
5171		return -EFBIG;
5172
5173	ptr = super_copy->sys_chunk_array + array_size;
5174	btrfs_cpu_key_to_disk(&disk_key, key);
5175	memcpy(ptr, &disk_key, sizeof(disk_key));
5176	ptr += sizeof(disk_key);
5177	memcpy(ptr, chunk, item_size);
5178	item_size += sizeof(disk_key);
5179	btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
5180
5181	return 0;
5182}
5183
5184/*
5185 * sort the devices in descending order by max_avail, total_avail
5186 */
5187static int btrfs_cmp_device_info(const void *a, const void *b)
5188{
5189	const struct btrfs_device_info *di_a = a;
5190	const struct btrfs_device_info *di_b = b;
5191
5192	if (di_a->max_avail > di_b->max_avail)
5193		return -1;
5194	if (di_a->max_avail < di_b->max_avail)
5195		return 1;
5196	if (di_a->total_avail > di_b->total_avail)
5197		return -1;
5198	if (di_a->total_avail < di_b->total_avail)
5199		return 1;
5200	return 0;
5201}
5202
5203static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
5204{
5205	if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
5206		return;
5207
5208	btrfs_set_fs_incompat(info, RAID56);
5209}
5210
5211static void check_raid1c34_incompat_flag(struct btrfs_fs_info *info, u64 type)
5212{
5213	if (!(type & (BTRFS_BLOCK_GROUP_RAID1C3 | BTRFS_BLOCK_GROUP_RAID1C4)))
5214		return;
5215
5216	btrfs_set_fs_incompat(info, RAID1C34);
5217}
5218
5219/*
5220 * Structure used internally for btrfs_create_chunk() function.
5221 * Wraps needed parameters.
5222 */
5223struct alloc_chunk_ctl {
5224	u64 start;
5225	u64 type;
5226	/* Total number of stripes to allocate */
5227	int num_stripes;
5228	/* sub_stripes info for map */
5229	int sub_stripes;
5230	/* Stripes per device */
5231	int dev_stripes;
5232	/* Maximum number of devices to use */
5233	int devs_max;
5234	/* Minimum number of devices to use */
5235	int devs_min;
5236	/* ndevs has to be a multiple of this */
5237	int devs_increment;
5238	/* Number of copies */
5239	int ncopies;
5240	/* Number of stripes worth of bytes to store parity information */
5241	int nparity;
5242	u64 max_stripe_size;
5243	u64 max_chunk_size;
5244	u64 dev_extent_min;
5245	u64 stripe_size;
5246	u64 chunk_size;
5247	int ndevs;
5248	/* Space_info the block group is going to belong. */
5249	struct btrfs_space_info *space_info;
5250};
5251
5252static void init_alloc_chunk_ctl_policy_regular(
5253				struct btrfs_fs_devices *fs_devices,
5254				struct alloc_chunk_ctl *ctl)
5255{
5256	struct btrfs_space_info *space_info;
5257
5258	space_info = btrfs_find_space_info(fs_devices->fs_info, ctl->type);
5259	ASSERT(space_info);
5260
5261	ctl->max_chunk_size = READ_ONCE(space_info->chunk_size);
5262	ctl->max_stripe_size = min_t(u64, ctl->max_chunk_size, SZ_1G);
5263
5264	if (ctl->type & BTRFS_BLOCK_GROUP_SYSTEM)
5265		ctl->devs_max = min_t(int, ctl->devs_max, BTRFS_MAX_DEVS_SYS_CHUNK);
5266
5267	/* We don't want a chunk larger than 10% of writable space */
5268	ctl->max_chunk_size = min(mult_perc(fs_devices->total_rw_bytes, 10),
5269				  ctl->max_chunk_size);
5270	ctl->dev_extent_min = btrfs_stripe_nr_to_offset(ctl->dev_stripes);
5271}
5272
5273static void init_alloc_chunk_ctl_policy_zoned(
5274				      struct btrfs_fs_devices *fs_devices,
5275				      struct alloc_chunk_ctl *ctl)
5276{
5277	u64 zone_size = fs_devices->fs_info->zone_size;
5278	u64 limit;
5279	int min_num_stripes = ctl->devs_min * ctl->dev_stripes;
5280	int min_data_stripes = (min_num_stripes - ctl->nparity) / ctl->ncopies;
5281	u64 min_chunk_size = min_data_stripes * zone_size;
5282	u64 type = ctl->type;
5283
5284	ctl->max_stripe_size = zone_size;
5285	if (type & BTRFS_BLOCK_GROUP_DATA) {
5286		ctl->max_chunk_size = round_down(BTRFS_MAX_DATA_CHUNK_SIZE,
5287						 zone_size);
5288	} else if (type & BTRFS_BLOCK_GROUP_METADATA) {
5289		ctl->max_chunk_size = ctl->max_stripe_size;
5290	} else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
5291		ctl->max_chunk_size = 2 * ctl->max_stripe_size;
5292		ctl->devs_max = min_t(int, ctl->devs_max,
5293				      BTRFS_MAX_DEVS_SYS_CHUNK);
5294	} else {
5295		BUG();
5296	}
5297
5298	/* We don't want a chunk larger than 10% of writable space */
5299	limit = max(round_down(mult_perc(fs_devices->total_rw_bytes, 10),
5300			       zone_size),
5301		    min_chunk_size);
5302	ctl->max_chunk_size = min(limit, ctl->max_chunk_size);
5303	ctl->dev_extent_min = zone_size * ctl->dev_stripes;
5304}
5305
5306static void init_alloc_chunk_ctl(struct btrfs_fs_devices *fs_devices,
5307				 struct alloc_chunk_ctl *ctl)
5308{
5309	int index = btrfs_bg_flags_to_raid_index(ctl->type);
5310
5311	ctl->sub_stripes = btrfs_raid_array[index].sub_stripes;
5312	ctl->dev_stripes = btrfs_raid_array[index].dev_stripes;
5313	ctl->devs_max = btrfs_raid_array[index].devs_max;
5314	if (!ctl->devs_max)
5315		ctl->devs_max = BTRFS_MAX_DEVS(fs_devices->fs_info);
5316	ctl->devs_min = btrfs_raid_array[index].devs_min;
5317	ctl->devs_increment = btrfs_raid_array[index].devs_increment;
5318	ctl->ncopies = btrfs_raid_array[index].ncopies;
5319	ctl->nparity = btrfs_raid_array[index].nparity;
5320	ctl->ndevs = 0;
5321
5322	switch (fs_devices->chunk_alloc_policy) {
5323	default:
5324		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5325		fallthrough;
5326	case BTRFS_CHUNK_ALLOC_REGULAR:
5327		init_alloc_chunk_ctl_policy_regular(fs_devices, ctl);
5328		break;
5329	case BTRFS_CHUNK_ALLOC_ZONED:
5330		init_alloc_chunk_ctl_policy_zoned(fs_devices, ctl);
5331		break;
5332	}
5333}
5334
5335static int gather_device_info(struct btrfs_fs_devices *fs_devices,
5336			      struct alloc_chunk_ctl *ctl,
5337			      struct btrfs_device_info *devices_info)
5338{
5339	struct btrfs_fs_info *info = fs_devices->fs_info;
5340	struct btrfs_device *device;
5341	u64 total_avail;
5342	u64 dev_extent_want = ctl->max_stripe_size * ctl->dev_stripes;
5343	int ret;
5344	int ndevs = 0;
5345	u64 max_avail;
5346	u64 dev_offset;
5347
5348	/*
5349	 * in the first pass through the devices list, we gather information
5350	 * about the available holes on each device.
5351	 */
5352	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
5353		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
5354			WARN(1, KERN_ERR
5355			       "BTRFS: read-only device in alloc_list\n");
5356			continue;
5357		}
5358
5359		if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
5360					&device->dev_state) ||
5361		    test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
5362			continue;
5363
5364		if (device->total_bytes > device->bytes_used)
5365			total_avail = device->total_bytes - device->bytes_used;
5366		else
5367			total_avail = 0;
5368
5369		/* If there is no space on this device, skip it. */
5370		if (total_avail < ctl->dev_extent_min)
5371			continue;
5372
5373		ret = find_free_dev_extent(device, dev_extent_want, &dev_offset,
5374					   &max_avail);
5375		if (ret && ret != -ENOSPC)
5376			return ret;
5377
5378		if (ret == 0)
5379			max_avail = dev_extent_want;
5380
5381		if (max_avail < ctl->dev_extent_min) {
5382			if (btrfs_test_opt(info, ENOSPC_DEBUG))
5383				btrfs_debug(info,
5384			"%s: devid %llu has no free space, have=%llu want=%llu",
5385					    __func__, device->devid, max_avail,
5386					    ctl->dev_extent_min);
5387			continue;
5388		}
5389
5390		if (ndevs == fs_devices->rw_devices) {
5391			WARN(1, "%s: found more than %llu devices\n",
5392			     __func__, fs_devices->rw_devices);
5393			break;
5394		}
5395		devices_info[ndevs].dev_offset = dev_offset;
5396		devices_info[ndevs].max_avail = max_avail;
5397		devices_info[ndevs].total_avail = total_avail;
5398		devices_info[ndevs].dev = device;
5399		++ndevs;
5400	}
5401	ctl->ndevs = ndevs;
5402
5403	/*
5404	 * now sort the devices by hole size / available space
5405	 */
5406	sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
5407	     btrfs_cmp_device_info, NULL);
5408
5409	return 0;
5410}
5411
5412static int decide_stripe_size_regular(struct alloc_chunk_ctl *ctl,
5413				      struct btrfs_device_info *devices_info)
5414{
5415	/* Number of stripes that count for block group size */
5416	int data_stripes;
5417
5418	/*
5419	 * The primary goal is to maximize the number of stripes, so use as
5420	 * many devices as possible, even if the stripes are not maximum sized.
5421	 *
5422	 * The DUP profile stores more than one stripe per device, the
5423	 * max_avail is the total size so we have to adjust.
5424	 */
5425	ctl->stripe_size = div_u64(devices_info[ctl->ndevs - 1].max_avail,
5426				   ctl->dev_stripes);
5427	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5428
5429	/* This will have to be fixed for RAID1 and RAID10 over more drives */
5430	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5431
5432	/*
5433	 * Use the number of data stripes to figure out how big this chunk is
5434	 * really going to be in terms of logical address space, and compare
5435	 * that answer with the max chunk size. If it's higher, we try to
5436	 * reduce stripe_size.
5437	 */
5438	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5439		/*
5440		 * Reduce stripe_size, round it up to a 16MB boundary again and
5441		 * then use it, unless it ends up being even bigger than the
5442		 * previous value we had already.
5443		 */
5444		ctl->stripe_size = min(round_up(div_u64(ctl->max_chunk_size,
5445							data_stripes), SZ_16M),
5446				       ctl->stripe_size);
5447	}
5448
5449	/* Stripe size should not go beyond 1G. */
5450	ctl->stripe_size = min_t(u64, ctl->stripe_size, SZ_1G);
5451
5452	/* Align to BTRFS_STRIPE_LEN */
5453	ctl->stripe_size = round_down(ctl->stripe_size, BTRFS_STRIPE_LEN);
5454	ctl->chunk_size = ctl->stripe_size * data_stripes;
5455
5456	return 0;
5457}
5458
5459static int decide_stripe_size_zoned(struct alloc_chunk_ctl *ctl,
5460				    struct btrfs_device_info *devices_info)
5461{
5462	u64 zone_size = devices_info[0].dev->zone_info->zone_size;
5463	/* Number of stripes that count for block group size */
5464	int data_stripes;
5465
5466	/*
5467	 * It should hold because:
5468	 *    dev_extent_min == dev_extent_want == zone_size * dev_stripes
5469	 */
5470	ASSERT(devices_info[ctl->ndevs - 1].max_avail == ctl->dev_extent_min,
5471	       "ndevs=%d max_avail=%llu dev_extent_min=%llu", ctl->ndevs,
5472	       devices_info[ctl->ndevs - 1].max_avail, ctl->dev_extent_min);
5473
5474	ctl->stripe_size = zone_size;
5475	ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5476	data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5477
5478	/* stripe_size is fixed in zoned filesystem. Reduce ndevs instead. */
5479	if (ctl->stripe_size * data_stripes > ctl->max_chunk_size) {
5480		ctl->ndevs = div_u64(div_u64(ctl->max_chunk_size * ctl->ncopies,
5481					     ctl->stripe_size) + ctl->nparity,
5482				     ctl->dev_stripes);
5483		ctl->num_stripes = ctl->ndevs * ctl->dev_stripes;
5484		data_stripes = (ctl->num_stripes - ctl->nparity) / ctl->ncopies;
5485		ASSERT(ctl->stripe_size * data_stripes <= ctl->max_chunk_size,
5486		       "stripe_size=%llu data_stripes=%d max_chunk_size=%llu",
5487		       ctl->stripe_size, data_stripes, ctl->max_chunk_size);
5488	}
5489
5490	ctl->chunk_size = ctl->stripe_size * data_stripes;
5491
5492	return 0;
5493}
5494
5495static int decide_stripe_size(struct btrfs_fs_devices *fs_devices,
5496			      struct alloc_chunk_ctl *ctl,
5497			      struct btrfs_device_info *devices_info)
5498{
5499	struct btrfs_fs_info *info = fs_devices->fs_info;
5500
5501	/*
5502	 * Round down to number of usable stripes, devs_increment can be any
5503	 * number so we can't use round_down() that requires power of 2, while
5504	 * rounddown is safe.
5505	 */
5506	ctl->ndevs = rounddown(ctl->ndevs, ctl->devs_increment);
5507
5508	if (ctl->ndevs < ctl->devs_min) {
5509		if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
5510			btrfs_debug(info,
5511	"%s: not enough devices with free space: have=%d minimum required=%d",
5512				    __func__, ctl->ndevs, ctl->devs_min);
5513		}
5514		return -ENOSPC;
5515	}
5516
5517	ctl->ndevs = min(ctl->ndevs, ctl->devs_max);
5518
5519	switch (fs_devices->chunk_alloc_policy) {
5520	default:
5521		btrfs_warn_unknown_chunk_allocation(fs_devices->chunk_alloc_policy);
5522		fallthrough;
5523	case BTRFS_CHUNK_ALLOC_REGULAR:
5524		return decide_stripe_size_regular(ctl, devices_info);
5525	case BTRFS_CHUNK_ALLOC_ZONED:
5526		return decide_stripe_size_zoned(ctl, devices_info);
5527	}
5528}
5529
5530static void chunk_map_device_set_bits(struct btrfs_chunk_map *map, unsigned int bits)
5531{
5532	for (int i = 0; i < map->num_stripes; i++) {
5533		struct btrfs_io_stripe *stripe = &map->stripes[i];
5534		struct btrfs_device *device = stripe->dev;
5535
5536		btrfs_set_extent_bit(&device->alloc_state, stripe->physical,
5537				     stripe->physical + map->stripe_size - 1,
5538				     bits | EXTENT_NOWAIT, NULL);
5539	}
5540}
5541
5542static void chunk_map_device_clear_bits(struct btrfs_chunk_map *map, unsigned int bits)
5543{
5544	for (int i = 0; i < map->num_stripes; i++) {
5545		struct btrfs_io_stripe *stripe = &map->stripes[i];
5546		struct btrfs_device *device = stripe->dev;
5547
5548		btrfs_clear_extent_bit(&device->alloc_state, stripe->physical,
5549				       stripe->physical + map->stripe_size - 1,
5550				       bits | EXTENT_NOWAIT, NULL);
5551	}
5552}
5553
5554void btrfs_remove_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5555{
5556	write_lock(&fs_info->mapping_tree_lock);
5557	rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5558	RB_CLEAR_NODE(&map->rb_node);
5559	chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5560	write_unlock(&fs_info->mapping_tree_lock);
5561
5562	/* Once for the tree reference. */
5563	btrfs_free_chunk_map(map);
5564}
5565
5566static int btrfs_chunk_map_cmp(const struct rb_node *new,
5567			       const struct rb_node *exist)
5568{
5569	const struct btrfs_chunk_map *new_map =
5570		rb_entry(new, struct btrfs_chunk_map, rb_node);
5571	const struct btrfs_chunk_map *exist_map =
5572		rb_entry(exist, struct btrfs_chunk_map, rb_node);
5573
5574	if (new_map->start == exist_map->start)
5575		return 0;
5576	if (new_map->start < exist_map->start)
5577		return -1;
5578	return 1;
5579}
5580
5581EXPORT_FOR_TESTS
5582int btrfs_add_chunk_map(struct btrfs_fs_info *fs_info, struct btrfs_chunk_map *map)
5583{
5584	struct rb_node *exist;
5585
5586	write_lock(&fs_info->mapping_tree_lock);
5587	exist = rb_find_add_cached(&map->rb_node, &fs_info->mapping_tree,
5588				   btrfs_chunk_map_cmp);
5589
5590	if (exist) {
5591		write_unlock(&fs_info->mapping_tree_lock);
5592		return -EEXIST;
5593	}
5594	chunk_map_device_set_bits(map, CHUNK_ALLOCATED);
5595	chunk_map_device_clear_bits(map, CHUNK_TRIMMED);
5596	write_unlock(&fs_info->mapping_tree_lock);
5597
5598	return 0;
5599}
5600
5601EXPORT_FOR_TESTS
5602struct btrfs_chunk_map *btrfs_alloc_chunk_map(int num_stripes, gfp_t gfp)
5603{
5604	struct btrfs_chunk_map *map;
5605
5606	map = kmalloc(btrfs_chunk_map_size(num_stripes), gfp);
5607	if (!map)
5608		return NULL;
5609
5610	refcount_set(&map->refs, 1);
5611	RB_CLEAR_NODE(&map->rb_node);
5612
5613	return map;
5614}
5615
5616static struct btrfs_block_group *create_chunk(struct btrfs_trans_handle *trans,
5617			struct alloc_chunk_ctl *ctl,
5618			struct btrfs_device_info *devices_info)
5619{
5620	struct btrfs_fs_info *info = trans->fs_info;
5621	struct btrfs_chunk_map *map;
5622	struct btrfs_block_group *block_group;
5623	u64 start = ctl->start;
5624	u64 type = ctl->type;
5625	int ret;
5626
5627	map = btrfs_alloc_chunk_map(ctl->num_stripes, GFP_NOFS);
5628	if (!map)
5629		return ERR_PTR(-ENOMEM);
5630
5631	map->start = start;
5632	map->chunk_len = ctl->chunk_size;
5633	map->stripe_size = ctl->stripe_size;
5634	map->type = type;
5635	map->io_align = BTRFS_STRIPE_LEN;
5636	map->io_width = BTRFS_STRIPE_LEN;
5637	map->sub_stripes = ctl->sub_stripes;
5638	map->num_stripes = ctl->num_stripes;
5639
5640	for (int i = 0; i < ctl->ndevs; i++) {
5641		for (int j = 0; j < ctl->dev_stripes; j++) {
5642			int s = i * ctl->dev_stripes + j;
5643			map->stripes[s].dev = devices_info[i].dev;
5644			map->stripes[s].physical = devices_info[i].dev_offset +
5645						   j * ctl->stripe_size;
5646		}
5647	}
5648
5649	trace_btrfs_chunk_alloc(info, map, start, ctl->chunk_size);
5650
5651	ret = btrfs_add_chunk_map(info, map);
5652	if (ret) {
5653		btrfs_free_chunk_map(map);
5654		return ERR_PTR(ret);
5655	}
5656
5657	block_group = btrfs_make_block_group(trans, ctl->space_info, type, start,
5658					     ctl->chunk_size);
5659	if (IS_ERR(block_group)) {
5660		btrfs_remove_chunk_map(info, map);
5661		return block_group;
5662	}
5663
5664	for (int i = 0; i < map->num_stripes; i++) {
5665		struct btrfs_device *dev = map->stripes[i].dev;
5666
5667		btrfs_device_set_bytes_used(dev,
5668					    dev->bytes_used + ctl->stripe_size);
5669		if (list_empty(&dev->post_commit_list))
5670			list_add_tail(&dev->post_commit_list,
5671				      &trans->transaction->dev_update_list);
5672	}
5673
5674	atomic64_sub(ctl->stripe_size * map->num_stripes,
5675		     &info->free_chunk_space);
5676
5677	check_raid56_incompat_flag(info, type);
5678	check_raid1c34_incompat_flag(info, type);
5679
5680	return block_group;
5681}
5682
5683struct btrfs_block_group *btrfs_create_chunk(struct btrfs_trans_handle *trans,
5684					     struct btrfs_space_info *space_info,
5685					     u64 type)
5686{
5687	struct btrfs_fs_info *info = trans->fs_info;
5688	struct btrfs_fs_devices *fs_devices = info->fs_devices;
5689	struct btrfs_device_info AUTO_KFREE(devices_info);
5690	struct alloc_chunk_ctl ctl;
5691	int ret;
5692
5693	lockdep_assert_held(&info->chunk_mutex);
5694
5695	if (!alloc_profile_is_valid(type, 0)) {
5696		DEBUG_WARN("invalid alloc profile for type %llu", type);
5697		return ERR_PTR(-EINVAL);
5698	}
5699
5700	if (list_empty(&fs_devices->alloc_list)) {
5701		if (btrfs_test_opt(info, ENOSPC_DEBUG))
5702			btrfs_debug(info, "%s: no writable device", __func__);
5703		return ERR_PTR(-ENOSPC);
5704	}
5705
5706	if (!(type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
5707		btrfs_err(info, "invalid chunk type 0x%llx requested", type);
5708		DEBUG_WARN();
5709		return ERR_PTR(-EINVAL);
5710	}
5711
5712	ctl.start = find_next_chunk(info);
5713	ctl.type = type;
5714	ctl.space_info = space_info;
5715	init_alloc_chunk_ctl(fs_devices, &ctl);
5716
5717	devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
5718			       GFP_NOFS);
5719	if (!devices_info)
5720		return ERR_PTR(-ENOMEM);
5721
5722	ret = gather_device_info(fs_devices, &ctl, devices_info);
5723	if (ret < 0)
5724		return ERR_PTR(ret);
5725
5726	ret = decide_stripe_size(fs_devices, &ctl, devices_info);
5727	if (ret < 0)
5728		return ERR_PTR(ret);
5729
5730	return create_chunk(trans, &ctl, devices_info);
5731}
5732
5733/*
5734 * This function, btrfs_chunk_alloc_add_chunk_item(), typically belongs to the
5735 * phase 1 of chunk allocation. It belongs to phase 2 only when allocating system
5736 * chunks.
5737 *
5738 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
5739 * phases.
5740 */
5741int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
5742				     struct btrfs_block_group *bg)
5743{
5744	struct btrfs_fs_info *fs_info = trans->fs_info;
5745	struct btrfs_root *chunk_root = fs_info->chunk_root;
5746	struct btrfs_key key;
5747	struct btrfs_chunk *chunk;
5748	struct btrfs_stripe *stripe;
5749	struct btrfs_chunk_map *map;
5750	size_t item_size;
5751	int i;
5752	int ret;
5753
5754	/*
5755	 * We take the chunk_mutex for 2 reasons:
5756	 *
5757	 * 1) Updates and insertions in the chunk btree must be done while holding
5758	 *    the chunk_mutex, as well as updating the system chunk array in the
5759	 *    superblock. See the comment on top of btrfs_chunk_alloc() for the
5760	 *    details;
5761	 *
5762	 * 2) To prevent races with the final phase of a device replace operation
5763	 *    that replaces the device object associated with the map's stripes,
5764	 *    because the device object's id can change at any time during that
5765	 *    final phase of the device replace operation
5766	 *    (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
5767	 *    replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
5768	 *    which would cause a failure when updating the device item, which does
5769	 *    not exists, or persisting a stripe of the chunk item with such ID.
5770	 *    Here we can't use the device_list_mutex because our caller already
5771	 *    has locked the chunk_mutex, and the final phase of device replace
5772	 *    acquires both mutexes - first the device_list_mutex and then the
5773	 *    chunk_mutex. Using any of those two mutexes protects us from a
5774	 *    concurrent device replace.
5775	 */
5776	lockdep_assert_held(&fs_info->chunk_mutex);
5777
5778	map = btrfs_get_chunk_map(fs_info, bg->start, bg->length);
5779	if (IS_ERR(map)) {
5780		ret = PTR_ERR(map);
5781		btrfs_abort_transaction(trans, ret);
5782		return ret;
5783	}
5784
5785	item_size = btrfs_chunk_item_size(map->num_stripes);
5786
5787	chunk = kzalloc(item_size, GFP_NOFS);
5788	if (unlikely(!chunk)) {
5789		ret = -ENOMEM;
5790		btrfs_abort_transaction(trans, ret);
5791		goto out;
5792	}
5793
5794	for (i = 0; i < map->num_stripes; i++) {
5795		struct btrfs_device *device = map->stripes[i].dev;
5796
5797		ret = btrfs_update_device(trans, device);
5798		if (ret)
5799			goto out;
5800	}
5801
5802	stripe = &chunk->stripe;
5803	for (i = 0; i < map->num_stripes; i++) {
5804		struct btrfs_device *device = map->stripes[i].dev;
5805		const u64 dev_offset = map->stripes[i].physical;
5806
5807		btrfs_set_stack_stripe_devid(stripe, device->devid);
5808		btrfs_set_stack_stripe_offset(stripe, dev_offset);
5809		memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5810		stripe++;
5811	}
5812
5813	btrfs_set_stack_chunk_length(chunk, bg->length);
5814	btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
5815	btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
5816	btrfs_set_stack_chunk_type(chunk, map->type);
5817	btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5818	btrfs_set_stack_chunk_io_align(chunk, BTRFS_STRIPE_LEN);
5819	btrfs_set_stack_chunk_io_width(chunk, BTRFS_STRIPE_LEN);
5820	btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5821	btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5822
5823	key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5824	key.type = BTRFS_CHUNK_ITEM_KEY;
5825	key.offset = bg->start;
5826
5827	ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5828	if (ret)
5829		goto out;
5830
5831	set_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED, &bg->runtime_flags);
5832
5833	if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5834		ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5835		if (ret)
5836			goto out;
5837	}
5838
5839out:
5840	kfree(chunk);
5841	btrfs_free_chunk_map(map);
5842	return ret;
5843}
5844
5845static noinline int init_first_rw_device(struct btrfs_trans_handle *trans)
5846{
5847	struct btrfs_fs_info *fs_info = trans->fs_info;
5848	u64 alloc_profile;
5849	struct btrfs_block_group *meta_bg;
5850	struct btrfs_space_info *meta_space_info;
5851	struct btrfs_block_group *sys_bg;
5852	struct btrfs_space_info *sys_space_info;
5853
5854	/*
5855	 * When adding a new device for sprouting, the seed device is read-only
5856	 * so we must first allocate a metadata and a system chunk. But before
5857	 * adding the block group items to the extent, device and chunk btrees,
5858	 * we must first:
5859	 *
5860	 * 1) Create both chunks without doing any changes to the btrees, as
5861	 *    otherwise we would get -ENOSPC since the block groups from the
5862	 *    seed device are read-only;
5863	 *
5864	 * 2) Add the device item for the new sprout device - finishing the setup
5865	 *    of a new block group requires updating the device item in the chunk
5866	 *    btree, so it must exist when we attempt to do it. The previous step
5867	 *    ensures this does not fail with -ENOSPC.
5868	 *
5869	 * After that we can add the block group items to their btrees:
5870	 * update existing device item in the chunk btree, add a new block group
5871	 * item to the extent btree, add a new chunk item to the chunk btree and
5872	 * finally add the new device extent items to the devices btree.
5873	 */
5874
5875	alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5876	meta_space_info = btrfs_find_space_info(fs_info, alloc_profile);
5877	if (!meta_space_info) {
5878		DEBUG_WARN();
5879		return -EINVAL;
5880	}
5881	meta_bg = btrfs_create_chunk(trans, meta_space_info, alloc_profile);
5882	if (IS_ERR(meta_bg))
5883		return PTR_ERR(meta_bg);
5884
5885	alloc_profile = btrfs_system_alloc_profile(fs_info);
5886	sys_space_info = btrfs_find_space_info(fs_info, alloc_profile);
5887	if (!sys_space_info) {
5888		DEBUG_WARN();
5889		return -EINVAL;
5890	}
5891	sys_bg = btrfs_create_chunk(trans, sys_space_info, alloc_profile);
5892	if (IS_ERR(sys_bg))
5893		return PTR_ERR(sys_bg);
5894
5895	return 0;
5896}
5897
5898static inline int btrfs_chunk_max_errors(struct btrfs_chunk_map *map)
5899{
5900	const int index = btrfs_bg_flags_to_raid_index(map->type);
5901
5902	return btrfs_raid_array[index].tolerated_failures;
5903}
5904
5905bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5906{
5907	struct btrfs_chunk_map *map;
5908	int miss_ndevs = 0;
5909	int i;
5910	bool ret = true;
5911
5912	map = btrfs_get_chunk_map(fs_info, chunk_offset, 1);
5913	if (IS_ERR(map))
5914		return false;
5915
5916	for (i = 0; i < map->num_stripes; i++) {
5917		if (test_bit(BTRFS_DEV_STATE_MISSING,
5918					&map->stripes[i].dev->dev_state)) {
5919			miss_ndevs++;
5920			continue;
5921		}
5922		if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5923					&map->stripes[i].dev->dev_state)) {
5924			ret = false;
5925			goto end;
5926		}
5927	}
5928
5929	/*
5930	 * If the number of missing devices is larger than max errors, we can
5931	 * not write the data into that chunk successfully.
5932	 */
5933	if (miss_ndevs > btrfs_chunk_max_errors(map))
5934		ret = false;
5935end:
5936	btrfs_free_chunk_map(map);
5937	return ret;
5938}
5939
5940void btrfs_mapping_tree_free(struct btrfs_fs_info *fs_info)
5941{
5942	write_lock(&fs_info->mapping_tree_lock);
5943	while (!RB_EMPTY_ROOT(&fs_info->mapping_tree.rb_root)) {
5944		struct btrfs_chunk_map *map;
5945		struct rb_node *node;
5946
5947		node = rb_first_cached(&fs_info->mapping_tree);
5948		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
5949		rb_erase_cached(&map->rb_node, &fs_info->mapping_tree);
5950		RB_CLEAR_NODE(&map->rb_node);
5951		chunk_map_device_clear_bits(map, CHUNK_ALLOCATED);
5952		/* Once for the tree ref. */
5953		btrfs_free_chunk_map(map);
5954		cond_resched_rwlock_write(&fs_info->mapping_tree_lock);
5955	}
5956	write_unlock(&fs_info->mapping_tree_lock);
5957}
5958
5959static int btrfs_chunk_map_num_copies(const struct btrfs_chunk_map *map)
5960{
5961	enum btrfs_raid_types index = btrfs_bg_flags_to_raid_index(map->type);
5962
5963	if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5964		return 2;
5965
5966	/*
5967	 * There could be two corrupted data stripes, we need to loop retry in
5968	 * order to rebuild the correct data.
5969	 *
5970	 * Fail a stripe at a time on every retry except the stripe under
5971	 * reconstruction.
5972	 */
5973	if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5974		return map->num_stripes;
5975
5976	/* Non-RAID56, use their ncopies from btrfs_raid_array. */
5977	return btrfs_raid_array[index].ncopies;
5978}
5979
5980int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5981{
5982	struct btrfs_chunk_map *map;
5983	int ret;
5984
5985	map = btrfs_get_chunk_map(fs_info, logical, len);
5986	if (IS_ERR(map))
5987		/*
5988		 * We could return errors for these cases, but that could get
5989		 * ugly and we'd probably do the same thing which is just not do
5990		 * anything else and exit, so return 1 so the callers don't try
5991		 * to use other copies.
5992		 */
5993		return 1;
5994
5995	ret = btrfs_chunk_map_num_copies(map);
5996	btrfs_free_chunk_map(map);
5997	return ret;
5998}
5999
6000unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
6001				    u64 logical)
6002{
6003	struct btrfs_chunk_map *map;
6004	unsigned long len = fs_info->sectorsize;
6005
6006	if (!btrfs_fs_incompat(fs_info, RAID56))
6007		return len;
6008
6009	map = btrfs_get_chunk_map(fs_info, logical, len);
6010
6011	if (!WARN_ON(IS_ERR(map))) {
6012		if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6013			len = btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6014		btrfs_free_chunk_map(map);
6015	}
6016	return len;
6017}
6018
6019#ifdef CONFIG_BTRFS_EXPERIMENTAL
6020static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
6021{
6022	for (int index = first; index < first + num_stripes; index++) {
6023		const struct btrfs_device *device = map->stripes[index].dev;
6024
6025		if (device->devid == READ_ONCE(device->fs_devices->read_devid))
6026			return index;
6027	}
6028
6029	/* If no read-preferred device is set use the first stripe. */
6030	return first;
6031}
6032
6033struct stripe_mirror {
6034	u64 devid;
6035	int num;
6036};
6037
6038static int btrfs_cmp_devid(const void *a, const void *b)
6039{
6040	const struct stripe_mirror *s1 = (const struct stripe_mirror *)a;
6041	const struct stripe_mirror *s2 = (const struct stripe_mirror *)b;
6042
6043	if (s1->devid < s2->devid)
6044		return -1;
6045	if (s1->devid > s2->devid)
6046		return 1;
6047	return 0;
6048}
6049
6050/*
6051 * Select a stripe for reading using the round-robin algorithm.
6052 *
6053 *  1. Compute the read cycle as the total sectors read divided by the minimum
6054 *     sectors per device.
6055 *  2. Determine the stripe number for the current read by taking the modulus
6056 *     of the read cycle with the total number of stripes:
6057 *
6058 *      stripe index = (total sectors / min sectors per dev) % num stripes
6059 *
6060 * The calculated stripe index is then used to select the corresponding device
6061 * from the list of devices, which is ordered by devid.
6062 */
6063static int btrfs_read_rr(const struct btrfs_chunk_map *map, int first, int num_stripes)
6064{
6065	struct stripe_mirror stripes[BTRFS_RAID1_MAX_MIRRORS] = { 0 };
6066	struct btrfs_device *device  = map->stripes[first].dev;
6067	struct btrfs_fs_info *fs_info = device->fs_devices->fs_info;
6068	unsigned int read_cycle;
6069	unsigned int total_reads;
6070	unsigned int min_reads_per_dev;
6071
6072	total_reads = percpu_counter_sum(&fs_info->stats_read_blocks);
6073	min_reads_per_dev = READ_ONCE(fs_info->fs_devices->rr_min_contig_read) >>
6074						       fs_info->sectorsize_bits;
6075
6076	for (int index = 0, i = first; i < first + num_stripes; i++) {
6077		stripes[index].devid = map->stripes[i].dev->devid;
6078		stripes[index].num = i;
6079		index++;
6080	}
6081	sort(stripes, num_stripes, sizeof(struct stripe_mirror),
6082	     btrfs_cmp_devid, NULL);
6083
6084	read_cycle = total_reads / min_reads_per_dev;
6085	return stripes[read_cycle % num_stripes].num;
6086}
6087#endif
6088
6089static int find_live_mirror(struct btrfs_fs_info *fs_info,
6090			    struct btrfs_chunk_map *map, int first,
6091			    bool dev_replace_is_ongoing)
6092{
6093	const enum btrfs_read_policy policy = READ_ONCE(fs_info->fs_devices->read_policy);
6094	int i;
6095	int num_stripes;
6096	int preferred_mirror;
6097	int tolerance;
6098	struct btrfs_device *srcdev;
6099
6100	ASSERT((map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10)),
6101	       "type=%llu", map->type);
6102
6103	if (map->type & BTRFS_BLOCK_GROUP_RAID10)
6104		num_stripes = map->sub_stripes;
6105	else
6106		num_stripes = map->num_stripes;
6107
6108	switch (policy) {
6109	default:
6110		/* Shouldn't happen, just warn and use pid instead of failing */
6111		btrfs_warn_rl(fs_info, "unknown read_policy type %u, reset to pid",
6112			      policy);
6113		WRITE_ONCE(fs_info->fs_devices->read_policy, BTRFS_READ_POLICY_PID);
6114		fallthrough;
6115	case BTRFS_READ_POLICY_PID:
6116		preferred_mirror = first + (current->pid % num_stripes);
6117		break;
6118#ifdef CONFIG_BTRFS_EXPERIMENTAL
6119	case BTRFS_READ_POLICY_RR:
6120		preferred_mirror = btrfs_read_rr(map, first, num_stripes);
6121		break;
6122	case BTRFS_READ_POLICY_DEVID:
6123		preferred_mirror = btrfs_read_preferred(map, first, num_stripes);
6124		break;
6125#endif
6126	}
6127
6128	if (dev_replace_is_ongoing &&
6129	    fs_info->dev_replace.cont_reading_from_srcdev_mode ==
6130	     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
6131		srcdev = fs_info->dev_replace.srcdev;
6132	else
6133		srcdev = NULL;
6134
6135	/*
6136	 * try to avoid the drive that is the source drive for a
6137	 * dev-replace procedure, only choose it if no other non-missing
6138	 * mirror is available
6139	 */
6140	for (tolerance = 0; tolerance < 2; tolerance++) {
6141		if (map->stripes[preferred_mirror].dev->bdev &&
6142		    (tolerance || map->stripes[preferred_mirror].dev != srcdev))
6143			return preferred_mirror;
6144		for (i = first; i < first + num_stripes; i++) {
6145			if (map->stripes[i].dev->bdev &&
6146			    (tolerance || map->stripes[i].dev != srcdev))
6147				return i;
6148		}
6149	}
6150
6151	/* we couldn't find one that doesn't fail.  Just return something
6152	 * and the io error handling code will clean up eventually
6153	 */
6154	return preferred_mirror;
6155}
6156
6157EXPORT_FOR_TESTS
6158struct btrfs_io_context *alloc_btrfs_io_context(struct btrfs_fs_info *fs_info,
6159						u64 logical, u16 total_stripes)
6160{
6161	struct btrfs_io_context *bioc;
6162
6163	bioc = kzalloc(struct_size(bioc, stripes, total_stripes), GFP_NOFS);
6164
6165	if (!bioc)
6166		return NULL;
6167
6168	refcount_set(&bioc->refs, 1);
6169
6170	bioc->fs_info = fs_info;
6171	bioc->replace_stripe_src = -1;
6172	bioc->full_stripe_logical = (u64)-1;
6173	bioc->logical = logical;
6174
6175	return bioc;
6176}
6177
6178void btrfs_get_bioc(struct btrfs_io_context *bioc)
6179{
6180	WARN_ON(!refcount_read(&bioc->refs));
6181	refcount_inc(&bioc->refs);
6182}
6183
6184void btrfs_put_bioc(struct btrfs_io_context *bioc)
6185{
6186	if (!bioc)
6187		return;
6188	if (refcount_dec_and_test(&bioc->refs))
6189		kfree(bioc);
6190}
6191
6192/*
6193 * Please note that, discard won't be sent to target device of device
6194 * replace.
6195 */
6196struct btrfs_discard_stripe *btrfs_map_discard(struct btrfs_fs_info *fs_info,
6197					       u64 logical, u64 *length_ret,
6198					       u32 *num_stripes)
6199{
6200	struct btrfs_chunk_map *map;
6201	struct btrfs_discard_stripe *stripes;
6202	u64 length = *length_ret;
6203	u64 offset;
6204	u32 stripe_nr;
6205	u32 stripe_nr_end;
6206	u32 stripe_cnt;
6207	u64 stripe_end_offset;
6208	u64 stripe_offset;
6209	u32 stripe_index;
6210	u32 factor = 0;
6211	u32 sub_stripes = 0;
6212	u32 stripes_per_dev = 0;
6213	u32 remaining_stripes = 0;
6214	u32 last_stripe = 0;
6215	int ret;
6216	int i;
6217
6218	map = btrfs_get_chunk_map(fs_info, logical, length);
6219	if (IS_ERR(map))
6220		return ERR_CAST(map);
6221
6222	/* we don't discard raid56 yet */
6223	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6224		ret = -EOPNOTSUPP;
6225		goto out_free_map;
6226	}
6227
6228	offset = logical - map->start;
6229	length = min_t(u64, map->start + map->chunk_len - logical, length);
6230	*length_ret = length;
6231
6232	/*
6233	 * stripe_nr counts the total number of stripes we have to stride
6234	 * to get to this block
6235	 */
6236	stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6237
6238	/* stripe_offset is the offset of this block in its stripe */
6239	stripe_offset = offset - btrfs_stripe_nr_to_offset(stripe_nr);
6240
6241	stripe_nr_end = round_up(offset + length, BTRFS_STRIPE_LEN) >>
6242			BTRFS_STRIPE_LEN_SHIFT;
6243	stripe_cnt = stripe_nr_end - stripe_nr;
6244	stripe_end_offset = btrfs_stripe_nr_to_offset(stripe_nr_end) -
6245			    (offset + length);
6246	/*
6247	 * after this, stripe_nr is the number of stripes on this
6248	 * device we have to walk to find the data, and stripe_index is
6249	 * the number of our device in the stripe array
6250	 */
6251	*num_stripes = 1;
6252	stripe_index = 0;
6253	if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6254			 BTRFS_BLOCK_GROUP_RAID10)) {
6255		if (map->type & BTRFS_BLOCK_GROUP_RAID0)
6256			sub_stripes = 1;
6257		else
6258			sub_stripes = map->sub_stripes;
6259
6260		factor = map->num_stripes / sub_stripes;
6261		*num_stripes = min_t(u64, map->num_stripes,
6262				    sub_stripes * stripe_cnt);
6263		stripe_index = stripe_nr % factor;
6264		stripe_nr /= factor;
6265		stripe_index *= sub_stripes;
6266
6267		remaining_stripes = stripe_cnt % factor;
6268		stripes_per_dev = stripe_cnt / factor;
6269		last_stripe = ((stripe_nr_end - 1) % factor) * sub_stripes;
6270	} else if (map->type & (BTRFS_BLOCK_GROUP_RAID1_MASK |
6271				BTRFS_BLOCK_GROUP_DUP)) {
6272		*num_stripes = map->num_stripes;
6273	} else {
6274		stripe_index = stripe_nr % map->num_stripes;
6275		stripe_nr /= map->num_stripes;
6276	}
6277
6278	stripes = kcalloc(*num_stripes, sizeof(*stripes), GFP_NOFS);
6279	if (!stripes) {
6280		ret = -ENOMEM;
6281		goto out_free_map;
6282	}
6283
6284	for (i = 0; i < *num_stripes; i++) {
6285		stripes[i].physical =
6286			map->stripes[stripe_index].physical +
6287			stripe_offset + btrfs_stripe_nr_to_offset(stripe_nr);
6288		stripes[i].dev = map->stripes[stripe_index].dev;
6289
6290		if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
6291				 BTRFS_BLOCK_GROUP_RAID10)) {
6292			stripes[i].length = btrfs_stripe_nr_to_offset(stripes_per_dev);
6293
6294			if (i / sub_stripes < remaining_stripes)
6295				stripes[i].length += BTRFS_STRIPE_LEN;
6296
6297			/*
6298			 * Special for the first stripe and
6299			 * the last stripe:
6300			 *
6301			 * |-------|...|-------|
6302			 *     |----------|
6303			 *    off     end_off
6304			 */
6305			if (i < sub_stripes)
6306				stripes[i].length -= stripe_offset;
6307
6308			if (stripe_index >= last_stripe &&
6309			    stripe_index <= (last_stripe +
6310					     sub_stripes - 1))
6311				stripes[i].length -= stripe_end_offset;
6312
6313			if (i == sub_stripes - 1)
6314				stripe_offset = 0;
6315		} else {
6316			stripes[i].length = length;
6317		}
6318
6319		stripe_index++;
6320		if (stripe_index == map->num_stripes) {
6321			stripe_index = 0;
6322			stripe_nr++;
6323		}
6324	}
6325
6326	btrfs_free_chunk_map(map);
6327	return stripes;
6328out_free_map:
6329	btrfs_free_chunk_map(map);
6330	return ERR_PTR(ret);
6331}
6332
6333static bool is_block_group_to_copy(struct btrfs_fs_info *fs_info, u64 logical)
6334{
6335	struct btrfs_block_group *cache;
6336	bool ret;
6337
6338	/* Non zoned filesystem does not use "to_copy" flag */
6339	if (!btrfs_is_zoned(fs_info))
6340		return false;
6341
6342	cache = btrfs_lookup_block_group(fs_info, logical);
6343
6344	ret = test_bit(BLOCK_GROUP_FLAG_TO_COPY, &cache->runtime_flags);
6345
6346	btrfs_put_block_group(cache);
6347	return ret;
6348}
6349
6350static void handle_ops_on_dev_replace(struct btrfs_io_context *bioc,
6351				      struct btrfs_dev_replace *dev_replace,
6352				      u64 logical,
6353				      struct btrfs_io_geometry *io_geom)
6354{
6355	u64 srcdev_devid = dev_replace->srcdev->devid;
6356	/*
6357	 * At this stage, num_stripes is still the real number of stripes,
6358	 * excluding the duplicated stripes.
6359	 */
6360	int num_stripes = io_geom->num_stripes;
6361	int max_errors = io_geom->max_errors;
6362	int nr_extra_stripes = 0;
6363	int i;
6364
6365	/*
6366	 * A block group which has "to_copy" set will eventually be copied by
6367	 * the dev-replace process. We can avoid cloning IO here.
6368	 */
6369	if (is_block_group_to_copy(dev_replace->srcdev->fs_info, logical))
6370		return;
6371
6372	/*
6373	 * Duplicate the write operations while the dev-replace procedure is
6374	 * running. Since the copying of the old disk to the new disk takes
6375	 * place at run time while the filesystem is mounted writable, the
6376	 * regular write operations to the old disk have to be duplicated to go
6377	 * to the new disk as well.
6378	 *
6379	 * Note that device->missing is handled by the caller, and that the
6380	 * write to the old disk is already set up in the stripes array.
6381	 */
6382	for (i = 0; i < num_stripes; i++) {
6383		struct btrfs_io_stripe *old = &bioc->stripes[i];
6384		struct btrfs_io_stripe *new = &bioc->stripes[num_stripes + nr_extra_stripes];
6385
6386		if (old->dev->devid != srcdev_devid)
6387			continue;
6388
6389		new->physical = old->physical;
6390		new->dev = dev_replace->tgtdev;
6391		if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
6392			bioc->replace_stripe_src = i;
6393		nr_extra_stripes++;
6394	}
6395
6396	/* We can only have at most 2 extra nr_stripes (for DUP). */
6397	ASSERT(nr_extra_stripes <= 2, "nr_extra_stripes=%d", nr_extra_stripes);
6398	/*
6399	 * For GET_READ_MIRRORS, we can only return at most 1 extra stripe for
6400	 * replace.
6401	 * If we have 2 extra stripes, only choose the one with smaller physical.
6402	 */
6403	if (io_geom->op == BTRFS_MAP_GET_READ_MIRRORS && nr_extra_stripes == 2) {
6404		struct btrfs_io_stripe *first = &bioc->stripes[num_stripes];
6405		struct btrfs_io_stripe *second = &bioc->stripes[num_stripes + 1];
6406
6407		/* Only DUP can have two extra stripes. */
6408		ASSERT(bioc->map_type & BTRFS_BLOCK_GROUP_DUP,
6409		       "map_type=%llu", bioc->map_type);
6410
6411		/*
6412		 * Swap the last stripe stripes and reduce @nr_extra_stripes.
6413		 * The extra stripe would still be there, but won't be accessed.
6414		 */
6415		if (first->physical > second->physical) {
6416			swap(second->physical, first->physical);
6417			swap(second->dev, first->dev);
6418			nr_extra_stripes--;
6419		}
6420	}
6421
6422	io_geom->num_stripes = num_stripes + nr_extra_stripes;
6423	io_geom->max_errors = max_errors + nr_extra_stripes;
6424	bioc->replace_nr_stripes = nr_extra_stripes;
6425}
6426
6427static u64 btrfs_max_io_len(struct btrfs_chunk_map *map, u64 offset,
6428			    struct btrfs_io_geometry *io_geom)
6429{
6430	/*
6431	 * Stripe_nr is the stripe where this block falls.  stripe_offset is
6432	 * the offset of this block in its stripe.
6433	 */
6434	io_geom->stripe_offset = offset & BTRFS_STRIPE_LEN_MASK;
6435	io_geom->stripe_nr = offset >> BTRFS_STRIPE_LEN_SHIFT;
6436	ASSERT(io_geom->stripe_offset < U32_MAX,
6437	       "stripe_offset=%llu", io_geom->stripe_offset);
6438
6439	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
6440		unsigned long full_stripe_len =
6441			btrfs_stripe_nr_to_offset(nr_data_stripes(map));
6442
6443		/*
6444		 * For full stripe start, we use previously calculated
6445		 * @stripe_nr. Align it to nr_data_stripes, then multiply with
6446		 * STRIPE_LEN.
6447		 *
6448		 * By this we can avoid u64 division completely.  And we have
6449		 * to go rounddown(), not round_down(), as nr_data_stripes is
6450		 * not ensured to be power of 2.
6451		 */
6452		io_geom->raid56_full_stripe_start = btrfs_stripe_nr_to_offset(
6453			rounddown(io_geom->stripe_nr, nr_data_stripes(map)));
6454
6455		ASSERT(io_geom->raid56_full_stripe_start + full_stripe_len > offset,
6456		       "raid56_full_stripe_start=%llu full_stripe_len=%lu offset=%llu",
6457		       io_geom->raid56_full_stripe_start, full_stripe_len, offset);
6458		ASSERT(io_geom->raid56_full_stripe_start <= offset,
6459		       "raid56_full_stripe_start=%llu offset=%llu",
6460		       io_geom->raid56_full_stripe_start, offset);
6461		/*
6462		 * For writes to RAID56, allow to write a full stripe set, but
6463		 * no straddling of stripe sets.
6464		 */
6465		if (io_geom->op == BTRFS_MAP_WRITE)
6466			return full_stripe_len - (offset - io_geom->raid56_full_stripe_start);
6467	}
6468
6469	/*
6470	 * For other RAID types and for RAID56 reads, allow a single stripe (on
6471	 * a single disk).
6472	 */
6473	if (map->type & BTRFS_BLOCK_GROUP_STRIPE_MASK)
6474		return BTRFS_STRIPE_LEN - io_geom->stripe_offset;
6475	return U64_MAX;
6476}
6477
6478static int set_io_stripe(struct btrfs_fs_info *fs_info, u64 logical,
6479			 u64 *length, struct btrfs_io_stripe *dst,
6480			 struct btrfs_chunk_map *map,
6481			 struct btrfs_io_geometry *io_geom)
6482{
6483	dst->dev = map->stripes[io_geom->stripe_index].dev;
6484
6485	if (io_geom->op == BTRFS_MAP_READ && io_geom->use_rst)
6486		return btrfs_get_raid_extent_offset(fs_info, logical, length,
6487						    map->type,
6488						    io_geom->stripe_index, dst);
6489
6490	dst->physical = map->stripes[io_geom->stripe_index].physical +
6491			io_geom->stripe_offset +
6492			btrfs_stripe_nr_to_offset(io_geom->stripe_nr);
6493	return 0;
6494}
6495
6496static bool is_single_device_io(struct btrfs_fs_info *fs_info,
6497				const struct btrfs_io_stripe *smap,
6498				const struct btrfs_chunk_map *map,
6499				int num_alloc_stripes,
6500				struct btrfs_io_geometry *io_geom)
6501{
6502	if (!smap)
6503		return false;
6504
6505	if (num_alloc_stripes != 1)
6506		return false;
6507
6508	if (io_geom->use_rst && io_geom->op != BTRFS_MAP_READ)
6509		return false;
6510
6511	if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) && io_geom->mirror_num > 1)
6512		return false;
6513
6514	return true;
6515}
6516
6517static void map_blocks_raid0(const struct btrfs_chunk_map *map,
6518			     struct btrfs_io_geometry *io_geom)
6519{
6520	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6521	io_geom->stripe_nr /= map->num_stripes;
6522	if (io_geom->op == BTRFS_MAP_READ)
6523		io_geom->mirror_num = 1;
6524}
6525
6526static void map_blocks_raid1(struct btrfs_fs_info *fs_info,
6527			     struct btrfs_chunk_map *map,
6528			     struct btrfs_io_geometry *io_geom,
6529			     bool dev_replace_is_ongoing)
6530{
6531	if (io_geom->op != BTRFS_MAP_READ) {
6532		io_geom->num_stripes = map->num_stripes;
6533		return;
6534	}
6535
6536	if (io_geom->mirror_num) {
6537		io_geom->stripe_index = io_geom->mirror_num - 1;
6538		return;
6539	}
6540
6541	io_geom->stripe_index = find_live_mirror(fs_info, map, 0,
6542						 dev_replace_is_ongoing);
6543	io_geom->mirror_num = io_geom->stripe_index + 1;
6544}
6545
6546static void map_blocks_dup(const struct btrfs_chunk_map *map,
6547			   struct btrfs_io_geometry *io_geom)
6548{
6549	if (io_geom->op != BTRFS_MAP_READ) {
6550		io_geom->num_stripes = map->num_stripes;
6551		return;
6552	}
6553
6554	if (io_geom->mirror_num) {
6555		io_geom->stripe_index = io_geom->mirror_num - 1;
6556		return;
6557	}
6558
6559	io_geom->mirror_num = 1;
6560}
6561
6562static void map_blocks_raid10(struct btrfs_fs_info *fs_info,
6563			      struct btrfs_chunk_map *map,
6564			      struct btrfs_io_geometry *io_geom,
6565			      bool dev_replace_is_ongoing)
6566{
6567	u32 factor = map->num_stripes / map->sub_stripes;
6568	int old_stripe_index;
6569
6570	io_geom->stripe_index = (io_geom->stripe_nr % factor) * map->sub_stripes;
6571	io_geom->stripe_nr /= factor;
6572
6573	if (io_geom->op != BTRFS_MAP_READ) {
6574		io_geom->num_stripes = map->sub_stripes;
6575		return;
6576	}
6577
6578	if (io_geom->mirror_num) {
6579		io_geom->stripe_index += io_geom->mirror_num - 1;
6580		return;
6581	}
6582
6583	old_stripe_index = io_geom->stripe_index;
6584	io_geom->stripe_index = find_live_mirror(fs_info, map,
6585						 io_geom->stripe_index,
6586						 dev_replace_is_ongoing);
6587	io_geom->mirror_num = io_geom->stripe_index - old_stripe_index + 1;
6588}
6589
6590static void map_blocks_raid56_write(struct btrfs_chunk_map *map,
6591				    struct btrfs_io_geometry *io_geom,
6592				    u64 logical, u64 *length)
6593{
6594	int data_stripes = nr_data_stripes(map);
6595
6596	/*
6597	 * Needs full stripe mapping.
6598	 *
6599	 * Push stripe_nr back to the start of the full stripe For those cases
6600	 * needing a full stripe, @stripe_nr is the full stripe number.
6601	 *
6602	 * Originally we go raid56_full_stripe_start / full_stripe_len, but
6603	 * that can be expensive.  Here we just divide @stripe_nr with
6604	 * @data_stripes.
6605	 */
6606	io_geom->stripe_nr /= data_stripes;
6607
6608	/* RAID[56] write or recovery. Return all stripes */
6609	io_geom->num_stripes = map->num_stripes;
6610	io_geom->max_errors = btrfs_chunk_max_errors(map);
6611
6612	/* Return the length to the full stripe end. */
6613	*length = min(logical + *length,
6614		      io_geom->raid56_full_stripe_start + map->start +
6615		      btrfs_stripe_nr_to_offset(data_stripes)) -
6616		logical;
6617	io_geom->stripe_index = 0;
6618	io_geom->stripe_offset = 0;
6619}
6620
6621static void map_blocks_raid56_read(struct btrfs_chunk_map *map,
6622				   struct btrfs_io_geometry *io_geom)
6623{
6624	int data_stripes = nr_data_stripes(map);
6625
6626	ASSERT(io_geom->mirror_num <= 1, "mirror_num=%d", io_geom->mirror_num);
6627	/* Just grab the data stripe directly. */
6628	io_geom->stripe_index = io_geom->stripe_nr % data_stripes;
6629	io_geom->stripe_nr /= data_stripes;
6630
6631	/* We distribute the parity blocks across stripes. */
6632	io_geom->stripe_index =
6633		(io_geom->stripe_nr + io_geom->stripe_index) % map->num_stripes;
6634
6635	if (io_geom->op == BTRFS_MAP_READ && io_geom->mirror_num < 1)
6636		io_geom->mirror_num = 1;
6637}
6638
6639static void map_blocks_single(const struct btrfs_chunk_map *map,
6640			      struct btrfs_io_geometry *io_geom)
6641{
6642	io_geom->stripe_index = io_geom->stripe_nr % map->num_stripes;
6643	io_geom->stripe_nr /= map->num_stripes;
6644	io_geom->mirror_num = io_geom->stripe_index + 1;
6645}
6646
6647/*
6648 * Map one logical range to one or more physical ranges.
6649 *
6650 * @length:		(Mandatory) mapped length of this run.
6651 *			One logical range can be split into different segments
6652 *			due to factors like zones and RAID0/5/6/10 stripe
6653 *			boundaries.
6654 *
6655 * @bioc_ret:		(Mandatory) returned btrfs_io_context structure.
6656 *			which has one or more physical ranges (btrfs_io_stripe)
6657 *			recorded inside.
6658 *			Caller should call btrfs_put_bioc() to free it after use.
6659 *
6660 * @smap:		(Optional) single physical range optimization.
6661 *			If the map request can be fulfilled by one single
6662 *			physical range, and this is parameter is not NULL,
6663 *			then @bioc_ret would be NULL, and @smap would be
6664 *			updated.
6665 *
6666 * @mirror_num_ret:	(Mandatory) returned mirror number if the original
6667 *			value is 0.
6668 *
6669 *			Mirror number 0 means to choose any live mirrors.
6670 *
6671 *			For non-RAID56 profiles, non-zero mirror_num means
6672 *			the Nth mirror. (e.g. mirror_num 1 means the first
6673 *			copy).
6674 *
6675 *			For RAID56 profile, mirror 1 means rebuild from P and
6676 *			the remaining data stripes.
6677 *
6678 *			For RAID6 profile, mirror > 2 means mark another
6679 *			data/P stripe error and rebuild from the remaining
6680 *			stripes..
6681 */
6682int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
6683		    u64 logical, u64 *length,
6684		    struct btrfs_io_context **bioc_ret,
6685		    struct btrfs_io_stripe *smap, int *mirror_num_ret)
6686{
6687	struct btrfs_chunk_map *map;
6688	struct btrfs_io_geometry io_geom = { 0 };
6689	u64 map_offset;
6690	int ret = 0;
6691	int num_copies;
6692	struct btrfs_io_context *bioc = NULL;
6693	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
6694	bool dev_replace_is_ongoing = false;
6695	u16 num_alloc_stripes;
6696	u64 max_len;
6697
6698	ASSERT(bioc_ret);
6699
6700	io_geom.mirror_num = (mirror_num_ret ? *mirror_num_ret : 0);
6701	io_geom.num_stripes = 1;
6702	io_geom.stripe_index = 0;
6703	io_geom.op = op;
6704
6705	map = btrfs_get_chunk_map(fs_info, logical, *length);
6706	if (IS_ERR(map))
6707		return PTR_ERR(map);
6708
6709	num_copies = btrfs_chunk_map_num_copies(map);
6710	if (io_geom.mirror_num > num_copies) {
6711		ret = -EINVAL;
6712		goto out;
6713	}
6714
6715	map_offset = logical - map->start;
6716	io_geom.raid56_full_stripe_start = (u64)-1;
6717	max_len = btrfs_max_io_len(map, map_offset, &io_geom);
6718	*length = min_t(u64, map->chunk_len - map_offset, max_len);
6719	io_geom.use_rst = btrfs_need_stripe_tree_update(fs_info, map->type);
6720
6721	if (dev_replace->replace_task != current)
6722		down_read(&dev_replace->rwsem);
6723
6724	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
6725	/*
6726	 * Hold the semaphore for read during the whole operation, write is
6727	 * requested at commit time but must wait.
6728	 */
6729	if (!dev_replace_is_ongoing && dev_replace->replace_task != current)
6730		up_read(&dev_replace->rwsem);
6731
6732	switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
6733	case BTRFS_BLOCK_GROUP_RAID0:
6734		map_blocks_raid0(map, &io_geom);
6735		break;
6736	case BTRFS_BLOCK_GROUP_RAID1:
6737	case BTRFS_BLOCK_GROUP_RAID1C3:
6738	case BTRFS_BLOCK_GROUP_RAID1C4:
6739		map_blocks_raid1(fs_info, map, &io_geom, dev_replace_is_ongoing);
6740		break;
6741	case BTRFS_BLOCK_GROUP_DUP:
6742		map_blocks_dup(map, &io_geom);
6743		break;
6744	case BTRFS_BLOCK_GROUP_RAID10:
6745		map_blocks_raid10(fs_info, map, &io_geom, dev_replace_is_ongoing);
6746		break;
6747	case BTRFS_BLOCK_GROUP_RAID5:
6748	case BTRFS_BLOCK_GROUP_RAID6:
6749		if (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)
6750			map_blocks_raid56_write(map, &io_geom, logical, length);
6751		else
6752			map_blocks_raid56_read(map, &io_geom);
6753		break;
6754	default:
6755		/*
6756		 * After this, stripe_nr is the number of stripes on this
6757		 * device we have to walk to find the data, and stripe_index is
6758		 * the number of our device in the stripe array
6759		 */
6760		map_blocks_single(map, &io_geom);
6761		break;
6762	}
6763	if (io_geom.stripe_index >= map->num_stripes) {
6764		btrfs_crit(fs_info,
6765			   "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
6766			   io_geom.stripe_index, map->num_stripes);
6767		ret = -EINVAL;
6768		goto out;
6769	}
6770
6771	num_alloc_stripes = io_geom.num_stripes;
6772	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6773	    op != BTRFS_MAP_READ)
6774		/*
6775		 * For replace case, we need to add extra stripes for extra
6776		 * duplicated stripes.
6777		 *
6778		 * For both WRITE and GET_READ_MIRRORS, we may have at most
6779		 * 2 more stripes (DUP types, otherwise 1).
6780		 */
6781		num_alloc_stripes += 2;
6782
6783	/*
6784	 * If this I/O maps to a single device, try to return the device and
6785	 * physical block information on the stack instead of allocating an
6786	 * I/O context structure.
6787	 */
6788	if (is_single_device_io(fs_info, smap, map, num_alloc_stripes, &io_geom)) {
6789		ret = set_io_stripe(fs_info, logical, length, smap, map, &io_geom);
6790		if (mirror_num_ret)
6791			*mirror_num_ret = io_geom.mirror_num;
6792		*bioc_ret = NULL;
6793		goto out;
6794	}
6795
6796	bioc = alloc_btrfs_io_context(fs_info, logical, num_alloc_stripes);
6797	if (!bioc) {
6798		ret = -ENOMEM;
6799		goto out;
6800	}
6801	bioc->map_type = map->type;
6802	bioc->use_rst = io_geom.use_rst;
6803
6804	/*
6805	 * For RAID56 full map, we need to make sure the stripes[] follows the
6806	 * rule that data stripes are all ordered, then followed with P and Q
6807	 * (if we have).
6808	 *
6809	 * It's still mostly the same as other profiles, just with extra rotation.
6810	 */
6811	if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK &&
6812	    (op != BTRFS_MAP_READ || io_geom.mirror_num > 1)) {
6813		/*
6814		 * For RAID56 @stripe_nr is already the number of full stripes
6815		 * before us, which is also the rotation value (needs to modulo
6816		 * with num_stripes).
6817		 *
6818		 * In this case, we just add @stripe_nr with @i, then do the
6819		 * modulo, to reduce one modulo call.
6820		 */
6821		bioc->full_stripe_logical = map->start +
6822			btrfs_stripe_nr_to_offset(io_geom.stripe_nr *
6823						  nr_data_stripes(map));
6824		for (int i = 0; i < io_geom.num_stripes; i++) {
6825			struct btrfs_io_stripe *dst = &bioc->stripes[i];
6826			u32 stripe_index;
6827
6828			stripe_index = (i + io_geom.stripe_nr) % io_geom.num_stripes;
6829			dst->dev = map->stripes[stripe_index].dev;
6830			dst->physical =
6831				map->stripes[stripe_index].physical +
6832				io_geom.stripe_offset +
6833				btrfs_stripe_nr_to_offset(io_geom.stripe_nr);
6834		}
6835	} else {
6836		/*
6837		 * For all other non-RAID56 profiles, just copy the target
6838		 * stripe into the bioc.
6839		 */
6840		for (int i = 0; i < io_geom.num_stripes; i++) {
6841			ret = set_io_stripe(fs_info, logical, length,
6842					    &bioc->stripes[i], map, &io_geom);
6843			if (ret < 0)
6844				break;
6845			io_geom.stripe_index++;
6846		}
6847	}
6848
6849	if (ret) {
6850		*bioc_ret = NULL;
6851		btrfs_put_bioc(bioc);
6852		goto out;
6853	}
6854
6855	if (op != BTRFS_MAP_READ)
6856		io_geom.max_errors = btrfs_chunk_max_errors(map);
6857
6858	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
6859	    op != BTRFS_MAP_READ) {
6860		handle_ops_on_dev_replace(bioc, dev_replace, logical, &io_geom);
6861	}
6862
6863	*bioc_ret = bioc;
6864	bioc->num_stripes = io_geom.num_stripes;
6865	bioc->max_errors = io_geom.max_errors;
6866	bioc->mirror_num = io_geom.mirror_num;
6867
6868out:
6869	if (dev_replace_is_ongoing && dev_replace->replace_task != current) {
6870		lockdep_assert_held(&dev_replace->rwsem);
6871		/* Unlock and let waiting writers proceed */
6872		up_read(&dev_replace->rwsem);
6873	}
6874	btrfs_free_chunk_map(map);
6875	return ret;
6876}
6877
6878static bool dev_args_match_fs_devices(const struct btrfs_dev_lookup_args *args,
6879				      const struct btrfs_fs_devices *fs_devices)
6880{
6881	if (args->fsid == NULL)
6882		return true;
6883	if (memcmp(fs_devices->metadata_uuid, args->fsid, BTRFS_FSID_SIZE) == 0)
6884		return true;
6885	return false;
6886}
6887
6888static bool dev_args_match_device(const struct btrfs_dev_lookup_args *args,
6889				  const struct btrfs_device *device)
6890{
6891	if (args->devt)
6892		return device->devt == args->devt;
6893	if (args->missing) {
6894		if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state) &&
6895		    !device->bdev)
6896			return true;
6897		return false;
6898	}
6899
6900	if (device->devid != args->devid)
6901		return false;
6902	if (args->uuid && memcmp(device->uuid, args->uuid, BTRFS_UUID_SIZE) != 0)
6903		return false;
6904	return true;
6905}
6906
6907/*
6908 * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6909 * return NULL.
6910 *
6911 * If devid and uuid are both specified, the match must be exact, otherwise
6912 * only devid is used.
6913 */
6914struct btrfs_device *btrfs_find_device(const struct btrfs_fs_devices *fs_devices,
6915				       const struct btrfs_dev_lookup_args *args)
6916{
6917	struct btrfs_device *device;
6918	struct btrfs_fs_devices *seed_devs;
6919
6920	if (dev_args_match_fs_devices(args, fs_devices)) {
6921		list_for_each_entry(device, &fs_devices->devices, dev_list) {
6922			if (dev_args_match_device(args, device))
6923				return device;
6924		}
6925	}
6926
6927	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
6928		if (!dev_args_match_fs_devices(args, seed_devs))
6929			continue;
6930		list_for_each_entry(device, &seed_devs->devices, dev_list) {
6931			if (dev_args_match_device(args, device))
6932				return device;
6933		}
6934	}
6935
6936	return NULL;
6937}
6938
6939static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6940					    u64 devid, u8 *dev_uuid)
6941{
6942	struct btrfs_device *device;
6943	unsigned int nofs_flag;
6944
6945	/*
6946	 * We call this under the chunk_mutex, so we want to use NOFS for this
6947	 * allocation, however we don't want to change btrfs_alloc_device() to
6948	 * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6949	 * places.
6950	 */
6951
6952	nofs_flag = memalloc_nofs_save();
6953	device = btrfs_alloc_device(NULL, &devid, dev_uuid, NULL);
6954	memalloc_nofs_restore(nofs_flag);
6955	if (IS_ERR(device))
6956		return device;
6957
6958	list_add(&device->dev_list, &fs_devices->devices);
6959	device->fs_devices = fs_devices;
6960	fs_devices->num_devices++;
6961
6962	set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6963	fs_devices->missing_devices++;
6964
6965	return device;
6966}
6967
6968/*
6969 * Allocate new device struct, set up devid and UUID.
6970 *
6971 * @fs_info:	used only for generating a new devid, can be NULL if
6972 *		devid is provided (i.e. @devid != NULL).
6973 * @devid:	a pointer to devid for this device.  If NULL a new devid
6974 *		is generated.
6975 * @uuid:	a pointer to UUID for this device.  If NULL a new UUID
6976 *		is generated.
6977 * @path:	a pointer to device path if available, NULL otherwise.
6978 *
6979 * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6980 * on error.  Returned struct is not linked onto any lists and must be
6981 * destroyed with btrfs_free_device.
6982 */
6983struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6984					const u64 *devid, const u8 *uuid,
6985					const char *path)
6986{
6987	struct btrfs_device *dev;
6988	u64 tmp;
6989
6990	if (WARN_ON(!devid && !fs_info))
6991		return ERR_PTR(-EINVAL);
6992
6993	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
6994	if (!dev)
6995		return ERR_PTR(-ENOMEM);
6996
6997	INIT_LIST_HEAD(&dev->dev_list);
6998	INIT_LIST_HEAD(&dev->dev_alloc_list);
6999	INIT_LIST_HEAD(&dev->post_commit_list);
7000
7001	atomic_set(&dev->dev_stats_ccnt, 0);
7002	btrfs_device_data_ordered_init(dev);
7003	btrfs_extent_io_tree_init(fs_info, &dev->alloc_state, IO_TREE_DEVICE_ALLOC_STATE);
7004
7005	if (devid)
7006		tmp = *devid;
7007	else {
7008		int ret;
7009
7010		ret = find_next_devid(fs_info, &tmp);
7011		if (ret) {
7012			btrfs_free_device(dev);
7013			return ERR_PTR(ret);
7014		}
7015	}
7016	dev->devid = tmp;
7017
7018	if (uuid)
7019		memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
7020	else
7021		generate_random_uuid(dev->uuid);
7022
7023	if (path) {
7024		const char *name;
7025
7026		name = kstrdup(path, GFP_KERNEL);
7027		if (!name) {
7028			btrfs_free_device(dev);
7029			return ERR_PTR(-ENOMEM);
7030		}
7031		rcu_assign_pointer(dev->name, name);
7032	}
7033
7034	return dev;
7035}
7036
7037static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
7038					u64 devid, u8 *uuid, bool error)
7039{
7040	if (error)
7041		btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
7042			      devid, uuid);
7043	else
7044		btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
7045			      devid, uuid);
7046}
7047
7048u64 btrfs_calc_stripe_length(const struct btrfs_chunk_map *map)
7049{
7050	const int data_stripes = calc_data_stripes(map->type, map->num_stripes);
7051
7052	return div_u64(map->chunk_len, data_stripes);
7053}
7054
7055#if BITS_PER_LONG == 32
7056/*
7057 * Due to page cache limit, metadata beyond BTRFS_32BIT_MAX_FILE_SIZE
7058 * can't be accessed on 32bit systems.
7059 *
7060 * This function do mount time check to reject the fs if it already has
7061 * metadata chunk beyond that limit.
7062 */
7063static int check_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7064				  u64 logical, u64 length, u64 type)
7065{
7066	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7067		return 0;
7068
7069	if (logical + length < MAX_LFS_FILESIZE)
7070		return 0;
7071
7072	btrfs_err_32bit_limit(fs_info);
7073	return -EOVERFLOW;
7074}
7075
7076/*
7077 * This is to give early warning for any metadata chunk reaching
7078 * BTRFS_32BIT_EARLY_WARN_THRESHOLD.
7079 * Although we can still access the metadata, it's not going to be possible
7080 * once the limit is reached.
7081 */
7082static void warn_32bit_meta_chunk(struct btrfs_fs_info *fs_info,
7083				  u64 logical, u64 length, u64 type)
7084{
7085	if (!(type & BTRFS_BLOCK_GROUP_METADATA))
7086		return;
7087
7088	if (logical + length < BTRFS_32BIT_EARLY_WARN_THRESHOLD)
7089		return;
7090
7091	btrfs_warn_32bit_limit(fs_info);
7092}
7093#endif
7094
7095static struct btrfs_device *handle_missing_device(struct btrfs_fs_info *fs_info,
7096						  u64 devid, u8 *uuid)
7097{
7098	struct btrfs_device *dev;
7099
7100	if (!btrfs_test_opt(fs_info, DEGRADED)) {
7101		btrfs_report_missing_device(fs_info, devid, uuid, true);
7102		return ERR_PTR(-ENOENT);
7103	}
7104
7105	dev = add_missing_dev(fs_info->fs_devices, devid, uuid);
7106	if (IS_ERR(dev)) {
7107		btrfs_err(fs_info, "failed to init missing device %llu: %ld",
7108			  devid, PTR_ERR(dev));
7109		return dev;
7110	}
7111	btrfs_report_missing_device(fs_info, devid, uuid, false);
7112
7113	return dev;
7114}
7115
7116static int read_one_chunk(struct btrfs_key *key, struct extent_buffer *leaf,
7117			  struct btrfs_chunk *chunk)
7118{
7119	BTRFS_DEV_LOOKUP_ARGS(args);
7120	struct btrfs_fs_info *fs_info = leaf->fs_info;
7121	struct btrfs_chunk_map *map;
7122	u64 logical;
7123	u64 length;
7124	u64 devid;
7125	u64 type;
7126	u8 uuid[BTRFS_UUID_SIZE];
7127	int index;
7128	int num_stripes;
7129	int ret;
7130	int i;
7131
7132	logical = key->offset;
7133	length = btrfs_chunk_length(leaf, chunk);
7134	type = btrfs_chunk_type(leaf, chunk);
7135	index = btrfs_bg_flags_to_raid_index(type);
7136	num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
7137
7138#if BITS_PER_LONG == 32
7139	ret = check_32bit_meta_chunk(fs_info, logical, length, type);
7140	if (ret < 0)
7141		return ret;
7142	warn_32bit_meta_chunk(fs_info, logical, length, type);
7143#endif
7144
7145	map = btrfs_find_chunk_map(fs_info, logical, 1);
7146
7147	/* already mapped? */
7148	if (map && map->start <= logical && map->start + map->chunk_len > logical) {
7149		btrfs_free_chunk_map(map);
7150		return 0;
7151	} else if (map) {
7152		btrfs_free_chunk_map(map);
7153	}
7154
7155	map = btrfs_alloc_chunk_map(num_stripes, GFP_NOFS);
7156	if (!map)
7157		return -ENOMEM;
7158
7159	map->start = logical;
7160	map->chunk_len = length;
7161	map->num_stripes = num_stripes;
7162	map->io_width = btrfs_chunk_io_width(leaf, chunk);
7163	map->io_align = btrfs_chunk_io_align(leaf, chunk);
7164	map->type = type;
7165	/*
7166	 * We can't use the sub_stripes value, as for profiles other than
7167	 * RAID10, they may have 0 as sub_stripes for filesystems created by
7168	 * older mkfs (<v5.4).
7169	 * In that case, it can cause divide-by-zero errors later.
7170	 * Since currently sub_stripes is fixed for each profile, let's
7171	 * use the trusted value instead.
7172	 */
7173	map->sub_stripes = btrfs_raid_array[index].sub_stripes;
7174	map->verified_stripes = 0;
7175	map->stripe_size = btrfs_calc_stripe_length(map);
7176	for (i = 0; i < num_stripes; i++) {
7177		map->stripes[i].physical =
7178			btrfs_stripe_offset_nr(leaf, chunk, i);
7179		devid = btrfs_stripe_devid_nr(leaf, chunk, i);
7180		args.devid = devid;
7181		read_extent_buffer(leaf, uuid, (unsigned long)
7182				   btrfs_stripe_dev_uuid_nr(chunk, i),
7183				   BTRFS_UUID_SIZE);
7184		args.uuid = uuid;
7185		map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices, &args);
7186		if (!map->stripes[i].dev) {
7187			map->stripes[i].dev = handle_missing_device(fs_info,
7188								    devid, uuid);
7189			if (IS_ERR(map->stripes[i].dev)) {
7190				ret = PTR_ERR(map->stripes[i].dev);
7191				btrfs_free_chunk_map(map);
7192				return ret;
7193			}
7194		}
7195
7196		set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
7197				&(map->stripes[i].dev->dev_state));
7198	}
7199
7200	ret = btrfs_add_chunk_map(fs_info, map);
7201	if (ret < 0) {
7202		btrfs_err(fs_info,
7203			  "failed to add chunk map, start=%llu len=%llu: %d",
7204			  map->start, map->chunk_len, ret);
7205		btrfs_free_chunk_map(map);
7206	}
7207
7208	return ret;
7209}
7210
7211static void fill_device_from_item(struct extent_buffer *leaf,
7212				 struct btrfs_dev_item *dev_item,
7213				 struct btrfs_device *device)
7214{
7215	unsigned long ptr;
7216
7217	device->devid = btrfs_device_id(leaf, dev_item);
7218	device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
7219	device->total_bytes = device->disk_total_bytes;
7220	device->commit_total_bytes = device->disk_total_bytes;
7221	device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
7222	device->commit_bytes_used = device->bytes_used;
7223	device->type = btrfs_device_type(leaf, dev_item);
7224	device->io_align = btrfs_device_io_align(leaf, dev_item);
7225	device->io_width = btrfs_device_io_width(leaf, dev_item);
7226	device->sector_size = btrfs_device_sector_size(leaf, dev_item);
7227	WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
7228	clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
7229
7230	ptr = btrfs_device_uuid(dev_item);
7231	read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
7232}
7233
7234static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
7235						  u8 *fsid)
7236{
7237	struct btrfs_fs_devices *fs_devices;
7238	int ret;
7239
7240	lockdep_assert_held(&uuid_mutex);
7241	ASSERT(fsid);
7242
7243	/* This will match only for multi-device seed fs */
7244	list_for_each_entry(fs_devices, &fs_info->fs_devices->seed_list, seed_list)
7245		if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
7246			return fs_devices;
7247
7248
7249	fs_devices = find_fsid(fsid, NULL);
7250	if (!fs_devices) {
7251		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7252			btrfs_err(fs_info,
7253		"failed to find fsid %pU when attempting to open seed devices",
7254				  fsid);
7255			return ERR_PTR(-ENOENT);
7256		}
7257
7258		fs_devices = alloc_fs_devices(fsid);
7259		if (IS_ERR(fs_devices))
7260			return fs_devices;
7261
7262		fs_devices->seeding = true;
7263		fs_devices->opened = 1;
7264		list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7265		return fs_devices;
7266	}
7267
7268	/*
7269	 * Upon first call for a seed fs fsid, just create a private copy of the
7270	 * respective fs_devices and anchor it at fs_info->fs_devices->seed_list
7271	 */
7272	fs_devices = clone_fs_devices(fs_devices);
7273	if (IS_ERR(fs_devices))
7274		return fs_devices;
7275
7276	ret = open_fs_devices(fs_devices, BLK_OPEN_READ, fs_info->sb);
7277	if (ret) {
7278		free_fs_devices(fs_devices);
7279		return ERR_PTR(ret);
7280	}
7281
7282	if (!fs_devices->seeding) {
7283		close_fs_devices(fs_devices);
7284		free_fs_devices(fs_devices);
7285		return ERR_PTR(-EINVAL);
7286	}
7287
7288	list_add(&fs_devices->seed_list, &fs_info->fs_devices->seed_list);
7289
7290	return fs_devices;
7291}
7292
7293static int read_one_dev(struct extent_buffer *leaf,
7294			struct btrfs_dev_item *dev_item)
7295{
7296	BTRFS_DEV_LOOKUP_ARGS(args);
7297	struct btrfs_fs_info *fs_info = leaf->fs_info;
7298	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7299	struct btrfs_device *device;
7300	u64 devid;
7301	int ret;
7302	u8 fs_uuid[BTRFS_FSID_SIZE];
7303	u8 dev_uuid[BTRFS_UUID_SIZE];
7304
7305	devid = btrfs_device_id(leaf, dev_item);
7306	args.devid = devid;
7307	read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
7308			   BTRFS_UUID_SIZE);
7309	read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
7310			   BTRFS_FSID_SIZE);
7311	args.uuid = dev_uuid;
7312	args.fsid = fs_uuid;
7313
7314	if (memcmp(fs_uuid, fs_devices->metadata_uuid, BTRFS_FSID_SIZE)) {
7315		fs_devices = open_seed_devices(fs_info, fs_uuid);
7316		if (IS_ERR(fs_devices))
7317			return PTR_ERR(fs_devices);
7318	}
7319
7320	device = btrfs_find_device(fs_info->fs_devices, &args);
7321	if (!device) {
7322		if (!btrfs_test_opt(fs_info, DEGRADED)) {
7323			btrfs_report_missing_device(fs_info, devid,
7324							dev_uuid, true);
7325			return -ENOENT;
7326		}
7327
7328		device = add_missing_dev(fs_devices, devid, dev_uuid);
7329		if (IS_ERR(device)) {
7330			btrfs_err(fs_info,
7331				"failed to add missing dev %llu: %ld",
7332				devid, PTR_ERR(device));
7333			return PTR_ERR(device);
7334		}
7335		btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
7336	} else {
7337		if (!device->bdev) {
7338			if (!btrfs_test_opt(fs_info, DEGRADED)) {
7339				btrfs_report_missing_device(fs_info,
7340						devid, dev_uuid, true);
7341				return -ENOENT;
7342			}
7343			btrfs_report_missing_device(fs_info, devid,
7344							dev_uuid, false);
7345		}
7346
7347		if (!device->bdev &&
7348		    !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
7349			/*
7350			 * this happens when a device that was properly setup
7351			 * in the device info lists suddenly goes bad.
7352			 * device->bdev is NULL, and so we have to set
7353			 * device->missing to one here
7354			 */
7355			device->fs_devices->missing_devices++;
7356			set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
7357		}
7358
7359		/* Move the device to its own fs_devices */
7360		if (device->fs_devices != fs_devices) {
7361			ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
7362							&device->dev_state));
7363
7364			list_move(&device->dev_list, &fs_devices->devices);
7365			device->fs_devices->num_devices--;
7366			fs_devices->num_devices++;
7367
7368			device->fs_devices->missing_devices--;
7369			fs_devices->missing_devices++;
7370
7371			device->fs_devices = fs_devices;
7372		}
7373	}
7374
7375	if (device->fs_devices != fs_info->fs_devices) {
7376		BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
7377		if (device->generation !=
7378		    btrfs_device_generation(leaf, dev_item))
7379			return -EINVAL;
7380	}
7381
7382	fill_device_from_item(leaf, dev_item, device);
7383	if (device->bdev) {
7384		u64 max_total_bytes = bdev_nr_bytes(device->bdev);
7385
7386		if (device->total_bytes > max_total_bytes) {
7387			btrfs_err(fs_info,
7388			"device total_bytes should be at most %llu but found %llu",
7389				  max_total_bytes, device->total_bytes);
7390			return -EINVAL;
7391		}
7392	}
7393	set_bit(BTRFS_DEV_STATE_ITEM_FOUND, &device->dev_state);
7394	set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
7395	if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
7396	   !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
7397		device->fs_devices->total_rw_bytes += device->total_bytes;
7398		atomic64_add(device->total_bytes - device->bytes_used,
7399				&fs_info->free_chunk_space);
7400	}
7401	ret = 0;
7402	return ret;
7403}
7404
7405int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
7406{
7407	struct btrfs_super_block *super_copy = fs_info->super_copy;
7408	struct extent_buffer *sb;
7409	u8 *array_ptr;
7410	unsigned long sb_array_offset;
7411	int ret = 0;
7412	u32 array_size;
7413	u32 cur_offset;
7414	struct btrfs_key key;
7415
7416	ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
7417
7418	/*
7419	 * We allocated a dummy extent, just to use extent buffer accessors.
7420	 * There will be unused space after BTRFS_SUPER_INFO_SIZE, but
7421	 * that's fine, we will not go beyond system chunk array anyway.
7422	 */
7423	sb = alloc_dummy_extent_buffer(fs_info, BTRFS_SUPER_INFO_OFFSET);
7424	if (!sb)
7425		return -ENOMEM;
7426	set_extent_buffer_uptodate(sb);
7427
7428	write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
7429	array_size = btrfs_super_sys_array_size(super_copy);
7430
7431	array_ptr = super_copy->sys_chunk_array;
7432	sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
7433	cur_offset = 0;
7434
7435	while (cur_offset < array_size) {
7436		struct btrfs_chunk *chunk;
7437		struct btrfs_disk_key *disk_key = (struct btrfs_disk_key *)array_ptr;
7438		u32 len = sizeof(*disk_key);
7439
7440		/*
7441		 * The sys_chunk_array has been already verified at super block
7442		 * read time.  Only do ASSERT()s for basic checks.
7443		 */
7444		ASSERT(cur_offset + len <= array_size);
7445
7446		btrfs_disk_key_to_cpu(&key, disk_key);
7447
7448		array_ptr += len;
7449		sb_array_offset += len;
7450		cur_offset += len;
7451
7452		ASSERT(key.type == BTRFS_CHUNK_ITEM_KEY);
7453
7454		chunk = (struct btrfs_chunk *)sb_array_offset;
7455		ASSERT(btrfs_chunk_type(sb, chunk) & BTRFS_BLOCK_GROUP_SYSTEM);
7456
7457		len = btrfs_chunk_item_size(btrfs_chunk_num_stripes(sb, chunk));
7458
7459		ASSERT(cur_offset + len <= array_size);
7460
7461		ret = read_one_chunk(&key, sb, chunk);
7462		if (ret)
7463			break;
7464
7465		array_ptr += len;
7466		sb_array_offset += len;
7467		cur_offset += len;
7468	}
7469	clear_extent_buffer_uptodate(sb);
7470	free_extent_buffer_stale(sb);
7471	return ret;
7472}
7473
7474/*
7475 * Check if all chunks in the fs are OK for read-write degraded mount
7476 *
7477 * If the @failing_dev is specified, it's accounted as missing.
7478 *
7479 * Return true if all chunks meet the minimal RW mount requirements.
7480 * Return false if any chunk doesn't meet the minimal RW mount requirements.
7481 */
7482bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
7483					struct btrfs_device *failing_dev)
7484{
7485	struct btrfs_chunk_map *map;
7486	u64 next_start;
7487	bool ret = true;
7488
7489	map = btrfs_find_chunk_map(fs_info, 0, U64_MAX);
7490	/* No chunk at all? Return false anyway */
7491	if (!map) {
7492		ret = false;
7493		goto out;
7494	}
7495	while (map) {
7496		int missing = 0;
7497		int max_tolerated;
7498		int i;
7499
7500		max_tolerated =
7501			btrfs_get_num_tolerated_disk_barrier_failures(
7502					map->type);
7503		for (i = 0; i < map->num_stripes; i++) {
7504			struct btrfs_device *dev = map->stripes[i].dev;
7505
7506			if (!dev || !dev->bdev ||
7507			    test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
7508			    dev->last_flush_error)
7509				missing++;
7510			else if (failing_dev && failing_dev == dev)
7511				missing++;
7512		}
7513		if (missing > max_tolerated) {
7514			if (!failing_dev)
7515				btrfs_warn(fs_info,
7516	"chunk %llu missing %d devices, max tolerance is %d for writable mount",
7517				   map->start, missing, max_tolerated);
7518			btrfs_free_chunk_map(map);
7519			ret = false;
7520			goto out;
7521		}
7522		next_start = map->start + map->chunk_len;
7523		btrfs_free_chunk_map(map);
7524
7525		map = btrfs_find_chunk_map(fs_info, next_start, U64_MAX - next_start);
7526	}
7527out:
7528	return ret;
7529}
7530
7531static void readahead_tree_node_children(struct extent_buffer *node)
7532{
7533	int i;
7534	const int nr_items = btrfs_header_nritems(node);
7535
7536	for (i = 0; i < nr_items; i++)
7537		btrfs_readahead_node_child(node, i);
7538}
7539
7540int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
7541{
7542	struct btrfs_root *root = fs_info->chunk_root;
7543	BTRFS_PATH_AUTO_FREE(path);
7544	struct extent_buffer *leaf;
7545	struct btrfs_key key;
7546	struct btrfs_key found_key;
7547	int ret;
7548	int slot;
7549	int iter_ret = 0;
7550	u64 total_dev = 0;
7551	u64 last_ra_node = 0;
7552
7553	path = btrfs_alloc_path();
7554	if (!path)
7555		return -ENOMEM;
7556
7557	/*
7558	 * uuid_mutex is needed only if we are mounting a sprout FS
7559	 * otherwise we don't need it.
7560	 */
7561	mutex_lock(&uuid_mutex);
7562
7563	/*
7564	 * It is possible for mount and umount to race in such a way that
7565	 * we execute this code path, but open_fs_devices failed to clear
7566	 * total_rw_bytes. We certainly want it cleared before reading the
7567	 * device items, so clear it here.
7568	 */
7569	fs_info->fs_devices->total_rw_bytes = 0;
7570
7571	/*
7572	 * Lockdep complains about possible circular locking dependency between
7573	 * a disk's open_mutex (struct gendisk.open_mutex), the rw semaphores
7574	 * used for freeze protection of a fs (struct super_block.s_writers),
7575	 * which we take when starting a transaction, and extent buffers of the
7576	 * chunk tree if we call read_one_dev() while holding a lock on an
7577	 * extent buffer of the chunk tree. Since we are mounting the filesystem
7578	 * and at this point there can't be any concurrent task modifying the
7579	 * chunk tree, to keep it simple, just skip locking on the chunk tree.
7580	 */
7581	ASSERT(!test_bit(BTRFS_FS_OPEN, &fs_info->flags));
7582	path->skip_locking = true;
7583
7584	/*
7585	 * Read all device items, and then all the chunk items. All
7586	 * device items are found before any chunk item (their object id
7587	 * is smaller than the lowest possible object id for a chunk
7588	 * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
7589	 */
7590	key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
7591	key.type = 0;
7592	key.offset = 0;
7593	btrfs_for_each_slot(root, &key, &found_key, path, iter_ret) {
7594		struct extent_buffer *node = path->nodes[1];
7595
7596		leaf = path->nodes[0];
7597		slot = path->slots[0];
7598
7599		if (node) {
7600			if (last_ra_node != node->start) {
7601				readahead_tree_node_children(node);
7602				last_ra_node = node->start;
7603			}
7604		}
7605		if (found_key.type == BTRFS_DEV_ITEM_KEY) {
7606			struct btrfs_dev_item *dev_item;
7607			dev_item = btrfs_item_ptr(leaf, slot,
7608						  struct btrfs_dev_item);
7609			ret = read_one_dev(leaf, dev_item);
7610			if (ret)
7611				goto error;
7612			total_dev++;
7613		} else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
7614			struct btrfs_chunk *chunk;
7615
7616			/*
7617			 * We are only called at mount time, so no need to take
7618			 * fs_info->chunk_mutex. Plus, to avoid lockdep warnings,
7619			 * we always lock first fs_info->chunk_mutex before
7620			 * acquiring any locks on the chunk tree. This is a
7621			 * requirement for chunk allocation, see the comment on
7622			 * top of btrfs_chunk_alloc() for details.
7623			 */
7624			chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
7625			ret = read_one_chunk(&found_key, leaf, chunk);
7626			if (ret)
7627				goto error;
7628		}
7629	}
7630	/* Catch error found during iteration */
7631	if (iter_ret < 0) {
7632		ret = iter_ret;
7633		goto error;
7634	}
7635
7636	/*
7637	 * After loading chunk tree, we've got all device information,
7638	 * do another round of validation checks.
7639	 */
7640	if (total_dev != fs_info->fs_devices->total_devices) {
7641		btrfs_warn(fs_info,
7642"super block num_devices %llu mismatch with DEV_ITEM count %llu, will be repaired on next transaction commit",
7643			  btrfs_super_num_devices(fs_info->super_copy),
7644			  total_dev);
7645		fs_info->fs_devices->total_devices = total_dev;
7646		btrfs_set_super_num_devices(fs_info->super_copy, total_dev);
7647	}
7648	if (btrfs_super_total_bytes(fs_info->super_copy) <
7649	    fs_info->fs_devices->total_rw_bytes) {
7650		btrfs_err(fs_info,
7651	"super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
7652			  btrfs_super_total_bytes(fs_info->super_copy),
7653			  fs_info->fs_devices->total_rw_bytes);
7654		ret = -EINVAL;
7655		goto error;
7656	}
7657	ret = 0;
7658error:
7659	mutex_unlock(&uuid_mutex);
7660	return ret;
7661}
7662
7663int btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
7664{
7665	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7666	struct btrfs_device *device;
7667	int ret = 0;
7668
7669	mutex_lock(&fs_devices->device_list_mutex);
7670	list_for_each_entry(device, &fs_devices->devices, dev_list)
7671		device->fs_info = fs_info;
7672
7673	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7674		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7675			device->fs_info = fs_info;
7676			ret = btrfs_get_dev_zone_info(device, false);
7677			if (ret)
7678				break;
7679		}
7680
7681		seed_devs->fs_info = fs_info;
7682	}
7683	mutex_unlock(&fs_devices->device_list_mutex);
7684
7685	return ret;
7686}
7687
7688static u64 btrfs_dev_stats_value(const struct extent_buffer *eb,
7689				 const struct btrfs_dev_stats_item *ptr,
7690				 int index)
7691{
7692	u64 val;
7693
7694	read_extent_buffer(eb, &val,
7695			   offsetof(struct btrfs_dev_stats_item, values) +
7696			    ((unsigned long)ptr) + (index * sizeof(u64)),
7697			   sizeof(val));
7698	return val;
7699}
7700
7701static void btrfs_set_dev_stats_value(struct extent_buffer *eb,
7702				      struct btrfs_dev_stats_item *ptr,
7703				      int index, u64 val)
7704{
7705	write_extent_buffer(eb, &val,
7706			    offsetof(struct btrfs_dev_stats_item, values) +
7707			     ((unsigned long)ptr) + (index * sizeof(u64)),
7708			    sizeof(val));
7709}
7710
7711static int btrfs_device_init_dev_stats(struct btrfs_device *device,
7712				       struct btrfs_path *path)
7713{
7714	struct btrfs_dev_stats_item *ptr;
7715	struct extent_buffer *eb;
7716	struct btrfs_key key;
7717	int item_size;
7718	int i, ret, slot;
7719
7720	if (!device->fs_info->dev_root)
7721		return 0;
7722
7723	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7724	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7725	key.offset = device->devid;
7726	ret = btrfs_search_slot(NULL, device->fs_info->dev_root, &key, path, 0, 0);
7727	if (ret) {
7728		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7729			btrfs_dev_stat_set(device, i, 0);
7730		device->dev_stats_valid = 1;
7731		btrfs_release_path(path);
7732		return ret < 0 ? ret : 0;
7733	}
7734	slot = path->slots[0];
7735	eb = path->nodes[0];
7736	item_size = btrfs_item_size(eb, slot);
7737
7738	ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_stats_item);
7739
7740	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7741		if (item_size >= (1 + i) * sizeof(__le64))
7742			btrfs_dev_stat_set(device, i,
7743					   btrfs_dev_stats_value(eb, ptr, i));
7744		else
7745			btrfs_dev_stat_set(device, i, 0);
7746	}
7747
7748	device->dev_stats_valid = 1;
7749	btrfs_dev_stat_print_on_load(device);
7750	btrfs_release_path(path);
7751
7752	return 0;
7753}
7754
7755int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
7756{
7757	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
7758	struct btrfs_device *device;
7759	BTRFS_PATH_AUTO_FREE(path);
7760	int ret = 0;
7761
7762	path = btrfs_alloc_path();
7763	if (!path)
7764		return -ENOMEM;
7765
7766	mutex_lock(&fs_devices->device_list_mutex);
7767	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7768		ret = btrfs_device_init_dev_stats(device, path);
7769		if (ret)
7770			goto out;
7771	}
7772	list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list) {
7773		list_for_each_entry(device, &seed_devs->devices, dev_list) {
7774			ret = btrfs_device_init_dev_stats(device, path);
7775			if (ret)
7776				goto out;
7777		}
7778	}
7779out:
7780	mutex_unlock(&fs_devices->device_list_mutex);
7781	return ret;
7782}
7783
7784static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7785				struct btrfs_device *device)
7786{
7787	struct btrfs_fs_info *fs_info = trans->fs_info;
7788	struct btrfs_root *dev_root = fs_info->dev_root;
7789	BTRFS_PATH_AUTO_FREE(path);
7790	struct btrfs_key key;
7791	struct extent_buffer *eb;
7792	struct btrfs_dev_stats_item *ptr;
7793	int ret;
7794	int i;
7795
7796	key.objectid = BTRFS_DEV_STATS_OBJECTID;
7797	key.type = BTRFS_PERSISTENT_ITEM_KEY;
7798	key.offset = device->devid;
7799
7800	path = btrfs_alloc_path();
7801	if (!path)
7802		return -ENOMEM;
7803	ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7804	if (ret < 0) {
7805		btrfs_warn(fs_info,
7806			"error %d while searching for dev_stats item for device %s",
7807				  ret, btrfs_dev_name(device));
7808		return ret;
7809	}
7810
7811	if (ret == 0 &&
7812	    btrfs_item_size(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7813		/* need to delete old one and insert a new one */
7814		ret = btrfs_del_item(trans, dev_root, path);
7815		if (ret != 0) {
7816			btrfs_warn(fs_info,
7817				"delete too small dev_stats item for device %s failed %d",
7818					  btrfs_dev_name(device), ret);
7819			return ret;
7820		}
7821		ret = 1;
7822	}
7823
7824	if (ret == 1) {
7825		/* need to insert a new item */
7826		btrfs_release_path(path);
7827		ret = btrfs_insert_empty_item(trans, dev_root, path,
7828					      &key, sizeof(*ptr));
7829		if (ret < 0) {
7830			btrfs_warn(fs_info,
7831				"insert dev_stats item for device %s failed %d",
7832				btrfs_dev_name(device), ret);
7833			return ret;
7834		}
7835	}
7836
7837	eb = path->nodes[0];
7838	ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7839	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7840		btrfs_set_dev_stats_value(eb, ptr, i,
7841					  btrfs_dev_stat_read(device, i));
7842	return ret;
7843}
7844
7845/*
7846 * called from commit_transaction. Writes all changed device stats to disk.
7847 */
7848int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
7849{
7850	struct btrfs_fs_info *fs_info = trans->fs_info;
7851	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7852	struct btrfs_device *device;
7853	int stats_cnt;
7854	int ret = 0;
7855
7856	mutex_lock(&fs_devices->device_list_mutex);
7857	list_for_each_entry(device, &fs_devices->devices, dev_list) {
7858		stats_cnt = atomic_read(&device->dev_stats_ccnt);
7859		if (!device->dev_stats_valid || stats_cnt == 0)
7860			continue;
7861
7862
7863		/*
7864		 * There is a LOAD-LOAD control dependency between the value of
7865		 * dev_stats_ccnt and updating the on-disk values which requires
7866		 * reading the in-memory counters. Such control dependencies
7867		 * require explicit read memory barriers.
7868		 *
7869		 * This memory barriers pairs with smp_mb__before_atomic in
7870		 * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7871		 * barrier implied by atomic_xchg in
7872		 * btrfs_dev_stats_read_and_reset
7873		 */
7874		smp_rmb();
7875
7876		ret = update_dev_stat_item(trans, device);
7877		if (ret)
7878			break;
7879		atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7880	}
7881	mutex_unlock(&fs_devices->device_list_mutex);
7882
7883	return ret;
7884}
7885
7886void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7887{
7888	btrfs_dev_stat_inc(dev, index);
7889
7890	if (!dev->dev_stats_valid)
7891		return;
7892	btrfs_err_rl(dev->fs_info,
7893		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7894			   btrfs_dev_name(dev),
7895			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7896			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7897			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7898			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7899			   btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7900}
7901
7902static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7903{
7904	int i;
7905
7906	for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7907		if (btrfs_dev_stat_read(dev, i) != 0)
7908			break;
7909	if (i == BTRFS_DEV_STAT_VALUES_MAX)
7910		return; /* all values == 0, suppress message */
7911
7912	btrfs_info(dev->fs_info,
7913		"bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7914	       btrfs_dev_name(dev),
7915	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7916	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7917	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7918	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7919	       btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7920}
7921
7922int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7923			struct btrfs_ioctl_get_dev_stats *stats)
7924{
7925	BTRFS_DEV_LOOKUP_ARGS(args);
7926	struct btrfs_device *dev;
7927	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7928	int i;
7929
7930	mutex_lock(&fs_devices->device_list_mutex);
7931	args.devid = stats->devid;
7932	dev = btrfs_find_device(fs_info->fs_devices, &args);
7933	mutex_unlock(&fs_devices->device_list_mutex);
7934
7935	if (!dev) {
7936		btrfs_warn(fs_info, "get dev_stats failed, device not found");
7937		return -ENODEV;
7938	} else if (!dev->dev_stats_valid) {
7939		btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7940		return -ENODEV;
7941	} else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7942		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7943			if (stats->nr_items > i)
7944				stats->values[i] =
7945					btrfs_dev_stat_read_and_reset(dev, i);
7946			else
7947				btrfs_dev_stat_set(dev, i, 0);
7948		}
7949		btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7950			   current->comm, task_pid_nr(current));
7951	} else {
7952		for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7953			if (stats->nr_items > i)
7954				stats->values[i] = btrfs_dev_stat_read(dev, i);
7955	}
7956	if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7957		stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7958	return 0;
7959}
7960
7961/*
7962 * Update the size and bytes used for each device where it changed.  This is
7963 * delayed since we would otherwise get errors while writing out the
7964 * superblocks.
7965 *
7966 * Must be invoked during transaction commit.
7967 */
7968void btrfs_commit_device_sizes(struct btrfs_transaction *trans)
7969{
7970	struct btrfs_device *curr, *next;
7971
7972	ASSERT(trans->state == TRANS_STATE_COMMIT_DOING, "state=%d" , trans->state);
7973
7974	if (list_empty(&trans->dev_update_list))
7975		return;
7976
7977	/*
7978	 * We don't need the device_list_mutex here.  This list is owned by the
7979	 * transaction and the transaction must complete before the device is
7980	 * released.
7981	 */
7982	mutex_lock(&trans->fs_info->chunk_mutex);
7983	list_for_each_entry_safe(curr, next, &trans->dev_update_list,
7984				 post_commit_list) {
7985		list_del_init(&curr->post_commit_list);
7986		curr->commit_total_bytes = curr->disk_total_bytes;
7987		curr->commit_bytes_used = curr->bytes_used;
7988	}
7989	mutex_unlock(&trans->fs_info->chunk_mutex);
7990}
7991
7992/*
7993 * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7994 */
7995int btrfs_bg_type_to_factor(u64 flags)
7996{
7997	const int index = btrfs_bg_flags_to_raid_index(flags);
7998
7999	return btrfs_raid_array[index].ncopies;
8000}
8001
8002static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
8003				 u64 chunk_offset, u64 devid,
8004				 u64 physical_offset, u64 physical_len)
8005{
8006	struct btrfs_dev_lookup_args args = { .devid = devid };
8007	struct btrfs_chunk_map *map;
8008	struct btrfs_device *dev;
8009	u64 stripe_len;
8010	bool found = false;
8011	int ret = 0;
8012	int i;
8013
8014	map = btrfs_find_chunk_map(fs_info, chunk_offset, 1);
8015	if (unlikely(!map)) {
8016		btrfs_err(fs_info,
8017"dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
8018			  physical_offset, devid);
8019		ret = -EUCLEAN;
8020		goto out;
8021	}
8022
8023	stripe_len = btrfs_calc_stripe_length(map);
8024	if (unlikely(physical_len != stripe_len)) {
8025		btrfs_err(fs_info,
8026"dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
8027			  physical_offset, devid, map->start, physical_len,
8028			  stripe_len);
8029		ret = -EUCLEAN;
8030		goto out;
8031	}
8032
8033	/*
8034	 * Very old mkfs.btrfs (before v4.15) will not respect the reserved
8035	 * space. Although kernel can handle it without problem, better to warn
8036	 * the users.
8037	 */
8038	if (physical_offset < BTRFS_DEVICE_RANGE_RESERVED)
8039		btrfs_warn(fs_info,
8040		"devid %llu physical %llu len %llu inside the reserved space",
8041			   devid, physical_offset, physical_len);
8042
8043	for (i = 0; i < map->num_stripes; i++) {
8044		if (unlikely(map->stripes[i].dev->devid == devid &&
8045			     map->stripes[i].physical == physical_offset)) {
8046			found = true;
8047			if (map->verified_stripes >= map->num_stripes) {
8048				btrfs_err(fs_info,
8049				"too many dev extents for chunk %llu found",
8050					  map->start);
8051				ret = -EUCLEAN;
8052				goto out;
8053			}
8054			map->verified_stripes++;
8055			break;
8056		}
8057	}
8058	if (unlikely(!found)) {
8059		btrfs_err(fs_info,
8060	"dev extent physical offset %llu devid %llu has no corresponding chunk",
8061			physical_offset, devid);
8062		ret = -EUCLEAN;
8063	}
8064
8065	/* Make sure no dev extent is beyond device boundary */
8066	dev = btrfs_find_device(fs_info->fs_devices, &args);
8067	if (unlikely(!dev)) {
8068		btrfs_err(fs_info, "failed to find devid %llu", devid);
8069		ret = -EUCLEAN;
8070		goto out;
8071	}
8072
8073	if (unlikely(physical_offset + physical_len > dev->disk_total_bytes)) {
8074		btrfs_err(fs_info,
8075"dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
8076			  devid, physical_offset, physical_len,
8077			  dev->disk_total_bytes);
8078		ret = -EUCLEAN;
8079		goto out;
8080	}
8081
8082	if (dev->zone_info) {
8083		u64 zone_size = dev->zone_info->zone_size;
8084
8085		if (unlikely(!IS_ALIGNED(physical_offset, zone_size) ||
8086			     !IS_ALIGNED(physical_len, zone_size))) {
8087			btrfs_err(fs_info,
8088"zoned: dev extent devid %llu physical offset %llu len %llu is not aligned to device zone",
8089				  devid, physical_offset, physical_len);
8090			ret = -EUCLEAN;
8091			goto out;
8092		}
8093	}
8094
8095out:
8096	btrfs_free_chunk_map(map);
8097	return ret;
8098}
8099
8100static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
8101{
8102	struct rb_node *node;
8103	int ret = 0;
8104
8105	read_lock(&fs_info->mapping_tree_lock);
8106	for (node = rb_first_cached(&fs_info->mapping_tree); node; node = rb_next(node)) {
8107		struct btrfs_chunk_map *map;
8108
8109		map = rb_entry(node, struct btrfs_chunk_map, rb_node);
8110		if (unlikely(map->num_stripes != map->verified_stripes)) {
8111			btrfs_err(fs_info,
8112			"chunk %llu has missing dev extent, have %d expect %d",
8113				  map->start, map->verified_stripes, map->num_stripes);
8114			ret = -EUCLEAN;
8115			goto out;
8116		}
8117	}
8118out:
8119	read_unlock(&fs_info->mapping_tree_lock);
8120	return ret;
8121}
8122
8123/*
8124 * Ensure that all dev extents are mapped to correct chunk, otherwise
8125 * later chunk allocation/free would cause unexpected behavior.
8126 *
8127 * NOTE: This will iterate through the whole device tree, which should be of
8128 * the same size level as the chunk tree.  This slightly increases mount time.
8129 */
8130int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
8131{
8132	BTRFS_PATH_AUTO_FREE(path);
8133	struct btrfs_root *root = fs_info->dev_root;
8134	struct btrfs_key key;
8135	u64 prev_devid = 0;
8136	u64 prev_dev_ext_end = 0;
8137	int ret = 0;
8138
8139	/*
8140	 * We don't have a dev_root because we mounted with ignorebadroots and
8141	 * failed to load the root, so we want to skip the verification in this
8142	 * case for sure.
8143	 *
8144	 * However if the dev root is fine, but the tree itself is corrupted
8145	 * we'd still fail to mount.  This verification is only to make sure
8146	 * writes can happen safely, so instead just bypass this check
8147	 * completely in the case of IGNOREBADROOTS.
8148	 */
8149	if (btrfs_test_opt(fs_info, IGNOREBADROOTS))
8150		return 0;
8151
8152	key.objectid = 1;
8153	key.type = BTRFS_DEV_EXTENT_KEY;
8154	key.offset = 0;
8155
8156	path = btrfs_alloc_path();
8157	if (!path)
8158		return -ENOMEM;
8159
8160	path->reada = READA_FORWARD;
8161	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8162	if (ret < 0)
8163		return ret;
8164
8165	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
8166		ret = btrfs_next_leaf(root, path);
8167		if (ret < 0)
8168			return ret;
8169		/* No dev extents at all? Not good */
8170		if (unlikely(ret > 0))
8171			return -EUCLEAN;
8172	}
8173	while (1) {
8174		struct extent_buffer *leaf = path->nodes[0];
8175		struct btrfs_dev_extent *dext;
8176		int slot = path->slots[0];
8177		u64 chunk_offset;
8178		u64 physical_offset;
8179		u64 physical_len;
8180		u64 devid;
8181
8182		btrfs_item_key_to_cpu(leaf, &key, slot);
8183		if (key.type != BTRFS_DEV_EXTENT_KEY)
8184			break;
8185		devid = key.objectid;
8186		physical_offset = key.offset;
8187
8188		dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
8189		chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
8190		physical_len = btrfs_dev_extent_length(leaf, dext);
8191
8192		/* Check if this dev extent overlaps with the previous one */
8193		if (unlikely(devid == prev_devid && physical_offset < prev_dev_ext_end)) {
8194			btrfs_err(fs_info,
8195"dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
8196				  devid, physical_offset, prev_dev_ext_end);
8197			return -EUCLEAN;
8198		}
8199
8200		ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
8201					    physical_offset, physical_len);
8202		if (ret < 0)
8203			return ret;
8204		prev_devid = devid;
8205		prev_dev_ext_end = physical_offset + physical_len;
8206
8207		ret = btrfs_next_item(root, path);
8208		if (ret < 0)
8209			return ret;
8210		if (ret > 0) {
8211			ret = 0;
8212			break;
8213		}
8214	}
8215
8216	/* Ensure all chunks have corresponding dev extents */
8217	return verify_chunk_dev_extent_mapping(fs_info);
8218}
8219
8220/*
8221 * Ensure that all devices registered in the fs have their device items in the
8222 * chunk tree.
8223 *
8224 * Return true if unexpected device is found.
8225 * Return false otherwise.
8226 */
8227bool btrfs_verify_dev_items(const struct btrfs_fs_info *fs_info)
8228{
8229	struct btrfs_fs_devices *seed_devs;
8230	struct btrfs_device *dev;
8231	bool ret = false;
8232
8233	mutex_lock(&uuid_mutex);
8234	list_for_each_entry(dev, &fs_info->fs_devices->devices, dev_list) {
8235		if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8236			btrfs_err(fs_info,
8237			"devid %llu path %s is registered but not found in chunk tree",
8238				  dev->devid, btrfs_dev_name(dev));
8239			ret = true;
8240		}
8241	}
8242	list_for_each_entry(seed_devs, &fs_info->fs_devices->seed_list, seed_list) {
8243		list_for_each_entry(dev, &seed_devs->devices, dev_list) {
8244			if (!test_bit(BTRFS_DEV_STATE_ITEM_FOUND, &dev->dev_state)) {
8245				btrfs_err(fs_info,
8246			"devid %llu path %s is registered but not found in chunk tree",
8247					  dev->devid, btrfs_dev_name(dev));
8248				ret = true;
8249			}
8250		}
8251	}
8252	mutex_unlock(&uuid_mutex);
8253	if (ret)
8254		btrfs_err(fs_info,
8255"remove the above devices or use 'btrfs device scan --forget <dev>' to unregister them before mount");
8256	return ret;
8257}
8258
8259/*
8260 * Check whether the given block group or device is pinned by any inode being
8261 * used as a swapfile.
8262 */
8263bool btrfs_pinned_by_swapfile(struct btrfs_fs_info *fs_info, void *ptr)
8264{
8265	struct btrfs_swapfile_pin *sp;
8266	struct rb_node *node;
8267
8268	spin_lock(&fs_info->swapfile_pins_lock);
8269	node = fs_info->swapfile_pins.rb_node;
8270	while (node) {
8271		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
8272		if (ptr < sp->ptr)
8273			node = node->rb_left;
8274		else if (ptr > sp->ptr)
8275			node = node->rb_right;
8276		else
8277			break;
8278	}
8279	spin_unlock(&fs_info->swapfile_pins_lock);
8280	return node != NULL;
8281}
8282
8283static int relocating_repair_kthread(void *data)
8284{
8285	struct btrfs_block_group *cache = data;
8286	struct btrfs_fs_info *fs_info = cache->fs_info;
8287	u64 target;
8288	int ret = 0;
8289
8290	target = cache->start;
8291	btrfs_put_block_group(cache);
8292
8293	guard(super_write)(fs_info->sb);
8294
8295	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
8296		btrfs_info(fs_info,
8297			   "zoned: skip relocating block group %llu to repair: EBUSY",
8298			   target);
8299		return -EBUSY;
8300	}
8301
8302	mutex_lock(&fs_info->reclaim_bgs_lock);
8303
8304	/* Ensure block group still exists */
8305	cache = btrfs_lookup_block_group(fs_info, target);
8306	if (!cache)
8307		goto out;
8308
8309	if (!test_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags))
8310		goto out;
8311
8312	ret = btrfs_may_alloc_data_chunk(fs_info, target);
8313	if (ret < 0)
8314		goto out;
8315
8316	btrfs_info(fs_info,
8317		   "zoned: relocating block group %llu to repair IO failure",
8318		   target);
8319	ret = btrfs_relocate_chunk(fs_info, target, true);
8320
8321out:
8322	if (cache)
8323		btrfs_put_block_group(cache);
8324	mutex_unlock(&fs_info->reclaim_bgs_lock);
8325	btrfs_exclop_finish(fs_info);
8326
8327	return ret;
8328}
8329
8330bool btrfs_repair_one_zone(struct btrfs_fs_info *fs_info, u64 logical)
8331{
8332	struct btrfs_block_group *cache;
8333
8334	if (!btrfs_is_zoned(fs_info))
8335		return false;
8336
8337	/* Do not attempt to repair in degraded state */
8338	if (btrfs_test_opt(fs_info, DEGRADED))
8339		return true;
8340
8341	cache = btrfs_lookup_block_group(fs_info, logical);
8342	if (!cache)
8343		return true;
8344
8345	if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOCATING_REPAIR, &cache->runtime_flags)) {
8346		btrfs_put_block_group(cache);
8347		return true;
8348	}
8349
8350	kthread_run(relocating_repair_kthread, cache,
8351		    "btrfs-relocating-repair");
8352
8353	return true;
8354}
8355
8356static void map_raid56_repair_block(struct btrfs_io_context *bioc,
8357				    struct btrfs_io_stripe *smap,
8358				    u64 logical)
8359{
8360	int data_stripes = nr_bioc_data_stripes(bioc);
8361	int i;
8362
8363	for (i = 0; i < data_stripes; i++) {
8364		u64 stripe_start = bioc->full_stripe_logical +
8365				   btrfs_stripe_nr_to_offset(i);
8366
8367		if (logical >= stripe_start &&
8368		    logical < stripe_start + BTRFS_STRIPE_LEN)
8369			break;
8370	}
8371	ASSERT(i < data_stripes, "i=%d data_stripes=%d", i, data_stripes);
8372	smap->dev = bioc->stripes[i].dev;
8373	smap->physical = bioc->stripes[i].physical +
8374			((logical - bioc->full_stripe_logical) &
8375			 BTRFS_STRIPE_LEN_MASK);
8376}
8377
8378/*
8379 * Map a repair write into a single device.
8380 *
8381 * A repair write is triggered by read time repair or scrub, which would only
8382 * update the contents of a single device.
8383 * Not update any other mirrors nor go through RMW path.
8384 *
8385 * Callers should ensure:
8386 *
8387 * - Call btrfs_bio_counter_inc_blocked() first
8388 * - The range does not cross stripe boundary
8389 * - Has a valid @mirror_num passed in.
8390 */
8391int btrfs_map_repair_block(struct btrfs_fs_info *fs_info,
8392			   struct btrfs_io_stripe *smap, u64 logical,
8393			   u32 length, int mirror_num)
8394{
8395	struct btrfs_io_context *bioc = NULL;
8396	u64 map_length = length;
8397	int mirror_ret = mirror_num;
8398	int ret;
8399
8400	ASSERT(mirror_num > 0, "mirror_num=%d", mirror_num);
8401
8402	ret = btrfs_map_block(fs_info, BTRFS_MAP_WRITE, logical, &map_length,
8403			      &bioc, smap, &mirror_ret);
8404	if (ret < 0)
8405		return ret;
8406
8407	/* The map range should not cross stripe boundary. */
8408	ASSERT(map_length >= length, "map_length=%llu length=%u", map_length, length);
8409
8410	/* Already mapped to single stripe. */
8411	if (!bioc)
8412		goto out;
8413
8414	/* Map the RAID56 multi-stripe writes to a single one. */
8415	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
8416		map_raid56_repair_block(bioc, smap, logical);
8417		goto out;
8418	}
8419
8420	ASSERT(mirror_num <= bioc->num_stripes,
8421	       "mirror_num=%d num_stripes=%d", mirror_num,  bioc->num_stripes);
8422	smap->dev = bioc->stripes[mirror_num - 1].dev;
8423	smap->physical = bioc->stripes[mirror_num - 1].physical;
8424out:
8425	btrfs_put_bioc(bioc);
8426	ASSERT(smap->dev);
8427	return 0;
8428}
~/ Read-only file preview.