File Index
Files and directories
Sign in
FILE

zoned.c

File preview with syntax highlighting.

linux-6.19.14/fs/btrfs/zoned.c C
   1// SPDX-License-Identifier: GPL-2.0
   2
   3#include <linux/bitops.h>
   4#include <linux/slab.h>
   5#include <linux/blkdev.h>
   6#include <linux/sched/mm.h>
   7#include <linux/atomic.h>
   8#include <linux/vmalloc.h>
   9#include "ctree.h"
  10#include "volumes.h"
  11#include "zoned.h"
  12#include "disk-io.h"
  13#include "block-group.h"
  14#include "dev-replace.h"
  15#include "space-info.h"
  16#include "fs.h"
  17#include "accessors.h"
  18#include "bio.h"
  19#include "transaction.h"
  20#include "sysfs.h"
  21
  22/* Maximum number of zones to report per blkdev_report_zones() call */
  23#define BTRFS_REPORT_NR_ZONES   4096
  24/* Invalid allocation pointer value for missing devices */
  25#define WP_MISSING_DEV ((u64)-1)
  26/* Pseudo write pointer value for conventional zone */
  27#define WP_CONVENTIONAL ((u64)-2)
  28
  29/*
  30 * Location of the first zone of superblock logging zone pairs.
  31 *
  32 * - primary superblock:    0B (zone 0)
  33 * - first copy:          512G (zone starting at that offset)
  34 * - second copy:           4T (zone starting at that offset)
  35 */
  36#define BTRFS_SB_LOG_PRIMARY_OFFSET	(0ULL)
  37#define BTRFS_SB_LOG_FIRST_OFFSET	(512ULL * SZ_1G)
  38#define BTRFS_SB_LOG_SECOND_OFFSET	(4096ULL * SZ_1G)
  39
  40#define BTRFS_SB_LOG_FIRST_SHIFT	ilog2(BTRFS_SB_LOG_FIRST_OFFSET)
  41#define BTRFS_SB_LOG_SECOND_SHIFT	ilog2(BTRFS_SB_LOG_SECOND_OFFSET)
  42
  43/* Number of superblock log zones */
  44#define BTRFS_NR_SB_LOG_ZONES 2
  45
  46/* Default number of max active zones when the device has no limits. */
  47#define BTRFS_DEFAULT_MAX_ACTIVE_ZONES	128
  48
  49/*
  50 * Minimum of active zones we need:
  51 *
  52 * - BTRFS_SUPER_MIRROR_MAX zones for superblock mirrors
  53 * - 3 zones to ensure at least one zone per SYSTEM, META and DATA block group
  54 * - 1 zone for tree-log dedicated block group
  55 * - 1 zone for relocation
  56 */
  57#define BTRFS_MIN_ACTIVE_ZONES		(BTRFS_SUPER_MIRROR_MAX + 5)
  58
  59/*
  60 * Minimum / maximum supported zone size. Currently, SMR disks have a zone
  61 * size of 256MiB, and we are expecting ZNS drives to be in the 1-4GiB range.
  62 * We do not expect the zone size to become larger than 8GiB or smaller than
  63 * 4MiB in the near future.
  64 */
  65#define BTRFS_MAX_ZONE_SIZE		SZ_8G
  66#define BTRFS_MIN_ZONE_SIZE		SZ_4M
  67
  68#define SUPER_INFO_SECTORS	((u64)BTRFS_SUPER_INFO_SIZE >> SECTOR_SHIFT)
  69
  70static void wait_eb_writebacks(struct btrfs_block_group *block_group);
  71static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_written);
  72
  73static inline bool sb_zone_is_full(const struct blk_zone *zone)
  74{
  75	return (zone->cond == BLK_ZONE_COND_FULL) ||
  76		(zone->wp + SUPER_INFO_SECTORS > zone->start + zone->capacity);
  77}
  78
  79static int copy_zone_info_cb(struct blk_zone *zone, unsigned int idx, void *data)
  80{
  81	struct blk_zone *zones = data;
  82
  83	memcpy(&zones[idx], zone, sizeof(*zone));
  84
  85	return 0;
  86}
  87
  88static int sb_write_pointer(struct block_device *bdev, struct blk_zone *zones,
  89			    u64 *wp_ret)
  90{
  91	bool empty[BTRFS_NR_SB_LOG_ZONES];
  92	bool full[BTRFS_NR_SB_LOG_ZONES];
  93	sector_t sector;
  94
  95	for (int i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
  96		ASSERT(zones[i].type != BLK_ZONE_TYPE_CONVENTIONAL,
  97		       "zones[%d].type=%d", i, zones[i].type);
  98		empty[i] = (zones[i].cond == BLK_ZONE_COND_EMPTY);
  99		full[i] = sb_zone_is_full(&zones[i]);
 100	}
 101
 102	/*
 103	 * Possible states of log buffer zones
 104	 *
 105	 *           Empty[0]  In use[0]  Full[0]
 106	 * Empty[1]         *          0        1
 107	 * In use[1]        x          x        1
 108	 * Full[1]          0          0        C
 109	 *
 110	 * Log position:
 111	 *   *: Special case, no superblock is written
 112	 *   0: Use write pointer of zones[0]
 113	 *   1: Use write pointer of zones[1]
 114	 *   C: Compare super blocks from zones[0] and zones[1], use the latest
 115	 *      one determined by generation
 116	 *   x: Invalid state
 117	 */
 118
 119	if (empty[0] && empty[1]) {
 120		/* Special case to distinguish no superblock to read */
 121		*wp_ret = zones[0].start << SECTOR_SHIFT;
 122		return -ENOENT;
 123	} else if (full[0] && full[1]) {
 124		/* Compare two super blocks */
 125		struct address_space *mapping = bdev->bd_mapping;
 126		struct page *page[BTRFS_NR_SB_LOG_ZONES];
 127		struct btrfs_super_block *super[BTRFS_NR_SB_LOG_ZONES];
 128
 129		for (int i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
 130			u64 zone_end = (zones[i].start + zones[i].capacity) << SECTOR_SHIFT;
 131			u64 bytenr = ALIGN_DOWN(zone_end, BTRFS_SUPER_INFO_SIZE) -
 132						BTRFS_SUPER_INFO_SIZE;
 133
 134			page[i] = read_cache_page_gfp(mapping,
 135					bytenr >> PAGE_SHIFT, GFP_NOFS);
 136			if (IS_ERR(page[i])) {
 137				if (i == 1)
 138					btrfs_release_disk_super(super[0]);
 139				return PTR_ERR(page[i]);
 140			}
 141			super[i] = page_address(page[i]);
 142		}
 143
 144		if (btrfs_super_generation(super[0]) >
 145		    btrfs_super_generation(super[1]))
 146			sector = zones[1].start;
 147		else
 148			sector = zones[0].start;
 149
 150		for (int i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++)
 151			btrfs_release_disk_super(super[i]);
 152	} else if (!full[0] && (empty[1] || full[1])) {
 153		sector = zones[0].wp;
 154	} else if (full[0]) {
 155		sector = zones[1].wp;
 156	} else {
 157		return -EUCLEAN;
 158	}
 159	*wp_ret = sector << SECTOR_SHIFT;
 160	return 0;
 161}
 162
 163/*
 164 * Get the first zone number of the superblock mirror
 165 */
 166static inline u32 sb_zone_number(int shift, int mirror)
 167{
 168	u64 zone = U64_MAX;
 169
 170	ASSERT(mirror < BTRFS_SUPER_MIRROR_MAX, "mirror=%d", mirror);
 171	switch (mirror) {
 172	case 0: zone = 0; break;
 173	case 1: zone = 1ULL << (BTRFS_SB_LOG_FIRST_SHIFT - shift); break;
 174	case 2: zone = 1ULL << (BTRFS_SB_LOG_SECOND_SHIFT - shift); break;
 175	}
 176
 177	ASSERT(zone <= U32_MAX, "zone=%llu", zone);
 178
 179	return (u32)zone;
 180}
 181
 182static inline sector_t zone_start_sector(u32 zone_number,
 183					 struct block_device *bdev)
 184{
 185	return (sector_t)zone_number << ilog2(bdev_zone_sectors(bdev));
 186}
 187
 188static inline u64 zone_start_physical(u32 zone_number,
 189				      struct btrfs_zoned_device_info *zone_info)
 190{
 191	return (u64)zone_number << zone_info->zone_size_shift;
 192}
 193
 194/*
 195 * Emulate blkdev_report_zones() for a non-zoned device. It slices up the block
 196 * device into static sized chunks and fake a conventional zone on each of
 197 * them.
 198 */
 199static int emulate_report_zones(struct btrfs_device *device, u64 pos,
 200				struct blk_zone *zones, unsigned int nr_zones)
 201{
 202	const sector_t zone_sectors = device->fs_info->zone_size >> SECTOR_SHIFT;
 203	sector_t bdev_size = bdev_nr_sectors(device->bdev);
 204	unsigned int i;
 205
 206	pos >>= SECTOR_SHIFT;
 207	for (i = 0; i < nr_zones; i++) {
 208		zones[i].start = i * zone_sectors + pos;
 209		zones[i].len = zone_sectors;
 210		zones[i].capacity = zone_sectors;
 211		zones[i].wp = zones[i].start + zone_sectors;
 212		zones[i].type = BLK_ZONE_TYPE_CONVENTIONAL;
 213		zones[i].cond = BLK_ZONE_COND_NOT_WP;
 214
 215		if (zones[i].wp >= bdev_size) {
 216			i++;
 217			break;
 218		}
 219	}
 220
 221	return i;
 222}
 223
 224static int btrfs_get_dev_zones(struct btrfs_device *device, u64 pos,
 225			       struct blk_zone *zones, unsigned int *nr_zones)
 226{
 227	struct btrfs_zoned_device_info *zinfo = device->zone_info;
 228	int ret;
 229
 230	if (!*nr_zones)
 231		return 0;
 232
 233	if (!bdev_is_zoned(device->bdev)) {
 234		ret = emulate_report_zones(device, pos, zones, *nr_zones);
 235		*nr_zones = ret;
 236		return 0;
 237	}
 238
 239	/* Check cache */
 240	if (zinfo->zone_cache) {
 241		unsigned int i;
 242		u32 zno;
 243
 244		ASSERT(IS_ALIGNED(pos, zinfo->zone_size),
 245		       "pos=%llu zinfo->zone_size=%llu", pos, zinfo->zone_size);
 246		zno = pos >> zinfo->zone_size_shift;
 247		/*
 248		 * We cannot report zones beyond the zone end. So, it is OK to
 249		 * cap *nr_zones to at the end.
 250		 */
 251		*nr_zones = min_t(u32, *nr_zones, zinfo->nr_zones - zno);
 252
 253		for (i = 0; i < *nr_zones; i++) {
 254			struct blk_zone *zone_info;
 255
 256			zone_info = &zinfo->zone_cache[zno + i];
 257			if (!zone_info->len)
 258				break;
 259		}
 260
 261		if (i == *nr_zones) {
 262			/* Cache hit on all the zones */
 263			memcpy(zones, zinfo->zone_cache + zno,
 264			       sizeof(*zinfo->zone_cache) * *nr_zones);
 265			return 0;
 266		}
 267	}
 268
 269	ret = blkdev_report_zones_cached(device->bdev, pos >> SECTOR_SHIFT,
 270					 *nr_zones, copy_zone_info_cb, zones);
 271	if (ret < 0) {
 272		btrfs_err(device->fs_info,
 273				 "zoned: failed to read zone %llu on %s (devid %llu)",
 274				 pos, rcu_dereference(device->name),
 275				 device->devid);
 276		return ret;
 277	}
 278	*nr_zones = ret;
 279	if (unlikely(!ret))
 280		return -EIO;
 281
 282	/* Populate cache */
 283	if (zinfo->zone_cache) {
 284		u32 zno = pos >> zinfo->zone_size_shift;
 285
 286		memcpy(zinfo->zone_cache + zno, zones,
 287		       sizeof(*zinfo->zone_cache) * *nr_zones);
 288	}
 289
 290	return 0;
 291}
 292
 293/* The emulated zone size is determined from the size of device extent */
 294static int calculate_emulated_zone_size(struct btrfs_fs_info *fs_info)
 295{
 296	BTRFS_PATH_AUTO_FREE(path);
 297	struct btrfs_root *root = fs_info->dev_root;
 298	struct btrfs_key key;
 299	struct extent_buffer *leaf;
 300	struct btrfs_dev_extent *dext;
 301	int ret = 0;
 302
 303	key.objectid = 1;
 304	key.type = BTRFS_DEV_EXTENT_KEY;
 305	key.offset = 0;
 306
 307	path = btrfs_alloc_path();
 308	if (!path)
 309		return -ENOMEM;
 310
 311	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
 312	if (ret < 0)
 313		return ret;
 314
 315	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
 316		ret = btrfs_next_leaf(root, path);
 317		if (ret < 0)
 318			return ret;
 319		/* No dev extents at all? Not good */
 320		if (unlikely(ret > 0))
 321			return -EUCLEAN;
 322	}
 323
 324	leaf = path->nodes[0];
 325	dext = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
 326	fs_info->zone_size = btrfs_dev_extent_length(leaf, dext);
 327	return 0;
 328}
 329
 330int btrfs_get_dev_zone_info_all_devices(struct btrfs_fs_info *fs_info)
 331{
 332	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
 333	struct btrfs_device *device;
 334	int ret = 0;
 335
 336	/* fs_info->zone_size might not set yet. Use the incomapt flag here. */
 337	if (!btrfs_fs_incompat(fs_info, ZONED))
 338		return 0;
 339
 340	/*
 341	 * No need to take the device_list mutex here, we're still in the mount
 342	 * path and devices cannot be added to or removed from the list yet.
 343	 */
 344	list_for_each_entry(device, &fs_devices->devices, dev_list) {
 345		/* We can skip reading of zone info for missing devices */
 346		if (!device->bdev)
 347			continue;
 348
 349		ret = btrfs_get_dev_zone_info(device, true);
 350		if (ret)
 351			break;
 352	}
 353
 354	return ret;
 355}
 356
 357int btrfs_get_dev_zone_info(struct btrfs_device *device, bool populate_cache)
 358{
 359	struct btrfs_fs_info *fs_info = device->fs_info;
 360	struct btrfs_zoned_device_info *zone_info = NULL;
 361	struct block_device *bdev = device->bdev;
 362	unsigned int max_active_zones;
 363	unsigned int nactive;
 364	sector_t nr_sectors;
 365	sector_t sector = 0;
 366	struct blk_zone *zones = NULL;
 367	unsigned int i, nreported = 0, nr_zones;
 368	sector_t zone_sectors;
 369	char *model, *emulated;
 370	int ret;
 371
 372	/*
 373	 * Cannot use btrfs_is_zoned here, since fs_info::zone_size might not
 374	 * yet be set.
 375	 */
 376	if (!btrfs_fs_incompat(fs_info, ZONED))
 377		return 0;
 378
 379	if (device->zone_info)
 380		return 0;
 381
 382	zone_info = kzalloc(sizeof(*zone_info), GFP_KERNEL);
 383	if (!zone_info)
 384		return -ENOMEM;
 385
 386	device->zone_info = zone_info;
 387
 388	if (!bdev_is_zoned(bdev)) {
 389		if (!fs_info->zone_size) {
 390			ret = calculate_emulated_zone_size(fs_info);
 391			if (ret)
 392				goto out;
 393		}
 394
 395		ASSERT(fs_info->zone_size);
 396		zone_sectors = fs_info->zone_size >> SECTOR_SHIFT;
 397	} else {
 398		zone_sectors = bdev_zone_sectors(bdev);
 399	}
 400
 401	ASSERT(is_power_of_two_u64(zone_sectors));
 402	zone_info->zone_size = zone_sectors << SECTOR_SHIFT;
 403
 404	/* We reject devices with a zone size larger than 8GB */
 405	if (zone_info->zone_size > BTRFS_MAX_ZONE_SIZE) {
 406		btrfs_err(fs_info,
 407		"zoned: %s: zone size %llu larger than supported maximum %llu",
 408				 rcu_dereference(device->name),
 409				 zone_info->zone_size, BTRFS_MAX_ZONE_SIZE);
 410		ret = -EINVAL;
 411		goto out;
 412	} else if (zone_info->zone_size < BTRFS_MIN_ZONE_SIZE) {
 413		btrfs_err(fs_info,
 414		"zoned: %s: zone size %llu smaller than supported minimum %u",
 415				 rcu_dereference(device->name),
 416				 zone_info->zone_size, BTRFS_MIN_ZONE_SIZE);
 417		ret = -EINVAL;
 418		goto out;
 419	}
 420
 421	nr_sectors = bdev_nr_sectors(bdev);
 422	zone_info->zone_size_shift = ilog2(zone_info->zone_size);
 423	zone_info->nr_zones = nr_sectors >> ilog2(zone_sectors);
 424	if (!IS_ALIGNED(nr_sectors, zone_sectors))
 425		zone_info->nr_zones++;
 426
 427	max_active_zones = min_not_zero(bdev_max_active_zones(bdev),
 428					bdev_max_open_zones(bdev));
 429	if (!max_active_zones && zone_info->nr_zones > BTRFS_DEFAULT_MAX_ACTIVE_ZONES)
 430		max_active_zones = BTRFS_DEFAULT_MAX_ACTIVE_ZONES;
 431	if (max_active_zones && max_active_zones < BTRFS_MIN_ACTIVE_ZONES) {
 432		btrfs_err(fs_info,
 433"zoned: %s: max active zones %u is too small, need at least %u active zones",
 434				 rcu_dereference(device->name), max_active_zones,
 435				 BTRFS_MIN_ACTIVE_ZONES);
 436		ret = -EINVAL;
 437		goto out;
 438	}
 439	zone_info->max_active_zones = max_active_zones;
 440
 441	zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 442	if (!zone_info->seq_zones) {
 443		ret = -ENOMEM;
 444		goto out;
 445	}
 446
 447	zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 448	if (!zone_info->empty_zones) {
 449		ret = -ENOMEM;
 450		goto out;
 451	}
 452
 453	zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 454	if (!zone_info->active_zones) {
 455		ret = -ENOMEM;
 456		goto out;
 457	}
 458
 459	zones = kvcalloc(BTRFS_REPORT_NR_ZONES, sizeof(struct blk_zone), GFP_KERNEL);
 460	if (!zones) {
 461		ret = -ENOMEM;
 462		goto out;
 463	}
 464
 465	/*
 466	 * Enable zone cache only for a zoned device. On a non-zoned device, we
 467	 * fill the zone info with emulated CONVENTIONAL zones, so no need to
 468	 * use the cache.
 469	 */
 470	if (populate_cache && bdev_is_zoned(device->bdev)) {
 471		zone_info->zone_cache = vcalloc(zone_info->nr_zones,
 472						sizeof(struct blk_zone));
 473		if (!zone_info->zone_cache) {
 474			btrfs_err(device->fs_info,
 475				"zoned: failed to allocate zone cache for %s",
 476				rcu_dereference(device->name));
 477			ret = -ENOMEM;
 478			goto out;
 479		}
 480	}
 481
 482	/* Get zones type */
 483	nactive = 0;
 484	while (sector < nr_sectors) {
 485		nr_zones = BTRFS_REPORT_NR_ZONES;
 486		ret = btrfs_get_dev_zones(device, sector << SECTOR_SHIFT, zones,
 487					  &nr_zones);
 488		if (ret)
 489			goto out;
 490
 491		for (i = 0; i < nr_zones; i++) {
 492			if (zones[i].type == BLK_ZONE_TYPE_SEQWRITE_REQ)
 493				__set_bit(nreported, zone_info->seq_zones);
 494			switch (zones[i].cond) {
 495			case BLK_ZONE_COND_EMPTY:
 496				__set_bit(nreported, zone_info->empty_zones);
 497				break;
 498			case BLK_ZONE_COND_IMP_OPEN:
 499			case BLK_ZONE_COND_EXP_OPEN:
 500			case BLK_ZONE_COND_CLOSED:
 501			case BLK_ZONE_COND_ACTIVE:
 502				__set_bit(nreported, zone_info->active_zones);
 503				nactive++;
 504				break;
 505			}
 506			nreported++;
 507		}
 508		sector = zones[nr_zones - 1].start + zones[nr_zones - 1].len;
 509	}
 510
 511	if (unlikely(nreported != zone_info->nr_zones)) {
 512		btrfs_err(device->fs_info,
 513				 "inconsistent number of zones on %s (%u/%u)",
 514				 rcu_dereference(device->name), nreported,
 515				 zone_info->nr_zones);
 516		ret = -EIO;
 517		goto out;
 518	}
 519
 520	if (max_active_zones) {
 521		if (unlikely(nactive > max_active_zones)) {
 522			if (bdev_max_active_zones(bdev) == 0) {
 523				max_active_zones = 0;
 524				zone_info->max_active_zones = 0;
 525				goto validate;
 526			}
 527			btrfs_err(device->fs_info,
 528			"zoned: %u active zones on %s exceeds max_active_zones %u",
 529					 nactive, rcu_dereference(device->name),
 530					 max_active_zones);
 531			ret = -EIO;
 532			goto out;
 533		}
 534		atomic_set(&zone_info->active_zones_left,
 535			   max_active_zones - nactive);
 536		set_bit(BTRFS_FS_ACTIVE_ZONE_TRACKING, &fs_info->flags);
 537	}
 538
 539validate:
 540	/* Validate superblock log */
 541	nr_zones = BTRFS_NR_SB_LOG_ZONES;
 542	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
 543		u32 sb_zone;
 544		u64 sb_wp;
 545		int sb_pos = BTRFS_NR_SB_LOG_ZONES * i;
 546
 547		sb_zone = sb_zone_number(zone_info->zone_size_shift, i);
 548		if (sb_zone + 1 >= zone_info->nr_zones)
 549			continue;
 550
 551		ret = btrfs_get_dev_zones(device,
 552					  zone_start_physical(sb_zone, zone_info),
 553					  &zone_info->sb_zones[sb_pos],
 554					  &nr_zones);
 555		if (ret)
 556			goto out;
 557
 558		if (unlikely(nr_zones != BTRFS_NR_SB_LOG_ZONES)) {
 559			btrfs_err(device->fs_info,
 560	"zoned: failed to read super block log zone info at devid %llu zone %u",
 561					 device->devid, sb_zone);
 562			ret = -EUCLEAN;
 563			goto out;
 564		}
 565
 566		/*
 567		 * If zones[0] is conventional, always use the beginning of the
 568		 * zone to record superblock. No need to validate in that case.
 569		 */
 570		if (zone_info->sb_zones[BTRFS_NR_SB_LOG_ZONES * i].type ==
 571		    BLK_ZONE_TYPE_CONVENTIONAL)
 572			continue;
 573
 574		ret = sb_write_pointer(device->bdev,
 575				       &zone_info->sb_zones[sb_pos], &sb_wp);
 576		if (unlikely(ret != -ENOENT && ret)) {
 577			btrfs_err(device->fs_info,
 578			"zoned: super block log zone corrupted devid %llu zone %u",
 579					 device->devid, sb_zone);
 580			ret = -EUCLEAN;
 581			goto out;
 582		}
 583	}
 584
 585
 586	kvfree(zones);
 587
 588	if (bdev_is_zoned(bdev)) {
 589		model = "host-managed zoned";
 590		emulated = "";
 591	} else {
 592		model = "regular";
 593		emulated = "emulated ";
 594	}
 595
 596	btrfs_info(fs_info,
 597		"%s block device %s, %u %szones of %llu bytes",
 598		model, rcu_dereference(device->name), zone_info->nr_zones,
 599		emulated, zone_info->zone_size);
 600
 601	return 0;
 602
 603out:
 604	kvfree(zones);
 605	btrfs_destroy_dev_zone_info(device);
 606	return ret;
 607}
 608
 609void btrfs_destroy_dev_zone_info(struct btrfs_device *device)
 610{
 611	struct btrfs_zoned_device_info *zone_info = device->zone_info;
 612
 613	if (!zone_info)
 614		return;
 615
 616	bitmap_free(zone_info->active_zones);
 617	bitmap_free(zone_info->seq_zones);
 618	bitmap_free(zone_info->empty_zones);
 619	vfree(zone_info->zone_cache);
 620	kfree(zone_info);
 621	device->zone_info = NULL;
 622}
 623
 624struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *orig_dev)
 625{
 626	struct btrfs_zoned_device_info *zone_info;
 627
 628	zone_info = kmemdup(orig_dev->zone_info, sizeof(*zone_info), GFP_KERNEL);
 629	if (!zone_info)
 630		return NULL;
 631
 632	zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 633	if (!zone_info->seq_zones)
 634		goto out;
 635
 636	bitmap_copy(zone_info->seq_zones, orig_dev->zone_info->seq_zones,
 637		    zone_info->nr_zones);
 638
 639	zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 640	if (!zone_info->empty_zones)
 641		goto out;
 642
 643	bitmap_copy(zone_info->empty_zones, orig_dev->zone_info->empty_zones,
 644		    zone_info->nr_zones);
 645
 646	zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 647	if (!zone_info->active_zones)
 648		goto out;
 649
 650	bitmap_copy(zone_info->active_zones, orig_dev->zone_info->active_zones,
 651		    zone_info->nr_zones);
 652	zone_info->zone_cache = NULL;
 653
 654	return zone_info;
 655
 656out:
 657	bitmap_free(zone_info->seq_zones);
 658	bitmap_free(zone_info->empty_zones);
 659	bitmap_free(zone_info->active_zones);
 660	kfree(zone_info);
 661	return NULL;
 662}
 663
 664static int btrfs_get_dev_zone(struct btrfs_device *device, u64 pos, struct blk_zone *zone)
 665{
 666	unsigned int nr_zones = 1;
 667	int ret;
 668
 669	ret = btrfs_get_dev_zones(device, pos, zone, &nr_zones);
 670	if (ret != 0 || !nr_zones)
 671		return ret ? ret : -EIO;
 672
 673	return 0;
 674}
 675
 676static int btrfs_check_for_zoned_device(struct btrfs_fs_info *fs_info)
 677{
 678	struct btrfs_device *device;
 679
 680	list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
 681		if (device->bdev && bdev_is_zoned(device->bdev)) {
 682			btrfs_err(fs_info,
 683				"zoned: mode not enabled but zoned device found: %pg",
 684				device->bdev);
 685			return -EINVAL;
 686		}
 687	}
 688
 689	return 0;
 690}
 691
 692int btrfs_check_zoned_mode(struct btrfs_fs_info *fs_info)
 693{
 694	struct queue_limits *lim = &fs_info->limits;
 695	struct btrfs_device *device;
 696	u64 zone_size = 0;
 697	int ret;
 698
 699	/*
 700	 * Host-Managed devices can't be used without the ZONED flag.  With the
 701	 * ZONED all devices can be used, using zone emulation if required.
 702	 */
 703	if (!btrfs_fs_incompat(fs_info, ZONED))
 704		return btrfs_check_for_zoned_device(fs_info);
 705
 706	blk_set_stacking_limits(lim);
 707
 708	list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
 709		struct btrfs_zoned_device_info *zone_info = device->zone_info;
 710
 711		if (!device->bdev)
 712			continue;
 713
 714		if (!zone_size) {
 715			zone_size = zone_info->zone_size;
 716		} else if (zone_info->zone_size != zone_size) {
 717			btrfs_err(fs_info,
 718		"zoned: unequal block device zone sizes: have %llu found %llu",
 719				  zone_info->zone_size, zone_size);
 720			return -EINVAL;
 721		}
 722
 723		/*
 724		 * With the zoned emulation, we can have non-zoned device on the
 725		 * zoned mode. In this case, we don't have a valid max zone
 726		 * append size.
 727		 */
 728		if (bdev_is_zoned(device->bdev))
 729			blk_stack_limits(lim, bdev_limits(device->bdev), 0);
 730	}
 731
 732	ret = blk_validate_limits(lim);
 733	if (ret) {
 734		btrfs_err(fs_info, "zoned: failed to validate queue limits");
 735		return ret;
 736	}
 737
 738	/*
 739	 * stripe_size is always aligned to BTRFS_STRIPE_LEN in
 740	 * btrfs_create_chunk(). Since we want stripe_len == zone_size,
 741	 * check the alignment here.
 742	 */
 743	if (!IS_ALIGNED(zone_size, BTRFS_STRIPE_LEN)) {
 744		btrfs_err(fs_info,
 745			  "zoned: zone size %llu not aligned to stripe %u",
 746			  zone_size, BTRFS_STRIPE_LEN);
 747		return -EINVAL;
 748	}
 749
 750	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
 751		btrfs_err(fs_info, "zoned: mixed block groups not supported");
 752		return -EINVAL;
 753	}
 754
 755	fs_info->zone_size = zone_size;
 756	/*
 757	 * Also limit max_zone_append_size by max_segments * PAGE_SIZE.
 758	 * Technically, we can have multiple pages per segment. But, since
 759	 * we add the pages one by one to a bio, and cannot increase the
 760	 * metadata reservation even if it increases the number of extents, it
 761	 * is safe to stick with the limit.
 762	 */
 763	fs_info->max_zone_append_size = ALIGN_DOWN(
 764		min3((u64)lim->max_zone_append_sectors << SECTOR_SHIFT,
 765		     (u64)lim->max_sectors << SECTOR_SHIFT,
 766		     (u64)lim->max_segments << PAGE_SHIFT),
 767		fs_info->sectorsize);
 768	fs_info->fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_ZONED;
 769
 770	fs_info->max_extent_size = min_not_zero(fs_info->max_extent_size,
 771						fs_info->max_zone_append_size);
 772
 773	/*
 774	 * Check mount options here, because we might change fs_info->zoned
 775	 * from fs_info->zone_size.
 776	 */
 777	ret = btrfs_check_mountopts_zoned(fs_info, &fs_info->mount_opt);
 778	if (ret)
 779		return ret;
 780
 781	btrfs_info(fs_info, "zoned mode enabled with zone size %llu", zone_size);
 782	return 0;
 783}
 784
 785int btrfs_check_mountopts_zoned(const struct btrfs_fs_info *info,
 786				unsigned long long *mount_opt)
 787{
 788	if (!btrfs_is_zoned(info))
 789		return 0;
 790
 791	/*
 792	 * Space cache writing is not COWed. Disable that to avoid write errors
 793	 * in sequential zones.
 794	 */
 795	if (btrfs_raw_test_opt(*mount_opt, SPACE_CACHE)) {
 796		btrfs_err(info, "zoned: space cache v1 is not supported");
 797		return -EINVAL;
 798	}
 799
 800	if (btrfs_raw_test_opt(*mount_opt, NODATACOW)) {
 801		btrfs_err(info, "zoned: NODATACOW not supported");
 802		return -EINVAL;
 803	}
 804
 805	if (btrfs_raw_test_opt(*mount_opt, DISCARD_ASYNC)) {
 806		btrfs_info(info,
 807			   "zoned: async discard ignored and disabled for zoned mode");
 808		btrfs_clear_opt(*mount_opt, DISCARD_ASYNC);
 809	}
 810
 811	return 0;
 812}
 813
 814static int sb_log_location(struct block_device *bdev, struct blk_zone *zones,
 815			   int rw, u64 *bytenr_ret)
 816{
 817	u64 wp;
 818	int ret;
 819
 820	if (zones[0].type == BLK_ZONE_TYPE_CONVENTIONAL) {
 821		*bytenr_ret = zones[0].start << SECTOR_SHIFT;
 822		return 0;
 823	}
 824
 825	ret = sb_write_pointer(bdev, zones, &wp);
 826	if (ret != -ENOENT && ret < 0)
 827		return ret;
 828
 829	if (rw == WRITE) {
 830		struct blk_zone *reset = NULL;
 831
 832		if (wp == zones[0].start << SECTOR_SHIFT)
 833			reset = &zones[0];
 834		else if (wp == zones[1].start << SECTOR_SHIFT)
 835			reset = &zones[1];
 836
 837		if (reset && reset->cond != BLK_ZONE_COND_EMPTY) {
 838			unsigned int nofs_flags;
 839
 840			ASSERT(sb_zone_is_full(reset));
 841
 842			nofs_flags = memalloc_nofs_save();
 843			ret = blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
 844					       reset->start, reset->len);
 845			memalloc_nofs_restore(nofs_flags);
 846			if (ret)
 847				return ret;
 848
 849			reset->cond = BLK_ZONE_COND_EMPTY;
 850			reset->wp = reset->start;
 851		}
 852	} else if (ret != -ENOENT) {
 853		/*
 854		 * For READ, we want the previous one. Move write pointer to
 855		 * the end of a zone, if it is at the head of a zone.
 856		 */
 857		u64 zone_end = 0;
 858
 859		if (wp == zones[0].start << SECTOR_SHIFT)
 860			zone_end = zones[1].start + zones[1].capacity;
 861		else if (wp == zones[1].start << SECTOR_SHIFT)
 862			zone_end = zones[0].start + zones[0].capacity;
 863		if (zone_end)
 864			wp = ALIGN_DOWN(zone_end << SECTOR_SHIFT,
 865					BTRFS_SUPER_INFO_SIZE);
 866
 867		wp -= BTRFS_SUPER_INFO_SIZE;
 868	}
 869
 870	*bytenr_ret = wp;
 871	return 0;
 872
 873}
 874
 875int btrfs_sb_log_location_bdev(struct block_device *bdev, int mirror, int rw,
 876			       u64 *bytenr_ret)
 877{
 878	struct blk_zone zones[BTRFS_NR_SB_LOG_ZONES];
 879	sector_t zone_sectors;
 880	u32 sb_zone;
 881	int ret;
 882	u8 zone_sectors_shift;
 883	sector_t nr_sectors;
 884	u32 nr_zones;
 885
 886	if (!bdev_is_zoned(bdev)) {
 887		*bytenr_ret = btrfs_sb_offset(mirror);
 888		return 0;
 889	}
 890
 891	ASSERT(rw == READ || rw == WRITE);
 892
 893	zone_sectors = bdev_zone_sectors(bdev);
 894	if (!is_power_of_2(zone_sectors))
 895		return -EINVAL;
 896	zone_sectors_shift = ilog2(zone_sectors);
 897	nr_sectors = bdev_nr_sectors(bdev);
 898	nr_zones = nr_sectors >> zone_sectors_shift;
 899
 900	sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
 901	if (sb_zone + 1 >= nr_zones)
 902		return -ENOENT;
 903
 904	ret = blkdev_report_zones_cached(bdev, zone_start_sector(sb_zone, bdev),
 905					 BTRFS_NR_SB_LOG_ZONES,
 906					 copy_zone_info_cb, zones);
 907	if (ret < 0)
 908		return ret;
 909	if (unlikely(ret != BTRFS_NR_SB_LOG_ZONES))
 910		return -EIO;
 911
 912	return sb_log_location(bdev, zones, rw, bytenr_ret);
 913}
 914
 915int btrfs_sb_log_location(struct btrfs_device *device, int mirror, int rw,
 916			  u64 *bytenr_ret)
 917{
 918	struct btrfs_zoned_device_info *zinfo = device->zone_info;
 919	u32 zone_num;
 920
 921	/*
 922	 * For a zoned filesystem on a non-zoned block device, use the same
 923	 * super block locations as regular filesystem. Doing so, the super
 924	 * block can always be retrieved and the zoned flag of the volume
 925	 * detected from the super block information.
 926	 */
 927	if (!bdev_is_zoned(device->bdev)) {
 928		*bytenr_ret = btrfs_sb_offset(mirror);
 929		return 0;
 930	}
 931
 932	zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
 933	if (zone_num + 1 >= zinfo->nr_zones)
 934		return -ENOENT;
 935
 936	return sb_log_location(device->bdev,
 937			       &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror],
 938			       rw, bytenr_ret);
 939}
 940
 941static inline bool is_sb_log_zone(struct btrfs_zoned_device_info *zinfo,
 942				  int mirror)
 943{
 944	u32 zone_num;
 945
 946	if (!zinfo)
 947		return false;
 948
 949	zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
 950	if (zone_num + 1 >= zinfo->nr_zones)
 951		return false;
 952
 953	if (!test_bit(zone_num, zinfo->seq_zones))
 954		return false;
 955
 956	return true;
 957}
 958
 959int btrfs_advance_sb_log(struct btrfs_device *device, int mirror)
 960{
 961	struct btrfs_zoned_device_info *zinfo = device->zone_info;
 962	struct blk_zone *zone;
 963	int i;
 964
 965	if (!is_sb_log_zone(zinfo, mirror))
 966		return 0;
 967
 968	zone = &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror];
 969	for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
 970		/* Advance the next zone */
 971		if (zone->cond == BLK_ZONE_COND_FULL) {
 972			zone++;
 973			continue;
 974		}
 975
 976		if (zone->cond == BLK_ZONE_COND_EMPTY)
 977			zone->cond = BLK_ZONE_COND_IMP_OPEN;
 978
 979		zone->wp += SUPER_INFO_SECTORS;
 980
 981		if (sb_zone_is_full(zone)) {
 982			/*
 983			 * No room left to write new superblock. Since
 984			 * superblock is written with REQ_SYNC, it is safe to
 985			 * finish the zone now.
 986			 *
 987			 * If the write pointer is exactly at the capacity,
 988			 * explicit ZONE_FINISH is not necessary.
 989			 */
 990			if (zone->wp != zone->start + zone->capacity) {
 991				unsigned int nofs_flags;
 992				int ret;
 993
 994				nofs_flags = memalloc_nofs_save();
 995				ret = blkdev_zone_mgmt(device->bdev,
 996						REQ_OP_ZONE_FINISH, zone->start,
 997						zone->len);
 998				memalloc_nofs_restore(nofs_flags);
 999				if (ret)
1000					return ret;
1001			}
1002
1003			zone->wp = zone->start + zone->len;
1004			zone->cond = BLK_ZONE_COND_FULL;
1005		}
1006		return 0;
1007	}
1008
1009	/* All the zones are FULL. Should not reach here. */
1010	DEBUG_WARN("unexpected state, all zones full");
1011	return -EIO;
1012}
1013
1014int btrfs_reset_sb_log_zones(struct block_device *bdev, int mirror)
1015{
1016	unsigned int nofs_flags;
1017	sector_t zone_sectors;
1018	sector_t nr_sectors;
1019	u8 zone_sectors_shift;
1020	u32 sb_zone;
1021	u32 nr_zones;
1022	int ret;
1023
1024	zone_sectors = bdev_zone_sectors(bdev);
1025	zone_sectors_shift = ilog2(zone_sectors);
1026	nr_sectors = bdev_nr_sectors(bdev);
1027	nr_zones = nr_sectors >> zone_sectors_shift;
1028
1029	sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
1030	if (sb_zone + 1 >= nr_zones)
1031		return -ENOENT;
1032
1033	nofs_flags = memalloc_nofs_save();
1034	ret = blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
1035			       zone_start_sector(sb_zone, bdev),
1036			       zone_sectors * BTRFS_NR_SB_LOG_ZONES);
1037	memalloc_nofs_restore(nofs_flags);
1038	return ret;
1039}
1040
1041/*
1042 * Find allocatable zones within a given region.
1043 *
1044 * @device:	the device to allocate a region on
1045 * @hole_start: the position of the hole to allocate the region
1046 * @num_bytes:	size of wanted region
1047 * @hole_end:	the end of the hole
1048 * @return:	position of allocatable zones
1049 *
1050 * Allocatable region should not contain any superblock locations.
1051 */
1052u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start,
1053				 u64 hole_end, u64 num_bytes)
1054{
1055	struct btrfs_zoned_device_info *zinfo = device->zone_info;
1056	const u8 shift = zinfo->zone_size_shift;
1057	u64 nzones = num_bytes >> shift;
1058	u64 pos = hole_start;
1059	u64 begin, end;
1060	bool have_sb;
1061	int i;
1062
1063	ASSERT(IS_ALIGNED(hole_start, zinfo->zone_size),
1064	       "hole_start=%llu zinfo->zone_size=%llu", hole_start, zinfo->zone_size);
1065	ASSERT(IS_ALIGNED(num_bytes, zinfo->zone_size),
1066	       "num_bytes=%llu zinfo->zone_size=%llu", num_bytes, zinfo->zone_size);
1067
1068	while (pos < hole_end) {
1069		begin = pos >> shift;
1070		end = begin + nzones;
1071
1072		if (end > zinfo->nr_zones)
1073			return hole_end;
1074
1075		/* Check if zones in the region are all empty */
1076		if (btrfs_dev_is_sequential(device, pos) &&
1077		    !bitmap_test_range_all_set(zinfo->empty_zones, begin, nzones)) {
1078			pos += zinfo->zone_size;
1079			continue;
1080		}
1081
1082		have_sb = false;
1083		for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1084			u32 sb_zone;
1085			u64 sb_pos;
1086
1087			sb_zone = sb_zone_number(shift, i);
1088			if (!(end <= sb_zone ||
1089			      sb_zone + BTRFS_NR_SB_LOG_ZONES <= begin)) {
1090				have_sb = true;
1091				pos = zone_start_physical(
1092					sb_zone + BTRFS_NR_SB_LOG_ZONES, zinfo);
1093				break;
1094			}
1095
1096			/* We also need to exclude regular superblock positions */
1097			sb_pos = btrfs_sb_offset(i);
1098			if (!(pos + num_bytes <= sb_pos ||
1099			      sb_pos + BTRFS_SUPER_INFO_SIZE <= pos)) {
1100				have_sb = true;
1101				pos = ALIGN(sb_pos + BTRFS_SUPER_INFO_SIZE,
1102					    zinfo->zone_size);
1103				break;
1104			}
1105		}
1106		if (!have_sb)
1107			break;
1108	}
1109
1110	return pos;
1111}
1112
1113static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos)
1114{
1115	struct btrfs_zoned_device_info *zone_info = device->zone_info;
1116	unsigned int zno = (pos >> zone_info->zone_size_shift);
1117
1118	/* We can use any number of zones */
1119	if (zone_info->max_active_zones == 0)
1120		return true;
1121
1122	if (!test_bit(zno, zone_info->active_zones)) {
1123		/* Active zone left? */
1124		if (atomic_dec_if_positive(&zone_info->active_zones_left) < 0)
1125			return false;
1126		if (test_and_set_bit(zno, zone_info->active_zones)) {
1127			/* Someone already set the bit */
1128			atomic_inc(&zone_info->active_zones_left);
1129		}
1130	}
1131
1132	return true;
1133}
1134
1135static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos)
1136{
1137	struct btrfs_zoned_device_info *zone_info = device->zone_info;
1138	unsigned int zno = (pos >> zone_info->zone_size_shift);
1139
1140	/* We can use any number of zones */
1141	if (zone_info->max_active_zones == 0)
1142		return;
1143
1144	if (test_and_clear_bit(zno, zone_info->active_zones))
1145		atomic_inc(&zone_info->active_zones_left);
1146}
1147
1148int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical,
1149			    u64 length, u64 *bytes)
1150{
1151	unsigned int nofs_flags;
1152	int ret;
1153
1154	*bytes = 0;
1155	nofs_flags = memalloc_nofs_save();
1156	ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_RESET,
1157			       physical >> SECTOR_SHIFT, length >> SECTOR_SHIFT);
1158	memalloc_nofs_restore(nofs_flags);
1159	if (ret)
1160		return ret;
1161
1162	*bytes = length;
1163	while (length) {
1164		btrfs_dev_set_zone_empty(device, physical);
1165		btrfs_dev_clear_active_zone(device, physical);
1166		physical += device->zone_info->zone_size;
1167		length -= device->zone_info->zone_size;
1168	}
1169
1170	return 0;
1171}
1172
1173int btrfs_ensure_empty_zones(struct btrfs_device *device, u64 start, u64 size)
1174{
1175	struct btrfs_zoned_device_info *zinfo = device->zone_info;
1176	const u8 shift = zinfo->zone_size_shift;
1177	unsigned long begin = start >> shift;
1178	unsigned long nbits = size >> shift;
1179	u64 pos;
1180	int ret;
1181
1182	ASSERT(IS_ALIGNED(start, zinfo->zone_size),
1183	       "start=%llu, zinfo->zone_size=%llu", start, zinfo->zone_size);
1184	ASSERT(IS_ALIGNED(size, zinfo->zone_size),
1185	       "size=%llu, zinfo->zone_size=%llu", size, zinfo->zone_size);
1186
1187	if (begin + nbits > zinfo->nr_zones)
1188		return -ERANGE;
1189
1190	/* All the zones are conventional */
1191	if (bitmap_test_range_all_zero(zinfo->seq_zones, begin, nbits))
1192		return 0;
1193
1194	/* All the zones are sequential and empty */
1195	if (bitmap_test_range_all_set(zinfo->seq_zones, begin, nbits) &&
1196	    bitmap_test_range_all_set(zinfo->empty_zones, begin, nbits))
1197		return 0;
1198
1199	for (pos = start; pos < start + size; pos += zinfo->zone_size) {
1200		u64 reset_bytes;
1201
1202		if (!btrfs_dev_is_sequential(device, pos) ||
1203		    btrfs_dev_is_empty_zone(device, pos))
1204			continue;
1205
1206		/* Free regions should be empty */
1207		btrfs_warn(
1208			device->fs_info,
1209		"zoned: resetting device %s (devid %llu) zone %llu for allocation",
1210			rcu_dereference(device->name), device->devid, pos >> shift);
1211		WARN_ON_ONCE(1);
1212
1213		ret = btrfs_reset_device_zone(device, pos, zinfo->zone_size,
1214					      &reset_bytes);
1215		if (ret)
1216			return ret;
1217	}
1218
1219	return 0;
1220}
1221
1222/*
1223 * Calculate an allocation pointer from the extent allocation information
1224 * for a block group consist of conventional zones. It is pointed to the
1225 * end of the highest addressed extent in the block group as an allocation
1226 * offset.
1227 */
1228static int calculate_alloc_pointer(struct btrfs_block_group *cache,
1229				   u64 *offset_ret, bool new)
1230{
1231	struct btrfs_fs_info *fs_info = cache->fs_info;
1232	struct btrfs_root *root;
1233	BTRFS_PATH_AUTO_FREE(path);
1234	struct btrfs_key key;
1235	struct btrfs_key found_key;
1236	int ret;
1237	u64 length;
1238
1239	/*
1240	 * Avoid  tree lookups for a new block group, there's no use for it.
1241	 * It must always be 0.
1242	 *
1243	 * Also, we have a lock chain of extent buffer lock -> chunk mutex.
1244	 * For new a block group, this function is called from
1245	 * btrfs_make_block_group() which is already taking the chunk mutex.
1246	 * Thus, we cannot call calculate_alloc_pointer() which takes extent
1247	 * buffer locks to avoid deadlock.
1248	 */
1249	if (new) {
1250		*offset_ret = 0;
1251		return 0;
1252	}
1253
1254	path = btrfs_alloc_path();
1255	if (!path)
1256		return -ENOMEM;
1257
1258	key.objectid = cache->start + cache->length;
1259	key.type = 0;
1260	key.offset = 0;
1261
1262	root = btrfs_extent_root(fs_info, key.objectid);
1263	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1264	/* We should not find the exact match */
1265	if (unlikely(!ret))
1266		ret = -EUCLEAN;
1267	if (ret < 0)
1268		return ret;
1269
1270	ret = btrfs_previous_extent_item(root, path, cache->start);
1271	if (ret) {
1272		if (ret == 1) {
1273			ret = 0;
1274			*offset_ret = 0;
1275		}
1276		return ret;
1277	}
1278
1279	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
1280
1281	if (found_key.type == BTRFS_EXTENT_ITEM_KEY)
1282		length = found_key.offset;
1283	else
1284		length = fs_info->nodesize;
1285
1286	if (unlikely(!(found_key.objectid >= cache->start &&
1287		       found_key.objectid + length <= cache->start + cache->length))) {
1288		return -EUCLEAN;
1289	}
1290	*offset_ret = found_key.objectid + length - cache->start;
1291	return 0;
1292}
1293
1294struct zone_info {
1295	u64 physical;
1296	u64 capacity;
1297	u64 alloc_offset;
1298};
1299
1300static int btrfs_load_zone_info(struct btrfs_fs_info *fs_info, int zone_idx,
1301				struct zone_info *info, unsigned long *active,
1302				struct btrfs_chunk_map *map, bool new)
1303{
1304	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1305	struct btrfs_device *device;
1306	int dev_replace_is_ongoing = 0;
1307	unsigned int nofs_flag;
1308	struct blk_zone zone;
1309	int ret;
1310
1311	info->physical = map->stripes[zone_idx].physical;
1312
1313	down_read(&dev_replace->rwsem);
1314	device = map->stripes[zone_idx].dev;
1315
1316	if (!device->bdev) {
1317		up_read(&dev_replace->rwsem);
1318		info->alloc_offset = WP_MISSING_DEV;
1319		return 0;
1320	}
1321
1322	/* Consider a zone as active if we can allow any number of active zones. */
1323	if (!device->zone_info->max_active_zones)
1324		__set_bit(zone_idx, active);
1325
1326	if (!btrfs_dev_is_sequential(device, info->physical)) {
1327		up_read(&dev_replace->rwsem);
1328		info->alloc_offset = WP_CONVENTIONAL;
1329		info->capacity = device->zone_info->zone_size;
1330		return 0;
1331	}
1332
1333	ASSERT(!new || btrfs_dev_is_empty_zone(device, info->physical));
1334
1335	/* This zone will be used for allocation, so mark this zone non-empty. */
1336	btrfs_dev_clear_zone_empty(device, info->physical);
1337
1338	dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
1339	if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
1340		btrfs_dev_clear_zone_empty(dev_replace->tgtdev, info->physical);
1341
1342	/*
1343	 * The group is mapped to a sequential zone. Get the zone write pointer
1344	 * to determine the allocation offset within the zone.
1345	 */
1346	WARN_ON(!IS_ALIGNED(info->physical, fs_info->zone_size));
1347
1348	if (new) {
1349		sector_t capacity;
1350
1351		capacity = bdev_zone_capacity(device->bdev, info->physical >> SECTOR_SHIFT);
1352		up_read(&dev_replace->rwsem);
1353		info->alloc_offset = 0;
1354		info->capacity = capacity << SECTOR_SHIFT;
1355
1356		return 0;
1357	}
1358
1359	nofs_flag = memalloc_nofs_save();
1360	ret = btrfs_get_dev_zone(device, info->physical, &zone);
1361	memalloc_nofs_restore(nofs_flag);
1362	if (ret) {
1363		up_read(&dev_replace->rwsem);
1364		if (ret != -EIO && ret != -EOPNOTSUPP)
1365			return ret;
1366		info->alloc_offset = WP_MISSING_DEV;
1367		return 0;
1368	}
1369
1370	if (unlikely(zone.type == BLK_ZONE_TYPE_CONVENTIONAL)) {
1371		btrfs_err(fs_info,
1372		"zoned: unexpected conventional zone %llu on device %s (devid %llu)",
1373			zone.start << SECTOR_SHIFT, rcu_dereference(device->name),
1374			device->devid);
1375		up_read(&dev_replace->rwsem);
1376		return -EIO;
1377	}
1378
1379	info->capacity = (zone.capacity << SECTOR_SHIFT);
1380
1381	switch (zone.cond) {
1382	case BLK_ZONE_COND_OFFLINE:
1383	case BLK_ZONE_COND_READONLY:
1384		btrfs_err(fs_info,
1385		"zoned: offline/readonly zone %llu on device %s (devid %llu)",
1386			  (info->physical >> device->zone_info->zone_size_shift),
1387			  rcu_dereference(device->name), device->devid);
1388		info->alloc_offset = WP_MISSING_DEV;
1389		break;
1390	case BLK_ZONE_COND_EMPTY:
1391		info->alloc_offset = 0;
1392		break;
1393	case BLK_ZONE_COND_FULL:
1394		info->alloc_offset = info->capacity;
1395		break;
1396	default:
1397		/* Partially used zone. */
1398		info->alloc_offset = ((zone.wp - zone.start) << SECTOR_SHIFT);
1399		__set_bit(zone_idx, active);
1400		break;
1401	}
1402
1403	up_read(&dev_replace->rwsem);
1404
1405	return 0;
1406}
1407
1408static int btrfs_load_block_group_single(struct btrfs_block_group *bg,
1409					 struct zone_info *info,
1410					 unsigned long *active)
1411{
1412	if (unlikely(info->alloc_offset == WP_MISSING_DEV)) {
1413		btrfs_err(bg->fs_info,
1414			"zoned: cannot recover write pointer for zone %llu",
1415			info->physical);
1416		return -EIO;
1417	}
1418
1419	bg->alloc_offset = info->alloc_offset;
1420	bg->zone_capacity = info->capacity;
1421	if (test_bit(0, active))
1422		set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &bg->runtime_flags);
1423	return 0;
1424}
1425
1426static int btrfs_load_block_group_dup(struct btrfs_block_group *bg,
1427				      struct btrfs_chunk_map *map,
1428				      struct zone_info *zone_info,
1429				      unsigned long *active,
1430				      u64 last_alloc)
1431{
1432	struct btrfs_fs_info *fs_info = bg->fs_info;
1433
1434	if ((map->type & BTRFS_BLOCK_GROUP_DATA) && !fs_info->stripe_root) {
1435		btrfs_err(fs_info, "zoned: data DUP profile needs raid-stripe-tree");
1436		return -EINVAL;
1437	}
1438
1439	bg->zone_capacity = min_not_zero(zone_info[0].capacity, zone_info[1].capacity);
1440
1441	if (unlikely(zone_info[0].alloc_offset == WP_MISSING_DEV)) {
1442		btrfs_err(bg->fs_info,
1443			  "zoned: cannot recover write pointer for zone %llu",
1444			  zone_info[0].physical);
1445		return -EIO;
1446	}
1447	if (unlikely(zone_info[1].alloc_offset == WP_MISSING_DEV)) {
1448		btrfs_err(bg->fs_info,
1449			  "zoned: cannot recover write pointer for zone %llu",
1450			  zone_info[1].physical);
1451		return -EIO;
1452	}
1453
1454	/*
1455	 * When the last extent is removed, last_alloc can be smaller than the other write
1456	 * pointer. In that case, last_alloc should be moved to the corresponding write
1457	 * pointer position.
1458	 */
1459	for (int i = 0; i < map->num_stripes; i++) {
1460		if (zone_info[i].alloc_offset == WP_CONVENTIONAL)
1461			continue;
1462		if (last_alloc <= zone_info[i].alloc_offset) {
1463			last_alloc = zone_info[i].alloc_offset;
1464			break;
1465		}
1466	}
1467
1468	if (zone_info[0].alloc_offset == WP_CONVENTIONAL)
1469		zone_info[0].alloc_offset = last_alloc;
1470
1471	if (zone_info[1].alloc_offset == WP_CONVENTIONAL)
1472		zone_info[1].alloc_offset = last_alloc;
1473
1474	if (unlikely(zone_info[0].alloc_offset != zone_info[1].alloc_offset)) {
1475		btrfs_err(bg->fs_info,
1476			  "zoned: write pointer offset mismatch of zones in DUP profile");
1477		return -EIO;
1478	}
1479
1480	if (test_bit(0, active) != test_bit(1, active)) {
1481		if (unlikely(!btrfs_zone_activate(bg)))
1482			return -EIO;
1483	} else if (test_bit(0, active)) {
1484		set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &bg->runtime_flags);
1485	}
1486
1487	bg->alloc_offset = zone_info[0].alloc_offset;
1488	return 0;
1489}
1490
1491static int btrfs_load_block_group_raid1(struct btrfs_block_group *bg,
1492					struct btrfs_chunk_map *map,
1493					struct zone_info *zone_info,
1494					unsigned long *active,
1495					u64 last_alloc)
1496{
1497	struct btrfs_fs_info *fs_info = bg->fs_info;
1498	int i;
1499
1500	if ((map->type & BTRFS_BLOCK_GROUP_DATA) && !fs_info->stripe_root) {
1501		btrfs_err(fs_info, "zoned: data %s needs raid-stripe-tree",
1502			  btrfs_bg_type_to_raid_name(map->type));
1503		return -EINVAL;
1504	}
1505
1506	/* In case a device is missing we have a cap of 0, so don't use it. */
1507	bg->zone_capacity = min_not_zero(zone_info[0].capacity, zone_info[1].capacity);
1508
1509	/*
1510	 * When the last extent is removed, last_alloc can be smaller than the other write
1511	 * pointer. In that case, last_alloc should be moved to the corresponding write
1512	 * pointer position.
1513	 */
1514	for (i = 0; i < map->num_stripes; i++) {
1515		if (zone_info[i].alloc_offset == WP_MISSING_DEV ||
1516		    zone_info[i].alloc_offset == WP_CONVENTIONAL)
1517			continue;
1518		if (last_alloc <= zone_info[i].alloc_offset) {
1519			last_alloc = zone_info[i].alloc_offset;
1520			break;
1521		}
1522	}
1523
1524	for (i = 0; i < map->num_stripes; i++) {
1525		if (zone_info[i].alloc_offset == WP_MISSING_DEV)
1526			continue;
1527
1528		if (zone_info[i].alloc_offset == WP_CONVENTIONAL)
1529			zone_info[i].alloc_offset = last_alloc;
1530
1531		if (unlikely((zone_info[0].alloc_offset != zone_info[i].alloc_offset) &&
1532			     !btrfs_test_opt(fs_info, DEGRADED))) {
1533			btrfs_err(fs_info,
1534			"zoned: write pointer offset mismatch of zones in %s profile",
1535				  btrfs_bg_type_to_raid_name(map->type));
1536			return -EIO;
1537		}
1538		if (test_bit(0, active) != test_bit(i, active)) {
1539			if (unlikely(!btrfs_test_opt(fs_info, DEGRADED) &&
1540				     !btrfs_zone_activate(bg))) {
1541				return -EIO;
1542			}
1543		} else {
1544			if (test_bit(0, active))
1545				set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &bg->runtime_flags);
1546		}
1547	}
1548
1549	if (zone_info[0].alloc_offset != WP_MISSING_DEV)
1550		bg->alloc_offset = zone_info[0].alloc_offset;
1551	else
1552		bg->alloc_offset = zone_info[i - 1].alloc_offset;
1553
1554	return 0;
1555}
1556
1557static int btrfs_load_block_group_raid0(struct btrfs_block_group *bg,
1558					struct btrfs_chunk_map *map,
1559					struct zone_info *zone_info,
1560					unsigned long *active,
1561					u64 last_alloc)
1562{
1563	struct btrfs_fs_info *fs_info = bg->fs_info;
1564	u64 stripe_nr = 0, stripe_offset = 0;
1565	u64 prev_offset = 0;
1566	u32 stripe_index = 0;
1567	bool has_partial = false, has_conventional = false;
1568
1569	if ((map->type & BTRFS_BLOCK_GROUP_DATA) && !fs_info->stripe_root) {
1570		btrfs_err(fs_info, "zoned: data %s needs raid-stripe-tree",
1571			  btrfs_bg_type_to_raid_name(map->type));
1572		return -EINVAL;
1573	}
1574
1575	/*
1576	 * When the last extent is removed, last_alloc can be smaller than the other write
1577	 * pointer. In that case, last_alloc should be moved to the corresponding write
1578	 * pointer position.
1579	 */
1580	for (int i = 0; i < map->num_stripes; i++) {
1581		u64 alloc;
1582
1583		if (zone_info[i].alloc_offset == WP_MISSING_DEV ||
1584		    zone_info[i].alloc_offset == WP_CONVENTIONAL)
1585			continue;
1586
1587		stripe_nr = zone_info[i].alloc_offset >> BTRFS_STRIPE_LEN_SHIFT;
1588		stripe_offset = zone_info[i].alloc_offset & BTRFS_STRIPE_LEN_MASK;
1589		if (stripe_offset == 0 && stripe_nr > 0) {
1590			stripe_nr--;
1591			stripe_offset = BTRFS_STRIPE_LEN;
1592		}
1593		alloc = ((stripe_nr * map->num_stripes + i) << BTRFS_STRIPE_LEN_SHIFT) +
1594			stripe_offset;
1595		last_alloc = max(last_alloc, alloc);
1596
1597		/* Partially written stripe found. It should be last. */
1598		if (zone_info[i].alloc_offset & BTRFS_STRIPE_LEN_MASK)
1599			break;
1600	}
1601	stripe_nr = 0;
1602	stripe_offset = 0;
1603
1604	if (last_alloc) {
1605		u32 factor = map->num_stripes;
1606
1607		stripe_nr = last_alloc >> BTRFS_STRIPE_LEN_SHIFT;
1608		stripe_offset = last_alloc & BTRFS_STRIPE_LEN_MASK;
1609		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
1610	}
1611
1612	for (int i = 0; i < map->num_stripes; i++) {
1613		if (zone_info[i].alloc_offset == WP_MISSING_DEV)
1614			continue;
1615
1616		if (zone_info[i].alloc_offset == WP_CONVENTIONAL) {
1617			has_conventional = true;
1618			zone_info[i].alloc_offset = btrfs_stripe_nr_to_offset(stripe_nr);
1619
1620			if (stripe_index > i)
1621				zone_info[i].alloc_offset += BTRFS_STRIPE_LEN;
1622			else if (stripe_index == i)
1623				zone_info[i].alloc_offset += stripe_offset;
1624		}
1625
1626		/* Verification */
1627		if (i != 0) {
1628			if (unlikely(prev_offset < zone_info[i].alloc_offset)) {
1629				btrfs_err(fs_info,
1630				"zoned: stripe position disorder found in block group %llu",
1631					  bg->start);
1632				return -EIO;
1633			}
1634
1635			if (unlikely(has_partial &&
1636				     (zone_info[i].alloc_offset & BTRFS_STRIPE_LEN_MASK))) {
1637				btrfs_err(fs_info,
1638				"zoned: multiple partial written stripe found in block group %llu",
1639					  bg->start);
1640				return -EIO;
1641			}
1642		}
1643		prev_offset = zone_info[i].alloc_offset;
1644
1645		if ((zone_info[i].alloc_offset & BTRFS_STRIPE_LEN_MASK) != 0)
1646			has_partial = true;
1647
1648		if (test_bit(0, active) != test_bit(i, active)) {
1649			if (unlikely(!btrfs_zone_activate(bg)))
1650				return -EIO;
1651		} else {
1652			if (test_bit(0, active))
1653				set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &bg->runtime_flags);
1654		}
1655		bg->zone_capacity += zone_info[i].capacity;
1656		bg->alloc_offset += zone_info[i].alloc_offset;
1657	}
1658
1659	/* Check if all devices stay in the same stripe row. */
1660	if (unlikely(zone_info[0].alloc_offset -
1661		     zone_info[map->num_stripes - 1].alloc_offset > BTRFS_STRIPE_LEN)) {
1662		btrfs_err(fs_info, "zoned: stripe gap too large in block group %llu", bg->start);
1663		return -EIO;
1664	}
1665
1666	if (unlikely(has_conventional && bg->alloc_offset < last_alloc)) {
1667		btrfs_err(fs_info, "zoned: allocated extent stays beyond write pointers %llu %llu",
1668			  bg->alloc_offset, last_alloc);
1669		return -EIO;
1670	}
1671
1672	return 0;
1673}
1674
1675static int btrfs_load_block_group_raid10(struct btrfs_block_group *bg,
1676					 struct btrfs_chunk_map *map,
1677					 struct zone_info *zone_info,
1678					 unsigned long *active,
1679					 u64 last_alloc)
1680{
1681	struct btrfs_fs_info *fs_info = bg->fs_info;
1682	u64 AUTO_KFREE(raid0_allocs);
1683	u64 stripe_nr = 0, stripe_offset = 0;
1684	u32 stripe_index = 0;
1685	bool has_partial = false, has_conventional = false;
1686	u64 prev_offset = 0;
1687
1688	if ((map->type & BTRFS_BLOCK_GROUP_DATA) && !fs_info->stripe_root) {
1689		btrfs_err(fs_info, "zoned: data %s needs raid-stripe-tree",
1690			  btrfs_bg_type_to_raid_name(map->type));
1691		return -EINVAL;
1692	}
1693
1694	raid0_allocs = kcalloc(map->num_stripes / map->sub_stripes, sizeof(*raid0_allocs),
1695			       GFP_NOFS);
1696	if (!raid0_allocs)
1697		return -ENOMEM;
1698
1699	/*
1700	 * When the last extent is removed, last_alloc can be smaller than the other write
1701	 * pointer. In that case, last_alloc should be moved to the corresponding write
1702	 * pointer position.
1703	 */
1704	for (int i = 0; i < map->num_stripes; i += map->sub_stripes) {
1705		u64 alloc = zone_info[i].alloc_offset;
1706
1707		for (int j = 1; j < map->sub_stripes; j++) {
1708			int idx = i + j;
1709
1710			if (zone_info[idx].alloc_offset == WP_MISSING_DEV ||
1711			    zone_info[idx].alloc_offset == WP_CONVENTIONAL)
1712				continue;
1713			if (alloc == WP_MISSING_DEV || alloc == WP_CONVENTIONAL) {
1714				alloc = zone_info[idx].alloc_offset;
1715			} else if (unlikely(zone_info[idx].alloc_offset != alloc)) {
1716				btrfs_err(fs_info,
1717				"zoned: write pointer mismatch found in block group %llu",
1718					  bg->start);
1719				return -EIO;
1720			}
1721		}
1722
1723		raid0_allocs[i / map->sub_stripes] = alloc;
1724		if (alloc == WP_CONVENTIONAL)
1725			continue;
1726		if (unlikely(alloc == WP_MISSING_DEV)) {
1727			btrfs_err(fs_info,
1728			"zoned: cannot recover write pointer of block group %llu due to missing device",
1729				  bg->start);
1730			return -EIO;
1731		}
1732
1733		stripe_nr = alloc >> BTRFS_STRIPE_LEN_SHIFT;
1734		stripe_offset = alloc & BTRFS_STRIPE_LEN_MASK;
1735		if (stripe_offset == 0 && stripe_nr > 0) {
1736			stripe_nr--;
1737			stripe_offset = BTRFS_STRIPE_LEN;
1738		}
1739
1740		alloc = ((stripe_nr * (map->num_stripes / map->sub_stripes) +
1741			  (i / map->sub_stripes)) <<
1742			 BTRFS_STRIPE_LEN_SHIFT) + stripe_offset;
1743		last_alloc = max(last_alloc, alloc);
1744	}
1745	stripe_nr = 0;
1746	stripe_offset = 0;
1747
1748	if (last_alloc) {
1749		u32 factor = map->num_stripes / map->sub_stripes;
1750
1751		stripe_nr = last_alloc >> BTRFS_STRIPE_LEN_SHIFT;
1752		stripe_offset = last_alloc & BTRFS_STRIPE_LEN_MASK;
1753		stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
1754	}
1755
1756	for (int i = 0; i < map->num_stripes; i++) {
1757		int idx = i / map->sub_stripes;
1758
1759		if (raid0_allocs[idx] == WP_CONVENTIONAL) {
1760			has_conventional = true;
1761			raid0_allocs[idx] = btrfs_stripe_nr_to_offset(stripe_nr);
1762
1763			if (stripe_index > idx)
1764				raid0_allocs[idx] += BTRFS_STRIPE_LEN;
1765			else if (stripe_index == idx)
1766				raid0_allocs[idx] += stripe_offset;
1767		}
1768
1769		if ((i % map->sub_stripes) == 0) {
1770			/* Verification */
1771			if (i != 0) {
1772				if (unlikely(prev_offset < raid0_allocs[idx])) {
1773					btrfs_err(fs_info,
1774					"zoned: stripe position disorder found in block group %llu",
1775						  bg->start);
1776					return -EIO;
1777				}
1778
1779				if (unlikely(has_partial &&
1780					     (raid0_allocs[idx] & BTRFS_STRIPE_LEN_MASK))) {
1781					btrfs_err(fs_info,
1782					"zoned: multiple partial written stripe found in block group %llu",
1783						  bg->start);
1784					return -EIO;
1785				}
1786			}
1787			prev_offset = raid0_allocs[idx];
1788
1789			if ((raid0_allocs[idx] & BTRFS_STRIPE_LEN_MASK) != 0)
1790				has_partial = true;
1791		}
1792
1793		if (zone_info[i].alloc_offset == WP_MISSING_DEV ||
1794		    zone_info[i].alloc_offset == WP_CONVENTIONAL)
1795			zone_info[i].alloc_offset = raid0_allocs[idx];
1796
1797		if (test_bit(0, active) != test_bit(i, active)) {
1798			if (unlikely(!btrfs_zone_activate(bg)))
1799				return -EIO;
1800		} else if (test_bit(0, active)) {
1801			set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &bg->runtime_flags);
1802		}
1803
1804		if ((i % map->sub_stripes) == 0) {
1805			bg->zone_capacity += zone_info[i].capacity;
1806			bg->alloc_offset += zone_info[i].alloc_offset;
1807		}
1808	}
1809
1810	/* Check if all devices stay in the same stripe row. */
1811	if (unlikely(zone_info[0].alloc_offset -
1812		     zone_info[map->num_stripes - 1].alloc_offset > BTRFS_STRIPE_LEN)) {
1813		btrfs_err(fs_info, "zoned: stripe gap too large in block group %llu",
1814			  bg->start);
1815		return -EIO;
1816	}
1817
1818	if (unlikely(has_conventional && bg->alloc_offset < last_alloc)) {
1819		btrfs_err(fs_info, "zoned: allocated extent stays beyond write pointers %llu %llu",
1820			  bg->alloc_offset, last_alloc);
1821		return -EIO;
1822	}
1823
1824	return 0;
1825}
1826
1827int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new)
1828{
1829	struct btrfs_fs_info *fs_info = cache->fs_info;
1830	struct btrfs_chunk_map *map;
1831	u64 logical = cache->start;
1832	u64 length = cache->length;
1833	struct zone_info AUTO_KFREE(zone_info);
1834	int ret;
1835	int i;
1836	unsigned long *active = NULL;
1837	u64 last_alloc = 0;
1838	u32 num_sequential = 0, num_conventional = 0;
1839	u64 profile;
1840
1841	if (!btrfs_is_zoned(fs_info))
1842		return 0;
1843
1844	/* Sanity check */
1845	if (unlikely(!IS_ALIGNED(length, fs_info->zone_size))) {
1846		btrfs_err(fs_info,
1847		"zoned: block group %llu len %llu unaligned to zone size %llu",
1848			  logical, length, fs_info->zone_size);
1849		return -EIO;
1850	}
1851
1852	map = btrfs_find_chunk_map(fs_info, logical, length);
1853	if (!map)
1854		return -EINVAL;
1855
1856	cache->physical_map = map;
1857
1858	zone_info = kcalloc(map->num_stripes, sizeof(*zone_info), GFP_NOFS);
1859	if (!zone_info) {
1860		ret = -ENOMEM;
1861		goto out;
1862	}
1863
1864	active = bitmap_zalloc(map->num_stripes, GFP_NOFS);
1865	if (!active) {
1866		ret = -ENOMEM;
1867		goto out;
1868	}
1869
1870	for (i = 0; i < map->num_stripes; i++) {
1871		ret = btrfs_load_zone_info(fs_info, i, &zone_info[i], active, map, new);
1872		if (ret)
1873			goto out;
1874
1875		if (zone_info[i].alloc_offset == WP_CONVENTIONAL)
1876			num_conventional++;
1877		else
1878			num_sequential++;
1879	}
1880
1881	if (num_sequential > 0)
1882		set_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &cache->runtime_flags);
1883
1884	if (num_conventional > 0) {
1885		ret = calculate_alloc_pointer(cache, &last_alloc, new);
1886		if (ret) {
1887			btrfs_err(fs_info,
1888			"zoned: failed to determine allocation offset of bg %llu",
1889				  cache->start);
1890			goto out;
1891		} else if (map->num_stripes == num_conventional) {
1892			cache->alloc_offset = last_alloc;
1893			cache->zone_capacity = cache->length;
1894			set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags);
1895			goto out;
1896		}
1897	}
1898
1899	profile = map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK;
1900	switch (profile) {
1901	case 0: /* single */
1902		ret = btrfs_load_block_group_single(cache, &zone_info[0], active);
1903		break;
1904	case BTRFS_BLOCK_GROUP_DUP:
1905		ret = btrfs_load_block_group_dup(cache, map, zone_info, active,
1906						 last_alloc);
1907		break;
1908	case BTRFS_BLOCK_GROUP_RAID1:
1909	case BTRFS_BLOCK_GROUP_RAID1C3:
1910	case BTRFS_BLOCK_GROUP_RAID1C4:
1911		ret = btrfs_load_block_group_raid1(cache, map, zone_info,
1912						   active, last_alloc);
1913		break;
1914	case BTRFS_BLOCK_GROUP_RAID0:
1915		ret = btrfs_load_block_group_raid0(cache, map, zone_info,
1916						   active, last_alloc);
1917		break;
1918	case BTRFS_BLOCK_GROUP_RAID10:
1919		ret = btrfs_load_block_group_raid10(cache, map, zone_info,
1920						    active, last_alloc);
1921		break;
1922	case BTRFS_BLOCK_GROUP_RAID5:
1923	case BTRFS_BLOCK_GROUP_RAID6:
1924	default:
1925		btrfs_err(fs_info, "zoned: profile %s not yet supported",
1926			  btrfs_bg_type_to_raid_name(map->type));
1927		ret = -EINVAL;
1928		goto out;
1929	}
1930
1931	if (ret == -EIO && profile != 0 && profile != BTRFS_BLOCK_GROUP_RAID0 &&
1932	    profile != BTRFS_BLOCK_GROUP_RAID10) {
1933		/*
1934		 * Detected broken write pointer.  Make this block group
1935		 * unallocatable by setting the allocation pointer at the end of
1936		 * allocatable region. Relocating this block group will fix the
1937		 * mismatch.
1938		 *
1939		 * Currently, we cannot handle RAID0 or RAID10 case like this
1940		 * because we don't have a proper zone_capacity value. But,
1941		 * reading from this block group won't work anyway by a missing
1942		 * stripe.
1943		 */
1944		cache->alloc_offset = cache->zone_capacity;
1945	}
1946
1947out:
1948	/* Reject non SINGLE data profiles without RST */
1949	if ((map->type & BTRFS_BLOCK_GROUP_DATA) &&
1950	    (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) &&
1951	    !fs_info->stripe_root) {
1952		btrfs_err(fs_info, "zoned: data %s needs raid-stripe-tree",
1953			  btrfs_bg_type_to_raid_name(map->type));
1954		ret = -EINVAL;
1955	}
1956
1957	if (unlikely(cache->alloc_offset > cache->zone_capacity)) {
1958		btrfs_err(fs_info,
1959"zoned: invalid write pointer %llu (larger than zone capacity %llu) in block group %llu",
1960			  cache->alloc_offset, cache->zone_capacity,
1961			  cache->start);
1962		ret = -EIO;
1963	}
1964
1965	/* An extent is allocated after the write pointer */
1966	if (!ret && num_conventional && last_alloc > cache->alloc_offset) {
1967		btrfs_err(fs_info,
1968			  "zoned: got wrong write pointer in BG %llu: %llu > %llu",
1969			  logical, last_alloc, cache->alloc_offset);
1970		ret = -EIO;
1971	}
1972
1973	if (!ret) {
1974		cache->meta_write_pointer = cache->alloc_offset + cache->start;
1975		if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags)) {
1976			btrfs_get_block_group(cache);
1977			spin_lock(&fs_info->zone_active_bgs_lock);
1978			list_add_tail(&cache->active_bg_list,
1979				      &fs_info->zone_active_bgs);
1980			spin_unlock(&fs_info->zone_active_bgs_lock);
1981		}
1982	} else {
1983		btrfs_free_chunk_map(cache->physical_map);
1984		cache->physical_map = NULL;
1985	}
1986	bitmap_free(active);
1987
1988	return ret;
1989}
1990
1991void btrfs_calc_zone_unusable(struct btrfs_block_group *cache)
1992{
1993	u64 unusable, free;
1994
1995	if (!btrfs_is_zoned(cache->fs_info))
1996		return;
1997
1998	WARN_ON(cache->bytes_super != 0);
1999	unusable = (cache->alloc_offset - cache->used) +
2000		   (cache->length - cache->zone_capacity);
2001	free = cache->zone_capacity - cache->alloc_offset;
2002
2003	/* We only need ->free_space in ALLOC_SEQ block groups */
2004	cache->cached = BTRFS_CACHE_FINISHED;
2005	cache->free_space_ctl->free_space = free;
2006	cache->zone_unusable = unusable;
2007}
2008
2009bool btrfs_use_zone_append(struct btrfs_bio *bbio)
2010{
2011	u64 start = (bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT);
2012	struct btrfs_inode *inode = bbio->inode;
2013	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2014	struct btrfs_block_group *cache;
2015	bool ret = false;
2016
2017	if (!btrfs_is_zoned(fs_info))
2018		return false;
2019
2020	if (!is_data_inode(inode))
2021		return false;
2022
2023	if (btrfs_op(&bbio->bio) != BTRFS_MAP_WRITE)
2024		return false;
2025
2026	/*
2027	 * Using REQ_OP_ZONE_APPEND for relocation can break assumptions on the
2028	 * extent layout the relocation code has.
2029	 * Furthermore we have set aside own block-group from which only the
2030	 * relocation "process" can allocate and make sure only one process at a
2031	 * time can add pages to an extent that gets relocated, so it's safe to
2032	 * use regular REQ_OP_WRITE for this special case.
2033	 */
2034	if (btrfs_is_data_reloc_root(inode->root))
2035		return false;
2036
2037	cache = btrfs_lookup_block_group(fs_info, start);
2038	ASSERT(cache);
2039	if (!cache)
2040		return false;
2041
2042	ret = !!test_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &cache->runtime_flags);
2043	btrfs_put_block_group(cache);
2044
2045	return ret;
2046}
2047
2048void btrfs_record_physical_zoned(struct btrfs_bio *bbio)
2049{
2050	const u64 physical = bbio->bio.bi_iter.bi_sector << SECTOR_SHIFT;
2051	struct btrfs_ordered_sum *sum = bbio->sums;
2052
2053	if (physical < bbio->orig_physical)
2054		sum->logical -= bbio->orig_physical - physical;
2055	else
2056		sum->logical += physical - bbio->orig_physical;
2057}
2058
2059static void btrfs_rewrite_logical_zoned(struct btrfs_ordered_extent *ordered,
2060					u64 logical)
2061{
2062	struct extent_map_tree *em_tree = &ordered->inode->extent_tree;
2063	struct extent_map *em;
2064
2065	ordered->disk_bytenr = logical;
2066
2067	write_lock(&em_tree->lock);
2068	em = btrfs_search_extent_mapping(em_tree, ordered->file_offset,
2069					 ordered->num_bytes);
2070	/* The em should be a new COW extent, thus it should not have an offset. */
2071	ASSERT(em->offset == 0, "em->offset=%llu", em->offset);
2072	em->disk_bytenr = logical;
2073	btrfs_free_extent_map(em);
2074	write_unlock(&em_tree->lock);
2075}
2076
2077static bool btrfs_zoned_split_ordered(struct btrfs_ordered_extent *ordered,
2078				      u64 logical, u64 len)
2079{
2080	struct btrfs_ordered_extent *new;
2081
2082	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags) &&
2083	    btrfs_split_extent_map(ordered->inode, ordered->file_offset,
2084				   ordered->num_bytes, len, logical))
2085		return false;
2086
2087	new = btrfs_split_ordered_extent(ordered, len);
2088	if (IS_ERR(new))
2089		return false;
2090	new->disk_bytenr = logical;
2091	btrfs_finish_one_ordered(new);
2092	return true;
2093}
2094
2095void btrfs_finish_ordered_zoned(struct btrfs_ordered_extent *ordered)
2096{
2097	struct btrfs_inode *inode = ordered->inode;
2098	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2099	struct btrfs_ordered_sum *sum;
2100	u64 logical, len;
2101
2102	/*
2103	 * Write to pre-allocated region is for the data relocation, and so
2104	 * it should use WRITE operation. No split/rewrite are necessary.
2105	 */
2106	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags))
2107		return;
2108
2109	ASSERT(!list_empty(&ordered->list));
2110	/* The ordered->list can be empty in the above pre-alloc case. */
2111	sum = list_first_entry(&ordered->list, struct btrfs_ordered_sum, list);
2112	logical = sum->logical;
2113	len = sum->len;
2114
2115	while (len < ordered->disk_num_bytes) {
2116		sum = list_next_entry(sum, list);
2117		if (sum->logical == logical + len) {
2118			len += sum->len;
2119			continue;
2120		}
2121		if (!btrfs_zoned_split_ordered(ordered, logical, len)) {
2122			set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
2123			btrfs_err(fs_info, "failed to split ordered extent");
2124			goto out;
2125		}
2126		logical = sum->logical;
2127		len = sum->len;
2128	}
2129
2130	if (ordered->disk_bytenr != logical)
2131		btrfs_rewrite_logical_zoned(ordered, logical);
2132
2133out:
2134	/*
2135	 * If we end up here for nodatasum I/O, the btrfs_ordered_sum structures
2136	 * were allocated by btrfs_alloc_dummy_sum only to record the logical
2137	 * addresses and don't contain actual checksums.  We thus must free them
2138	 * here so that we don't attempt to log the csums later.
2139	 */
2140	if ((inode->flags & BTRFS_INODE_NODATASUM) ||
2141	    test_bit(BTRFS_FS_STATE_NO_DATA_CSUMS, &fs_info->fs_state)) {
2142		while ((sum = list_first_entry_or_null(&ordered->list,
2143						       typeof(*sum), list))) {
2144			list_del(&sum->list);
2145			kfree(sum);
2146		}
2147	}
2148}
2149
2150static bool check_bg_is_active(struct btrfs_eb_write_context *ctx,
2151			       struct btrfs_block_group **active_bg)
2152{
2153	const struct writeback_control *wbc = ctx->wbc;
2154	struct btrfs_block_group *block_group = ctx->zoned_bg;
2155	struct btrfs_fs_info *fs_info = block_group->fs_info;
2156
2157	if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags))
2158		return true;
2159
2160	if (fs_info->treelog_bg == block_group->start) {
2161		if (!btrfs_zone_activate(block_group)) {
2162			int ret_fin = btrfs_zone_finish_one_bg(fs_info);
2163
2164			if (ret_fin != 1 || !btrfs_zone_activate(block_group))
2165				return false;
2166		}
2167	} else if (*active_bg != block_group) {
2168		struct btrfs_block_group *tgt = *active_bg;
2169
2170		/* zoned_meta_io_lock protects fs_info->active_{meta,system}_bg. */
2171		lockdep_assert_held(&fs_info->zoned_meta_io_lock);
2172
2173		if (tgt) {
2174			/*
2175			 * If there is an unsent IO left in the allocated area,
2176			 * we cannot wait for them as it may cause a deadlock.
2177			 */
2178			if (tgt->meta_write_pointer < tgt->start + tgt->alloc_offset) {
2179				if (wbc->sync_mode == WB_SYNC_NONE ||
2180				    (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync))
2181					return false;
2182			}
2183
2184			/* Pivot active metadata/system block group. */
2185			btrfs_zoned_meta_io_unlock(fs_info);
2186			wait_eb_writebacks(tgt);
2187			do_zone_finish(tgt, true);
2188			btrfs_zoned_meta_io_lock(fs_info);
2189			if (*active_bg == tgt) {
2190				btrfs_put_block_group(tgt);
2191				*active_bg = NULL;
2192			}
2193		}
2194		if (!btrfs_zone_activate(block_group))
2195			return false;
2196		if (*active_bg != block_group) {
2197			ASSERT(*active_bg == NULL);
2198			*active_bg = block_group;
2199			btrfs_get_block_group(block_group);
2200		}
2201	}
2202
2203	return true;
2204}
2205
2206/*
2207 * Check if @ctx->eb is aligned to the write pointer.
2208 *
2209 * Return:
2210 *   0:        @ctx->eb is at the write pointer. You can write it.
2211 *   -EAGAIN:  There is a hole. The caller should handle the case.
2212 *   -EBUSY:   There is a hole, but the caller can just bail out.
2213 */
2214int btrfs_check_meta_write_pointer(struct btrfs_fs_info *fs_info,
2215				   struct btrfs_eb_write_context *ctx)
2216{
2217	const struct writeback_control *wbc = ctx->wbc;
2218	const struct extent_buffer *eb = ctx->eb;
2219	struct btrfs_block_group *block_group = ctx->zoned_bg;
2220
2221	if (!btrfs_is_zoned(fs_info))
2222		return 0;
2223
2224	if (block_group) {
2225		if (block_group->start > eb->start ||
2226		    block_group->start + block_group->length <= eb->start) {
2227			btrfs_put_block_group(block_group);
2228			block_group = NULL;
2229			ctx->zoned_bg = NULL;
2230		}
2231	}
2232
2233	if (!block_group) {
2234		block_group = btrfs_lookup_block_group(fs_info, eb->start);
2235		if (!block_group)
2236			return 0;
2237		ctx->zoned_bg = block_group;
2238	}
2239
2240	if (block_group->meta_write_pointer == eb->start) {
2241		struct btrfs_block_group **tgt;
2242
2243		if (!test_bit(BTRFS_FS_ACTIVE_ZONE_TRACKING, &fs_info->flags))
2244			return 0;
2245
2246		if (block_group->flags & BTRFS_BLOCK_GROUP_SYSTEM)
2247			tgt = &fs_info->active_system_bg;
2248		else
2249			tgt = &fs_info->active_meta_bg;
2250		if (check_bg_is_active(ctx, tgt))
2251			return 0;
2252	}
2253
2254	/*
2255	 * Since we may release fs_info->zoned_meta_io_lock, someone can already
2256	 * start writing this eb. In that case, we can just bail out.
2257	 */
2258	if (block_group->meta_write_pointer > eb->start)
2259		return -EBUSY;
2260
2261	/* If for_sync, this hole will be filled with transaction commit. */
2262	if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
2263		return -EAGAIN;
2264	return -EBUSY;
2265}
2266
2267int btrfs_zoned_issue_zeroout(struct btrfs_device *device, u64 physical, u64 length)
2268{
2269	if (!btrfs_dev_is_sequential(device, physical))
2270		return -EOPNOTSUPP;
2271
2272	return blkdev_issue_zeroout(device->bdev, physical >> SECTOR_SHIFT,
2273				    length >> SECTOR_SHIFT, GFP_NOFS, 0);
2274}
2275
2276static int read_zone_info(struct btrfs_fs_info *fs_info, u64 logical,
2277			  struct blk_zone *zone)
2278{
2279	struct btrfs_io_context *bioc = NULL;
2280	u64 mapped_length = PAGE_SIZE;
2281	unsigned int nofs_flag;
2282	int nmirrors;
2283	int i, ret;
2284
2285	ret = btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
2286			      &mapped_length, &bioc, NULL, NULL);
2287	if (unlikely(ret || !bioc || mapped_length < PAGE_SIZE)) {
2288		ret = -EIO;
2289		goto out_put_bioc;
2290	}
2291
2292	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
2293		ret = -EINVAL;
2294		goto out_put_bioc;
2295	}
2296
2297	nofs_flag = memalloc_nofs_save();
2298	nmirrors = (int)bioc->num_stripes;
2299	for (i = 0; i < nmirrors; i++) {
2300		u64 physical = bioc->stripes[i].physical;
2301		struct btrfs_device *dev = bioc->stripes[i].dev;
2302
2303		/* Missing device */
2304		if (!dev->bdev)
2305			continue;
2306
2307		ret = btrfs_get_dev_zone(dev, physical, zone);
2308		/* Failing device */
2309		if (ret == -EIO || ret == -EOPNOTSUPP)
2310			continue;
2311		break;
2312	}
2313	memalloc_nofs_restore(nofs_flag);
2314out_put_bioc:
2315	btrfs_put_bioc(bioc);
2316	return ret;
2317}
2318
2319/*
2320 * Synchronize write pointer in a zone at @physical_start on @tgt_dev, by
2321 * filling zeros between @physical_pos to a write pointer of dev-replace
2322 * source device.
2323 */
2324int btrfs_sync_zone_write_pointer(struct btrfs_device *tgt_dev, u64 logical,
2325				    u64 physical_start, u64 physical_pos)
2326{
2327	struct btrfs_fs_info *fs_info = tgt_dev->fs_info;
2328	struct blk_zone zone;
2329	u64 length;
2330	u64 wp;
2331	int ret;
2332
2333	if (!btrfs_dev_is_sequential(tgt_dev, physical_pos))
2334		return 0;
2335
2336	ret = read_zone_info(fs_info, logical, &zone);
2337	if (ret)
2338		return ret;
2339
2340	wp = physical_start + ((zone.wp - zone.start) << SECTOR_SHIFT);
2341
2342	if (physical_pos == wp)
2343		return 0;
2344
2345	if (unlikely(physical_pos > wp))
2346		return -EUCLEAN;
2347
2348	length = wp - physical_pos;
2349	return btrfs_zoned_issue_zeroout(tgt_dev, physical_pos, length);
2350}
2351
2352/*
2353 * Activate block group and underlying device zones
2354 *
2355 * @block_group: the block group to activate
2356 *
2357 * Return: true on success, false otherwise
2358 */
2359bool btrfs_zone_activate(struct btrfs_block_group *block_group)
2360{
2361	struct btrfs_fs_info *fs_info = block_group->fs_info;
2362	struct btrfs_chunk_map *map;
2363	struct btrfs_device *device;
2364	u64 physical;
2365	const bool is_data = (block_group->flags & BTRFS_BLOCK_GROUP_DATA);
2366	bool ret;
2367	int i;
2368
2369	if (!btrfs_is_zoned(block_group->fs_info))
2370		return true;
2371
2372	map = block_group->physical_map;
2373
2374	spin_lock(&fs_info->zone_active_bgs_lock);
2375	spin_lock(&block_group->lock);
2376	if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
2377		ret = true;
2378		goto out_unlock;
2379	}
2380
2381	if (block_group->flags & BTRFS_BLOCK_GROUP_DATA) {
2382		/* The caller should check if the block group is full. */
2383		if (WARN_ON_ONCE(btrfs_zoned_bg_is_full(block_group))) {
2384			ret = false;
2385			goto out_unlock;
2386		}
2387	} else {
2388		/* Since it is already written, it should have been active. */
2389		WARN_ON_ONCE(block_group->meta_write_pointer != block_group->start);
2390	}
2391
2392	for (i = 0; i < map->num_stripes; i++) {
2393		struct btrfs_zoned_device_info *zinfo;
2394		int reserved = 0;
2395
2396		device = map->stripes[i].dev;
2397		physical = map->stripes[i].physical;
2398		zinfo = device->zone_info;
2399
2400		if (!device->bdev)
2401			continue;
2402
2403		if (zinfo->max_active_zones == 0)
2404			continue;
2405
2406		if (is_data)
2407			reserved = zinfo->reserved_active_zones;
2408		/*
2409		 * For the data block group, leave active zones for one
2410		 * metadata block group and one system block group.
2411		 */
2412		if (atomic_read(&zinfo->active_zones_left) <= reserved) {
2413			ret = false;
2414			goto out_unlock;
2415		}
2416
2417		if (!btrfs_dev_set_active_zone(device, physical)) {
2418			/* Cannot activate the zone */
2419			ret = false;
2420			goto out_unlock;
2421		}
2422		if (!is_data)
2423			zinfo->reserved_active_zones--;
2424	}
2425
2426	/* Successfully activated all the zones */
2427	set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
2428	spin_unlock(&block_group->lock);
2429
2430	/* For the active block group list */
2431	btrfs_get_block_group(block_group);
2432	list_add_tail(&block_group->active_bg_list, &fs_info->zone_active_bgs);
2433	spin_unlock(&fs_info->zone_active_bgs_lock);
2434
2435	return true;
2436
2437out_unlock:
2438	spin_unlock(&block_group->lock);
2439	spin_unlock(&fs_info->zone_active_bgs_lock);
2440	return ret;
2441}
2442
2443static void wait_eb_writebacks(struct btrfs_block_group *block_group)
2444{
2445	struct btrfs_fs_info *fs_info = block_group->fs_info;
2446	const u64 end = block_group->start + block_group->length;
2447	struct extent_buffer *eb;
2448	unsigned long index, start = (block_group->start >> fs_info->nodesize_bits);
2449
2450	rcu_read_lock();
2451	xa_for_each_start(&fs_info->buffer_tree, index, eb, start) {
2452		if (eb->start < block_group->start)
2453			continue;
2454		if (eb->start >= end)
2455			break;
2456		rcu_read_unlock();
2457		wait_on_extent_buffer_writeback(eb);
2458		rcu_read_lock();
2459	}
2460	rcu_read_unlock();
2461}
2462
2463static int call_zone_finish(struct btrfs_block_group *block_group,
2464			    struct btrfs_io_stripe *stripe)
2465{
2466	struct btrfs_device *device = stripe->dev;
2467	const u64 physical = stripe->physical;
2468	struct btrfs_zoned_device_info *zinfo = device->zone_info;
2469	int ret;
2470
2471	if (!device->bdev)
2472		return 0;
2473
2474	if (zinfo->max_active_zones == 0)
2475		return 0;
2476
2477	if (btrfs_dev_is_sequential(device, physical)) {
2478		unsigned int nofs_flags;
2479
2480		nofs_flags = memalloc_nofs_save();
2481		ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_FINISH,
2482				       physical >> SECTOR_SHIFT,
2483				       zinfo->zone_size >> SECTOR_SHIFT);
2484		memalloc_nofs_restore(nofs_flags);
2485
2486		if (ret)
2487			return ret;
2488	}
2489
2490	if (!(block_group->flags & BTRFS_BLOCK_GROUP_DATA))
2491		zinfo->reserved_active_zones++;
2492	btrfs_dev_clear_active_zone(device, physical);
2493
2494	return 0;
2495}
2496
2497static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_written)
2498{
2499	struct btrfs_fs_info *fs_info = block_group->fs_info;
2500	struct btrfs_chunk_map *map;
2501	const bool is_metadata = (block_group->flags &
2502			(BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM));
2503	struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
2504	int ret = 0;
2505	int i;
2506
2507	spin_lock(&block_group->lock);
2508	if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
2509		spin_unlock(&block_group->lock);
2510		return 0;
2511	}
2512
2513	/* Check if we have unwritten allocated space */
2514	if (is_metadata &&
2515	    block_group->start + block_group->alloc_offset > block_group->meta_write_pointer) {
2516		spin_unlock(&block_group->lock);
2517		return -EAGAIN;
2518	}
2519
2520	/*
2521	 * If we are sure that the block group is full (= no more room left for
2522	 * new allocation) and the IO for the last usable block is completed, we
2523	 * don't need to wait for the other IOs. This holds because we ensure
2524	 * the sequential IO submissions using the ZONE_APPEND command for data
2525	 * and block_group->meta_write_pointer for metadata.
2526	 */
2527	if (!fully_written) {
2528		if (test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags)) {
2529			spin_unlock(&block_group->lock);
2530			return -EAGAIN;
2531		}
2532		spin_unlock(&block_group->lock);
2533
2534		ret = btrfs_inc_block_group_ro(block_group, false);
2535		if (ret)
2536			return ret;
2537
2538		/* Ensure all writes in this block group finish */
2539		btrfs_wait_block_group_reservations(block_group);
2540		/* No need to wait for NOCOW writers. Zoned mode does not allow that */
2541		btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group);
2542		/* Wait for extent buffers to be written. */
2543		if (is_metadata)
2544			wait_eb_writebacks(block_group);
2545
2546		spin_lock(&block_group->lock);
2547
2548		/*
2549		 * Bail out if someone already deactivated the block group, or
2550		 * allocated space is left in the block group.
2551		 */
2552		if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2553			      &block_group->runtime_flags)) {
2554			spin_unlock(&block_group->lock);
2555			btrfs_dec_block_group_ro(block_group);
2556			return 0;
2557		}
2558
2559		if (block_group->reserved ||
2560		    test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC,
2561			     &block_group->runtime_flags)) {
2562			spin_unlock(&block_group->lock);
2563			btrfs_dec_block_group_ro(block_group);
2564			return -EAGAIN;
2565		}
2566	}
2567
2568	clear_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
2569	block_group->alloc_offset = block_group->zone_capacity;
2570	if (block_group->flags & (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM))
2571		block_group->meta_write_pointer = block_group->start +
2572						  block_group->zone_capacity;
2573	block_group->free_space_ctl->free_space = 0;
2574	btrfs_clear_treelog_bg(block_group);
2575	btrfs_clear_data_reloc_bg(block_group);
2576	spin_unlock(&block_group->lock);
2577
2578	down_read(&dev_replace->rwsem);
2579	map = block_group->physical_map;
2580	for (i = 0; i < map->num_stripes; i++) {
2581
2582		ret = call_zone_finish(block_group, &map->stripes[i]);
2583		if (ret) {
2584			up_read(&dev_replace->rwsem);
2585			return ret;
2586		}
2587	}
2588	up_read(&dev_replace->rwsem);
2589
2590	if (!fully_written)
2591		btrfs_dec_block_group_ro(block_group);
2592
2593	spin_lock(&fs_info->zone_active_bgs_lock);
2594	ASSERT(!list_empty(&block_group->active_bg_list));
2595	list_del_init(&block_group->active_bg_list);
2596	spin_unlock(&fs_info->zone_active_bgs_lock);
2597
2598	/* For active_bg_list */
2599	btrfs_put_block_group(block_group);
2600
2601	clear_and_wake_up_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2602
2603	return 0;
2604}
2605
2606int btrfs_zone_finish(struct btrfs_block_group *block_group)
2607{
2608	if (!btrfs_is_zoned(block_group->fs_info))
2609		return 0;
2610
2611	return do_zone_finish(block_group, false);
2612}
2613
2614bool btrfs_can_activate_zone(struct btrfs_fs_devices *fs_devices, u64 flags)
2615{
2616	struct btrfs_fs_info *fs_info = fs_devices->fs_info;
2617	struct btrfs_device *device;
2618	bool ret = false;
2619
2620	if (!btrfs_is_zoned(fs_info))
2621		return true;
2622
2623	if (test_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags))
2624		return false;
2625
2626	/* Check if there is a device with active zones left */
2627	mutex_lock(&fs_info->chunk_mutex);
2628	spin_lock(&fs_info->zone_active_bgs_lock);
2629	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
2630		struct btrfs_zoned_device_info *zinfo = device->zone_info;
2631		int reserved = 0;
2632
2633		if (!device->bdev)
2634			continue;
2635
2636		if (!zinfo->max_active_zones) {
2637			ret = true;
2638			break;
2639		}
2640
2641		if (flags & BTRFS_BLOCK_GROUP_DATA)
2642			reserved = zinfo->reserved_active_zones;
2643
2644		switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2645		case 0: /* single */
2646			ret = (atomic_read(&zinfo->active_zones_left) >= (1 + reserved));
2647			break;
2648		case BTRFS_BLOCK_GROUP_DUP:
2649			ret = (atomic_read(&zinfo->active_zones_left) >= (2 + reserved));
2650			break;
2651		}
2652		if (ret)
2653			break;
2654	}
2655	spin_unlock(&fs_info->zone_active_bgs_lock);
2656	mutex_unlock(&fs_info->chunk_mutex);
2657
2658	if (!ret)
2659		set_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2660
2661	return ret;
2662}
2663
2664int btrfs_zone_finish_endio(struct btrfs_fs_info *fs_info, u64 logical, u64 length)
2665{
2666	struct btrfs_block_group *block_group;
2667	u64 min_alloc_bytes;
2668
2669	if (!btrfs_is_zoned(fs_info))
2670		return 0;
2671
2672	block_group = btrfs_lookup_block_group(fs_info, logical);
2673	if (WARN_ON_ONCE(!block_group))
2674		return -ENOENT;
2675
2676	/* No MIXED_BG on zoned btrfs. */
2677	if (block_group->flags & BTRFS_BLOCK_GROUP_DATA)
2678		min_alloc_bytes = fs_info->sectorsize;
2679	else
2680		min_alloc_bytes = fs_info->nodesize;
2681
2682	/* Bail out if we can allocate more data from this block group. */
2683	if (logical + length + min_alloc_bytes <=
2684	    block_group->start + block_group->zone_capacity)
2685		goto out;
2686
2687	do_zone_finish(block_group, true);
2688
2689out:
2690	btrfs_put_block_group(block_group);
2691	return 0;
2692}
2693
2694static void btrfs_zone_finish_endio_workfn(struct work_struct *work)
2695{
2696	int ret;
2697	struct btrfs_block_group *bg =
2698		container_of(work, struct btrfs_block_group, zone_finish_work);
2699
2700	wait_on_extent_buffer_writeback(bg->last_eb);
2701	free_extent_buffer(bg->last_eb);
2702	ret = do_zone_finish(bg, true);
2703	if (ret)
2704		btrfs_handle_fs_error(bg->fs_info, ret,
2705				      "Failed to finish block-group's zone");
2706	btrfs_put_block_group(bg);
2707}
2708
2709void btrfs_schedule_zone_finish_bg(struct btrfs_block_group *bg,
2710				   struct extent_buffer *eb)
2711{
2712	if (!test_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &bg->runtime_flags) ||
2713	    eb->start + eb->len * 2 <= bg->start + bg->zone_capacity)
2714		return;
2715
2716	if (WARN_ON(bg->zone_finish_work.func == btrfs_zone_finish_endio_workfn)) {
2717		btrfs_err(bg->fs_info, "double scheduling of bg %llu zone finishing",
2718			  bg->start);
2719		return;
2720	}
2721
2722	/* For the work */
2723	btrfs_get_block_group(bg);
2724	refcount_inc(&eb->refs);
2725	bg->last_eb = eb;
2726	INIT_WORK(&bg->zone_finish_work, btrfs_zone_finish_endio_workfn);
2727	queue_work(system_dfl_wq, &bg->zone_finish_work);
2728}
2729
2730void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg)
2731{
2732	struct btrfs_fs_info *fs_info = bg->fs_info;
2733
2734	spin_lock(&fs_info->relocation_bg_lock);
2735	if (fs_info->data_reloc_bg == bg->start)
2736		fs_info->data_reloc_bg = 0;
2737	spin_unlock(&fs_info->relocation_bg_lock);
2738}
2739
2740void btrfs_zoned_reserve_data_reloc_bg(struct btrfs_fs_info *fs_info)
2741{
2742	struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
2743	struct btrfs_space_info *space_info = data_sinfo;
2744	struct btrfs_trans_handle *trans;
2745	struct btrfs_block_group *bg;
2746	struct list_head *bg_list;
2747	u64 alloc_flags;
2748	bool first = true;
2749	bool did_chunk_alloc = false;
2750	int index;
2751	int ret;
2752
2753	if (!btrfs_is_zoned(fs_info))
2754		return;
2755
2756	if (fs_info->data_reloc_bg)
2757		return;
2758
2759	if (sb_rdonly(fs_info->sb))
2760		return;
2761
2762	alloc_flags = btrfs_get_alloc_profile(fs_info, space_info->flags);
2763	index = btrfs_bg_flags_to_raid_index(alloc_flags);
2764
2765	/* Scan the data space_info to find empty block groups. Take the second one. */
2766again:
2767	bg_list = &space_info->block_groups[index];
2768	list_for_each_entry(bg, bg_list, list) {
2769		if (bg->alloc_offset != 0)
2770			continue;
2771
2772		if (first) {
2773			first = false;
2774			continue;
2775		}
2776
2777		if (space_info == data_sinfo) {
2778			/* Migrate the block group to the data relocation space_info. */
2779			struct btrfs_space_info *reloc_sinfo = data_sinfo->sub_group[0];
2780			int factor;
2781
2782			ASSERT(reloc_sinfo->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC,
2783			       "reloc_sinfo->subgroup_id=%d", reloc_sinfo->subgroup_id);
2784			factor = btrfs_bg_type_to_factor(bg->flags);
2785
2786			down_write(&space_info->groups_sem);
2787			list_del_init(&bg->list);
2788			/* We can assume this as we choose the second empty one. */
2789			ASSERT(!list_empty(&space_info->block_groups[index]));
2790			up_write(&space_info->groups_sem);
2791
2792			spin_lock(&space_info->lock);
2793			space_info->total_bytes -= bg->length;
2794			space_info->disk_total -= bg->length * factor;
2795			space_info->disk_total -= bg->zone_unusable;
2796			/* There is no allocation ever happened. */
2797			ASSERT(bg->used == 0, "bg->used=%llu", bg->used);
2798			/* No super block in a block group on the zoned setup. */
2799			ASSERT(bg->bytes_super == 0, "bg->bytes_super=%llu", bg->bytes_super);
2800			spin_unlock(&space_info->lock);
2801
2802			bg->space_info = reloc_sinfo;
2803			if (reloc_sinfo->block_group_kobjs[index] == NULL)
2804				btrfs_sysfs_add_block_group_type(bg);
2805
2806			btrfs_add_bg_to_space_info(fs_info, bg);
2807		}
2808
2809		fs_info->data_reloc_bg = bg->start;
2810		set_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &bg->runtime_flags);
2811		btrfs_zone_activate(bg);
2812
2813		return;
2814	}
2815
2816	if (did_chunk_alloc)
2817		return;
2818
2819	trans = btrfs_join_transaction(fs_info->tree_root);
2820	if (IS_ERR(trans))
2821		return;
2822
2823	/* Allocate new BG in the data relocation space_info. */
2824	space_info = data_sinfo->sub_group[0];
2825	ASSERT(space_info->subgroup_id == BTRFS_SUB_GROUP_DATA_RELOC,
2826	       "space_info->subgroup_id=%d", space_info->subgroup_id);
2827	ret = btrfs_chunk_alloc(trans, space_info, alloc_flags, CHUNK_ALLOC_FORCE);
2828	btrfs_end_transaction(trans);
2829	if (ret == 1) {
2830		/*
2831		 * We allocated a new block group in the data relocation space_info. We
2832		 * can take that one.
2833		 */
2834		first = false;
2835		did_chunk_alloc = true;
2836		goto again;
2837	}
2838}
2839
2840void btrfs_free_zone_cache(struct btrfs_fs_info *fs_info)
2841{
2842	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2843	struct btrfs_device *device;
2844
2845	if (!btrfs_is_zoned(fs_info))
2846		return;
2847
2848	mutex_lock(&fs_devices->device_list_mutex);
2849	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2850		if (device->zone_info) {
2851			vfree(device->zone_info->zone_cache);
2852			device->zone_info->zone_cache = NULL;
2853		}
2854	}
2855	mutex_unlock(&fs_devices->device_list_mutex);
2856}
2857
2858bool btrfs_zoned_should_reclaim(const struct btrfs_fs_info *fs_info)
2859{
2860	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2861	struct btrfs_device *device;
2862	u64 total = btrfs_super_total_bytes(fs_info->super_copy);
2863	u64 used = 0;
2864	u64 factor;
2865
2866	ASSERT(btrfs_is_zoned(fs_info));
2867
2868	if (fs_info->bg_reclaim_threshold == 0)
2869		return false;
2870
2871	mutex_lock(&fs_devices->device_list_mutex);
2872	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2873		if (!device->bdev)
2874			continue;
2875
2876		used += device->bytes_used;
2877	}
2878	mutex_unlock(&fs_devices->device_list_mutex);
2879
2880	factor = div64_u64(used * 100, total);
2881	return factor >= fs_info->bg_reclaim_threshold;
2882}
2883
2884void btrfs_zoned_release_data_reloc_bg(struct btrfs_fs_info *fs_info, u64 logical,
2885				       u64 length)
2886{
2887	struct btrfs_block_group *block_group;
2888
2889	if (!btrfs_is_zoned(fs_info))
2890		return;
2891
2892	block_group = btrfs_lookup_block_group(fs_info, logical);
2893	/* It should be called on a previous data relocation block group. */
2894	ASSERT(block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA));
2895
2896	spin_lock(&block_group->lock);
2897	if (!test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))
2898		goto out;
2899
2900	/* All relocation extents are written. */
2901	if (block_group->start + block_group->alloc_offset == logical + length) {
2902		/*
2903		 * Now, release this block group for further allocations and
2904		 * zone finish.
2905		 */
2906		clear_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC,
2907			  &block_group->runtime_flags);
2908	}
2909
2910out:
2911	spin_unlock(&block_group->lock);
2912	btrfs_put_block_group(block_group);
2913}
2914
2915int btrfs_zone_finish_one_bg(struct btrfs_fs_info *fs_info)
2916{
2917	struct btrfs_block_group *block_group;
2918	struct btrfs_block_group *min_bg = NULL;
2919	u64 min_avail = U64_MAX;
2920	int ret;
2921
2922	spin_lock(&fs_info->zone_active_bgs_lock);
2923	list_for_each_entry(block_group, &fs_info->zone_active_bgs,
2924			    active_bg_list) {
2925		u64 avail;
2926
2927		spin_lock(&block_group->lock);
2928		if (block_group->reserved || block_group->alloc_offset == 0 ||
2929		    !(block_group->flags & BTRFS_BLOCK_GROUP_DATA) ||
2930		    test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags)) {
2931			spin_unlock(&block_group->lock);
2932			continue;
2933		}
2934
2935		avail = block_group->zone_capacity - block_group->alloc_offset;
2936		if (min_avail > avail) {
2937			if (min_bg)
2938				btrfs_put_block_group(min_bg);
2939			min_bg = block_group;
2940			min_avail = avail;
2941			btrfs_get_block_group(min_bg);
2942		}
2943		spin_unlock(&block_group->lock);
2944	}
2945	spin_unlock(&fs_info->zone_active_bgs_lock);
2946
2947	if (!min_bg)
2948		return 0;
2949
2950	ret = btrfs_zone_finish(min_bg);
2951	btrfs_put_block_group(min_bg);
2952
2953	return ret < 0 ? ret : 1;
2954}
2955
2956int btrfs_zoned_activate_one_bg(struct btrfs_space_info *space_info, bool do_finish)
2957{
2958	struct btrfs_fs_info *fs_info = space_info->fs_info;
2959	struct btrfs_block_group *bg;
2960	int index;
2961
2962	if (!btrfs_is_zoned(fs_info) || (space_info->flags & BTRFS_BLOCK_GROUP_DATA))
2963		return 0;
2964
2965	for (;;) {
2966		int ret;
2967		bool need_finish = false;
2968
2969		down_read(&space_info->groups_sem);
2970		for (index = 0; index < BTRFS_NR_RAID_TYPES; index++) {
2971			list_for_each_entry(bg, &space_info->block_groups[index],
2972					    list) {
2973				if (!spin_trylock(&bg->lock))
2974					continue;
2975				if (btrfs_zoned_bg_is_full(bg) ||
2976				    test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2977					     &bg->runtime_flags)) {
2978					spin_unlock(&bg->lock);
2979					continue;
2980				}
2981				spin_unlock(&bg->lock);
2982
2983				if (btrfs_zone_activate(bg)) {
2984					up_read(&space_info->groups_sem);
2985					return 1;
2986				}
2987
2988				need_finish = true;
2989			}
2990		}
2991		up_read(&space_info->groups_sem);
2992
2993		if (!do_finish || !need_finish)
2994			break;
2995
2996		ret = btrfs_zone_finish_one_bg(fs_info);
2997		if (ret == 0)
2998			break;
2999		if (ret < 0)
3000			return ret;
3001	}
3002
3003	return 0;
3004}
3005
3006/*
3007 * Reserve zones for one metadata block group, one tree-log block group, and one
3008 * system block group.
3009 */
3010void btrfs_check_active_zone_reservation(struct btrfs_fs_info *fs_info)
3011{
3012	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
3013	struct btrfs_block_group *block_group;
3014	struct btrfs_device *device;
3015	/* Reserve zones for normal SINGLE metadata and tree-log block group. */
3016	unsigned int metadata_reserve = 2;
3017	/* Reserve a zone for SINGLE system block group. */
3018	unsigned int system_reserve = 1;
3019
3020	if (!test_bit(BTRFS_FS_ACTIVE_ZONE_TRACKING, &fs_info->flags))
3021		return;
3022
3023	/*
3024	 * This function is called from the mount context. So, there is no
3025	 * parallel process touching the bits. No need for read_seqretry().
3026	 */
3027	if (fs_info->avail_metadata_alloc_bits & BTRFS_BLOCK_GROUP_DUP)
3028		metadata_reserve = 4;
3029	if (fs_info->avail_system_alloc_bits & BTRFS_BLOCK_GROUP_DUP)
3030		system_reserve = 2;
3031
3032	/* Apply the reservation on all the devices. */
3033	mutex_lock(&fs_devices->device_list_mutex);
3034	list_for_each_entry(device, &fs_devices->devices, dev_list) {
3035		if (!device->bdev)
3036			continue;
3037
3038		device->zone_info->reserved_active_zones =
3039			metadata_reserve + system_reserve;
3040	}
3041	mutex_unlock(&fs_devices->device_list_mutex);
3042
3043	/* Release reservation for currently active block groups. */
3044	spin_lock(&fs_info->zone_active_bgs_lock);
3045	list_for_each_entry(block_group, &fs_info->zone_active_bgs, active_bg_list) {
3046		struct btrfs_chunk_map *map = block_group->physical_map;
3047
3048		if (!(block_group->flags &
3049		      (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM)))
3050			continue;
3051
3052		for (int i = 0; i < map->num_stripes; i++)
3053			map->stripes[i].dev->zone_info->reserved_active_zones--;
3054	}
3055	spin_unlock(&fs_info->zone_active_bgs_lock);
3056}
3057
3058/*
3059 * Reset the zones of unused block groups from @space_info->bytes_zone_unusable.
3060 *
3061 * @space_info:	the space to work on
3062 * @num_bytes:	targeting reclaim bytes
3063 *
3064 * This one resets the zones of a block group, so we can reuse the region
3065 * without removing the block group. On the other hand, btrfs_delete_unused_bgs()
3066 * just removes a block group and frees up the underlying zones. So, we still
3067 * need to allocate a new block group to reuse the zones.
3068 *
3069 * Resetting is faster than deleting/recreating a block group. It is similar
3070 * to freeing the logical space on the regular mode. However, we cannot change
3071 * the block group's profile with this operation.
3072 */
3073int btrfs_reset_unused_block_groups(struct btrfs_space_info *space_info, u64 num_bytes)
3074{
3075	struct btrfs_fs_info *fs_info = space_info->fs_info;
3076	const sector_t zone_size_sectors = fs_info->zone_size >> SECTOR_SHIFT;
3077
3078	if (!btrfs_is_zoned(fs_info))
3079		return 0;
3080
3081	while (num_bytes > 0) {
3082		struct btrfs_chunk_map *map;
3083		struct btrfs_block_group *bg = NULL;
3084		bool found = false;
3085		u64 reclaimed = 0;
3086
3087		/*
3088		 * Here, we choose a fully zone_unusable block group. It's
3089		 * technically possible to reset a partly zone_unusable block
3090		 * group, which still has some free space left. However,
3091		 * handling that needs to cope with the allocation side, which
3092		 * makes the logic more complex. So, let's handle the easy case
3093		 * for now.
3094		 */
3095		spin_lock(&fs_info->unused_bgs_lock);
3096		list_for_each_entry(bg, &fs_info->unused_bgs, bg_list) {
3097			if ((bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) != space_info->flags)
3098				continue;
3099
3100			/*
3101			 * Use trylock to avoid locking order violation. In
3102			 * btrfs_reclaim_bgs_work(), the lock order is
3103			 * &bg->lock -> &fs_info->unused_bgs_lock. We skip a
3104			 * block group if we cannot take its lock.
3105			 */
3106			if (!spin_trylock(&bg->lock))
3107				continue;
3108			if (btrfs_is_block_group_used(bg) || bg->zone_unusable < bg->length) {
3109				spin_unlock(&bg->lock);
3110				continue;
3111			}
3112			spin_unlock(&bg->lock);
3113			found = true;
3114			break;
3115		}
3116		if (!found) {
3117			spin_unlock(&fs_info->unused_bgs_lock);
3118			return 0;
3119		}
3120
3121		list_del_init(&bg->bg_list);
3122		btrfs_put_block_group(bg);
3123		spin_unlock(&fs_info->unused_bgs_lock);
3124
3125		/*
3126		 * Since the block group is fully zone_unusable and we cannot
3127		 * allocate from this block group anymore, we don't need to set
3128		 * this block group read-only.
3129		 */
3130
3131		down_read(&fs_info->dev_replace.rwsem);
3132		map = bg->physical_map;
3133		for (int i = 0; i < map->num_stripes; i++) {
3134			struct btrfs_io_stripe *stripe = &map->stripes[i];
3135			unsigned int nofs_flags;
3136			int ret;
3137
3138			nofs_flags = memalloc_nofs_save();
3139			ret = blkdev_zone_mgmt(stripe->dev->bdev, REQ_OP_ZONE_RESET,
3140					       stripe->physical >> SECTOR_SHIFT,
3141					       zone_size_sectors);
3142			memalloc_nofs_restore(nofs_flags);
3143
3144			if (ret) {
3145				up_read(&fs_info->dev_replace.rwsem);
3146				return ret;
3147			}
3148		}
3149		up_read(&fs_info->dev_replace.rwsem);
3150
3151		spin_lock(&space_info->lock);
3152		spin_lock(&bg->lock);
3153		ASSERT(!btrfs_is_block_group_used(bg));
3154		if (bg->ro) {
3155			spin_unlock(&bg->lock);
3156			spin_unlock(&space_info->lock);
3157			continue;
3158		}
3159
3160		reclaimed = bg->alloc_offset;
3161		bg->zone_unusable = bg->length - bg->zone_capacity;
3162		bg->alloc_offset = 0;
3163		/*
3164		 * This holds because we currently reset fully used then freed
3165		 * block group.
3166		 */
3167		ASSERT(reclaimed == bg->zone_capacity,
3168		       "reclaimed=%llu bg->zone_capacity=%llu", reclaimed, bg->zone_capacity);
3169		bg->free_space_ctl->free_space += reclaimed;
3170		space_info->bytes_zone_unusable -= reclaimed;
3171		spin_unlock(&bg->lock);
3172		btrfs_return_free_space(space_info, reclaimed);
3173		spin_unlock(&space_info->lock);
3174
3175		if (num_bytes <= reclaimed)
3176			break;
3177		num_bytes -= reclaimed;
3178	}
3179
3180	return 0;
3181}
~/ Read-only file preview.