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