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