xref: /openbmc/linux/fs/btrfs/zoned.c (revision aaa746ad)
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 "transaction.h"
16 #include "dev-replace.h"
17 #include "space-info.h"
18 #include "fs.h"
19 #include "accessors.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 inline bool sb_zone_is_full(const struct blk_zone *zone)
67 {
68 	return (zone->cond == BLK_ZONE_COND_FULL) ||
69 		(zone->wp + SUPER_INFO_SECTORS > zone->start + zone->capacity);
70 }
71 
72 static int copy_zone_info_cb(struct blk_zone *zone, unsigned int idx, void *data)
73 {
74 	struct blk_zone *zones = data;
75 
76 	memcpy(&zones[idx], zone, sizeof(*zone));
77 
78 	return 0;
79 }
80 
81 static int sb_write_pointer(struct block_device *bdev, struct blk_zone *zones,
82 			    u64 *wp_ret)
83 {
84 	bool empty[BTRFS_NR_SB_LOG_ZONES];
85 	bool full[BTRFS_NR_SB_LOG_ZONES];
86 	sector_t sector;
87 	int i;
88 
89 	for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
90 		ASSERT(zones[i].type != BLK_ZONE_TYPE_CONVENTIONAL);
91 		empty[i] = (zones[i].cond == BLK_ZONE_COND_EMPTY);
92 		full[i] = sb_zone_is_full(&zones[i]);
93 	}
94 
95 	/*
96 	 * Possible states of log buffer zones
97 	 *
98 	 *           Empty[0]  In use[0]  Full[0]
99 	 * Empty[1]         *          0        1
100 	 * In use[1]        x          x        1
101 	 * Full[1]          0          0        C
102 	 *
103 	 * Log position:
104 	 *   *: Special case, no superblock is written
105 	 *   0: Use write pointer of zones[0]
106 	 *   1: Use write pointer of zones[1]
107 	 *   C: Compare super blocks from zones[0] and zones[1], use the latest
108 	 *      one determined by generation
109 	 *   x: Invalid state
110 	 */
111 
112 	if (empty[0] && empty[1]) {
113 		/* Special case to distinguish no superblock to read */
114 		*wp_ret = zones[0].start << SECTOR_SHIFT;
115 		return -ENOENT;
116 	} else if (full[0] && full[1]) {
117 		/* Compare two super blocks */
118 		struct address_space *mapping = bdev->bd_inode->i_mapping;
119 		struct page *page[BTRFS_NR_SB_LOG_ZONES];
120 		struct btrfs_super_block *super[BTRFS_NR_SB_LOG_ZONES];
121 		int i;
122 
123 		for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
124 			u64 bytenr;
125 
126 			bytenr = ((zones[i].start + zones[i].len)
127 				   << SECTOR_SHIFT) - 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 (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;
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 	u32 zno;
224 	int ret;
225 
226 	if (!*nr_zones)
227 		return 0;
228 
229 	if (!bdev_is_zoned(device->bdev)) {
230 		ret = emulate_report_zones(device, pos, zones, *nr_zones);
231 		*nr_zones = ret;
232 		return 0;
233 	}
234 
235 	/* Check cache */
236 	if (zinfo->zone_cache) {
237 		unsigned int i;
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 		memcpy(zinfo->zone_cache + zno, zones,
279 		       sizeof(*zinfo->zone_cache) * *nr_zones);
280 
281 	return 0;
282 }
283 
284 /* The emulated zone size is determined from the size of device extent */
285 static int calculate_emulated_zone_size(struct btrfs_fs_info *fs_info)
286 {
287 	struct btrfs_path *path;
288 	struct btrfs_root *root = fs_info->dev_root;
289 	struct btrfs_key key;
290 	struct extent_buffer *leaf;
291 	struct btrfs_dev_extent *dext;
292 	int ret = 0;
293 
294 	key.objectid = 1;
295 	key.type = BTRFS_DEV_EXTENT_KEY;
296 	key.offset = 0;
297 
298 	path = btrfs_alloc_path();
299 	if (!path)
300 		return -ENOMEM;
301 
302 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
303 	if (ret < 0)
304 		goto out;
305 
306 	if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
307 		ret = btrfs_next_leaf(root, path);
308 		if (ret < 0)
309 			goto out;
310 		/* No dev extents at all? Not good */
311 		if (ret > 0) {
312 			ret = -EUCLEAN;
313 			goto out;
314 		}
315 	}
316 
317 	leaf = path->nodes[0];
318 	dext = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
319 	fs_info->zone_size = btrfs_dev_extent_length(leaf, dext);
320 	ret = 0;
321 
322 out:
323 	btrfs_free_path(path);
324 
325 	return ret;
326 }
327 
328 int btrfs_get_dev_zone_info_all_devices(struct btrfs_fs_info *fs_info)
329 {
330 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
331 	struct btrfs_device *device;
332 	int ret = 0;
333 
334 	/* fs_info->zone_size might not set yet. Use the incomapt flag here. */
335 	if (!btrfs_fs_incompat(fs_info, ZONED))
336 		return 0;
337 
338 	mutex_lock(&fs_devices->device_list_mutex);
339 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
340 		/* We can skip reading of zone info for missing devices */
341 		if (!device->bdev)
342 			continue;
343 
344 		ret = btrfs_get_dev_zone_info(device, true);
345 		if (ret)
346 			break;
347 	}
348 	mutex_unlock(&fs_devices->device_list_mutex);
349 
350 	return ret;
351 }
352 
353 int btrfs_get_dev_zone_info(struct btrfs_device *device, bool populate_cache)
354 {
355 	struct btrfs_fs_info *fs_info = device->fs_info;
356 	struct btrfs_zoned_device_info *zone_info = NULL;
357 	struct block_device *bdev = device->bdev;
358 	unsigned int max_active_zones;
359 	unsigned int nactive;
360 	sector_t nr_sectors;
361 	sector_t sector = 0;
362 	struct blk_zone *zones = NULL;
363 	unsigned int i, nreported = 0, nr_zones;
364 	sector_t zone_sectors;
365 	char *model, *emulated;
366 	int ret;
367 
368 	/*
369 	 * Cannot use btrfs_is_zoned here, since fs_info::zone_size might not
370 	 * yet be set.
371 	 */
372 	if (!btrfs_fs_incompat(fs_info, ZONED))
373 		return 0;
374 
375 	if (device->zone_info)
376 		return 0;
377 
378 	zone_info = kzalloc(sizeof(*zone_info), GFP_KERNEL);
379 	if (!zone_info)
380 		return -ENOMEM;
381 
382 	device->zone_info = zone_info;
383 
384 	if (!bdev_is_zoned(bdev)) {
385 		if (!fs_info->zone_size) {
386 			ret = calculate_emulated_zone_size(fs_info);
387 			if (ret)
388 				goto out;
389 		}
390 
391 		ASSERT(fs_info->zone_size);
392 		zone_sectors = fs_info->zone_size >> SECTOR_SHIFT;
393 	} else {
394 		zone_sectors = bdev_zone_sectors(bdev);
395 	}
396 
397 	ASSERT(is_power_of_two_u64(zone_sectors));
398 	zone_info->zone_size = zone_sectors << SECTOR_SHIFT;
399 
400 	/* We reject devices with a zone size larger than 8GB */
401 	if (zone_info->zone_size > BTRFS_MAX_ZONE_SIZE) {
402 		btrfs_err_in_rcu(fs_info,
403 		"zoned: %s: zone size %llu larger than supported maximum %llu",
404 				 rcu_str_deref(device->name),
405 				 zone_info->zone_size, BTRFS_MAX_ZONE_SIZE);
406 		ret = -EINVAL;
407 		goto out;
408 	} else if (zone_info->zone_size < BTRFS_MIN_ZONE_SIZE) {
409 		btrfs_err_in_rcu(fs_info,
410 		"zoned: %s: zone size %llu smaller than supported minimum %u",
411 				 rcu_str_deref(device->name),
412 				 zone_info->zone_size, BTRFS_MIN_ZONE_SIZE);
413 		ret = -EINVAL;
414 		goto out;
415 	}
416 
417 	nr_sectors = bdev_nr_sectors(bdev);
418 	zone_info->zone_size_shift = ilog2(zone_info->zone_size);
419 	zone_info->nr_zones = nr_sectors >> ilog2(zone_sectors);
420 	/*
421 	 * We limit max_zone_append_size also by max_segments *
422 	 * PAGE_SIZE. Technically, we can have multiple pages per segment. But,
423 	 * since btrfs adds the pages one by one to a bio, and btrfs cannot
424 	 * increase the metadata reservation even if it increases the number of
425 	 * extents, it is safe to stick with the limit.
426 	 *
427 	 * With the zoned emulation, we can have non-zoned device on the zoned
428 	 * mode. In this case, we don't have a valid max zone append size. So,
429 	 * use max_segments * PAGE_SIZE as the pseudo max_zone_append_size.
430 	 */
431 	if (bdev_is_zoned(bdev)) {
432 		zone_info->max_zone_append_size = min_t(u64,
433 			(u64)bdev_max_zone_append_sectors(bdev) << SECTOR_SHIFT,
434 			(u64)bdev_max_segments(bdev) << PAGE_SHIFT);
435 	} else {
436 		zone_info->max_zone_append_size =
437 			(u64)bdev_max_segments(bdev) << PAGE_SHIFT;
438 	}
439 	if (!IS_ALIGNED(nr_sectors, zone_sectors))
440 		zone_info->nr_zones++;
441 
442 	max_active_zones = bdev_max_active_zones(bdev);
443 	if (max_active_zones && max_active_zones < BTRFS_MIN_ACTIVE_ZONES) {
444 		btrfs_err_in_rcu(fs_info,
445 "zoned: %s: max active zones %u is too small, need at least %u active zones",
446 				 rcu_str_deref(device->name), max_active_zones,
447 				 BTRFS_MIN_ACTIVE_ZONES);
448 		ret = -EINVAL;
449 		goto out;
450 	}
451 	zone_info->max_active_zones = max_active_zones;
452 
453 	zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
454 	if (!zone_info->seq_zones) {
455 		ret = -ENOMEM;
456 		goto out;
457 	}
458 
459 	zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
460 	if (!zone_info->empty_zones) {
461 		ret = -ENOMEM;
462 		goto out;
463 	}
464 
465 	zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
466 	if (!zone_info->active_zones) {
467 		ret = -ENOMEM;
468 		goto out;
469 	}
470 
471 	zones = kvcalloc(BTRFS_REPORT_NR_ZONES, sizeof(struct blk_zone), GFP_KERNEL);
472 	if (!zones) {
473 		ret = -ENOMEM;
474 		goto out;
475 	}
476 
477 	/*
478 	 * Enable zone cache only for a zoned device. On a non-zoned device, we
479 	 * fill the zone info with emulated CONVENTIONAL zones, so no need to
480 	 * use the cache.
481 	 */
482 	if (populate_cache && bdev_is_zoned(device->bdev)) {
483 		zone_info->zone_cache = vzalloc(sizeof(struct blk_zone) *
484 						zone_info->nr_zones);
485 		if (!zone_info->zone_cache) {
486 			btrfs_err_in_rcu(device->fs_info,
487 				"zoned: failed to allocate zone cache for %s",
488 				rcu_str_deref(device->name));
489 			ret = -ENOMEM;
490 			goto out;
491 		}
492 	}
493 
494 	/* Get zones type */
495 	nactive = 0;
496 	while (sector < nr_sectors) {
497 		nr_zones = BTRFS_REPORT_NR_ZONES;
498 		ret = btrfs_get_dev_zones(device, sector << SECTOR_SHIFT, zones,
499 					  &nr_zones);
500 		if (ret)
501 			goto out;
502 
503 		for (i = 0; i < nr_zones; i++) {
504 			if (zones[i].type == BLK_ZONE_TYPE_SEQWRITE_REQ)
505 				__set_bit(nreported, zone_info->seq_zones);
506 			switch (zones[i].cond) {
507 			case BLK_ZONE_COND_EMPTY:
508 				__set_bit(nreported, zone_info->empty_zones);
509 				break;
510 			case BLK_ZONE_COND_IMP_OPEN:
511 			case BLK_ZONE_COND_EXP_OPEN:
512 			case BLK_ZONE_COND_CLOSED:
513 				__set_bit(nreported, zone_info->active_zones);
514 				nactive++;
515 				break;
516 			}
517 			nreported++;
518 		}
519 		sector = zones[nr_zones - 1].start + zones[nr_zones - 1].len;
520 	}
521 
522 	if (nreported != zone_info->nr_zones) {
523 		btrfs_err_in_rcu(device->fs_info,
524 				 "inconsistent number of zones on %s (%u/%u)",
525 				 rcu_str_deref(device->name), nreported,
526 				 zone_info->nr_zones);
527 		ret = -EIO;
528 		goto out;
529 	}
530 
531 	if (max_active_zones) {
532 		if (nactive > max_active_zones) {
533 			btrfs_err_in_rcu(device->fs_info,
534 			"zoned: %u active zones on %s exceeds max_active_zones %u",
535 					 nactive, rcu_str_deref(device->name),
536 					 max_active_zones);
537 			ret = -EIO;
538 			goto out;
539 		}
540 		atomic_set(&zone_info->active_zones_left,
541 			   max_active_zones - nactive);
542 	}
543 
544 	/* Validate superblock log */
545 	nr_zones = BTRFS_NR_SB_LOG_ZONES;
546 	for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
547 		u32 sb_zone;
548 		u64 sb_wp;
549 		int sb_pos = BTRFS_NR_SB_LOG_ZONES * i;
550 
551 		sb_zone = sb_zone_number(zone_info->zone_size_shift, i);
552 		if (sb_zone + 1 >= zone_info->nr_zones)
553 			continue;
554 
555 		ret = btrfs_get_dev_zones(device,
556 					  zone_start_physical(sb_zone, zone_info),
557 					  &zone_info->sb_zones[sb_pos],
558 					  &nr_zones);
559 		if (ret)
560 			goto out;
561 
562 		if (nr_zones != BTRFS_NR_SB_LOG_ZONES) {
563 			btrfs_err_in_rcu(device->fs_info,
564 	"zoned: failed to read super block log zone info at devid %llu zone %u",
565 					 device->devid, sb_zone);
566 			ret = -EUCLEAN;
567 			goto out;
568 		}
569 
570 		/*
571 		 * If zones[0] is conventional, always use the beginning of the
572 		 * zone to record superblock. No need to validate in that case.
573 		 */
574 		if (zone_info->sb_zones[BTRFS_NR_SB_LOG_ZONES * i].type ==
575 		    BLK_ZONE_TYPE_CONVENTIONAL)
576 			continue;
577 
578 		ret = sb_write_pointer(device->bdev,
579 				       &zone_info->sb_zones[sb_pos], &sb_wp);
580 		if (ret != -ENOENT && ret) {
581 			btrfs_err_in_rcu(device->fs_info,
582 			"zoned: super block log zone corrupted devid %llu zone %u",
583 					 device->devid, sb_zone);
584 			ret = -EUCLEAN;
585 			goto out;
586 		}
587 	}
588 
589 
590 	kvfree(zones);
591 
592 	switch (bdev_zoned_model(bdev)) {
593 	case BLK_ZONED_HM:
594 		model = "host-managed zoned";
595 		emulated = "";
596 		break;
597 	case BLK_ZONED_HA:
598 		model = "host-aware zoned";
599 		emulated = "";
600 		break;
601 	case BLK_ZONED_NONE:
602 		model = "regular";
603 		emulated = "emulated ";
604 		break;
605 	default:
606 		/* Just in case */
607 		btrfs_err_in_rcu(fs_info, "zoned: unsupported model %d on %s",
608 				 bdev_zoned_model(bdev),
609 				 rcu_str_deref(device->name));
610 		ret = -EOPNOTSUPP;
611 		goto out_free_zone_info;
612 	}
613 
614 	btrfs_info_in_rcu(fs_info,
615 		"%s block device %s, %u %szones of %llu bytes",
616 		model, rcu_str_deref(device->name), zone_info->nr_zones,
617 		emulated, zone_info->zone_size);
618 
619 	return 0;
620 
621 out:
622 	kvfree(zones);
623 out_free_zone_info:
624 	btrfs_destroy_dev_zone_info(device);
625 
626 	return ret;
627 }
628 
629 void btrfs_destroy_dev_zone_info(struct btrfs_device *device)
630 {
631 	struct btrfs_zoned_device_info *zone_info = device->zone_info;
632 
633 	if (!zone_info)
634 		return;
635 
636 	bitmap_free(zone_info->active_zones);
637 	bitmap_free(zone_info->seq_zones);
638 	bitmap_free(zone_info->empty_zones);
639 	vfree(zone_info->zone_cache);
640 	kfree(zone_info);
641 	device->zone_info = NULL;
642 }
643 
644 struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *orig_dev)
645 {
646 	struct btrfs_zoned_device_info *zone_info;
647 
648 	zone_info = kmemdup(orig_dev->zone_info, sizeof(*zone_info), GFP_KERNEL);
649 	if (!zone_info)
650 		return NULL;
651 
652 	zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
653 	if (!zone_info->seq_zones)
654 		goto out;
655 
656 	bitmap_copy(zone_info->seq_zones, orig_dev->zone_info->seq_zones,
657 		    zone_info->nr_zones);
658 
659 	zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
660 	if (!zone_info->empty_zones)
661 		goto out;
662 
663 	bitmap_copy(zone_info->empty_zones, orig_dev->zone_info->empty_zones,
664 		    zone_info->nr_zones);
665 
666 	zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
667 	if (!zone_info->active_zones)
668 		goto out;
669 
670 	bitmap_copy(zone_info->active_zones, orig_dev->zone_info->active_zones,
671 		    zone_info->nr_zones);
672 	zone_info->zone_cache = NULL;
673 
674 	return zone_info;
675 
676 out:
677 	bitmap_free(zone_info->seq_zones);
678 	bitmap_free(zone_info->empty_zones);
679 	bitmap_free(zone_info->active_zones);
680 	kfree(zone_info);
681 	return NULL;
682 }
683 
684 int btrfs_get_dev_zone(struct btrfs_device *device, u64 pos,
685 		       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 &&
703 		    bdev_zoned_model(device->bdev) == BLK_ZONED_HM) {
704 			btrfs_err(fs_info,
705 				"zoned: mode not enabled but zoned device found: %pg",
706 				device->bdev);
707 			return -EINVAL;
708 		}
709 	}
710 
711 	return 0;
712 }
713 
714 int btrfs_check_zoned_mode(struct btrfs_fs_info *fs_info)
715 {
716 	struct btrfs_device *device;
717 	u64 zone_size = 0;
718 	u64 max_zone_append_size = 0;
719 	int ret;
720 
721 	/*
722 	 * Host-Managed devices can't be used without the ZONED flag.  With the
723 	 * ZONED all devices can be used, using zone emulation if required.
724 	 */
725 	if (!btrfs_fs_incompat(fs_info, ZONED))
726 		return btrfs_check_for_zoned_device(fs_info);
727 
728 	list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
729 		struct btrfs_zoned_device_info *zone_info = device->zone_info;
730 
731 		if (!device->bdev)
732 			continue;
733 
734 		if (!zone_size) {
735 			zone_size = zone_info->zone_size;
736 		} else if (zone_info->zone_size != zone_size) {
737 			btrfs_err(fs_info,
738 		"zoned: unequal block device zone sizes: have %llu found %llu",
739 				  zone_info->zone_size, zone_size);
740 			return -EINVAL;
741 		}
742 		if (!max_zone_append_size ||
743 		    (zone_info->max_zone_append_size &&
744 		     zone_info->max_zone_append_size < max_zone_append_size))
745 			max_zone_append_size = zone_info->max_zone_append_size;
746 	}
747 
748 	/*
749 	 * stripe_size is always aligned to BTRFS_STRIPE_LEN in
750 	 * btrfs_create_chunk(). Since we want stripe_len == zone_size,
751 	 * check the alignment here.
752 	 */
753 	if (!IS_ALIGNED(zone_size, BTRFS_STRIPE_LEN)) {
754 		btrfs_err(fs_info,
755 			  "zoned: zone size %llu not aligned to stripe %u",
756 			  zone_size, BTRFS_STRIPE_LEN);
757 		return -EINVAL;
758 	}
759 
760 	if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
761 		btrfs_err(fs_info, "zoned: mixed block groups not supported");
762 		return -EINVAL;
763 	}
764 
765 	fs_info->zone_size = zone_size;
766 	fs_info->max_zone_append_size = ALIGN_DOWN(max_zone_append_size,
767 						   fs_info->sectorsize);
768 	fs_info->fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_ZONED;
769 	if (fs_info->max_zone_append_size < fs_info->max_extent_size)
770 		fs_info->max_extent_size = fs_info->max_zone_append_size;
771 
772 	/*
773 	 * Check mount options here, because we might change fs_info->zoned
774 	 * from fs_info->zone_size.
775 	 */
776 	ret = btrfs_check_mountopts_zoned(fs_info);
777 	if (ret)
778 		return ret;
779 
780 	btrfs_info(fs_info, "zoned mode enabled with zone size %llu", zone_size);
781 	return 0;
782 }
783 
784 int btrfs_check_mountopts_zoned(struct btrfs_fs_info *info)
785 {
786 	if (!btrfs_is_zoned(info))
787 		return 0;
788 
789 	/*
790 	 * Space cache writing is not COWed. Disable that to avoid write errors
791 	 * in sequential zones.
792 	 */
793 	if (btrfs_test_opt(info, SPACE_CACHE)) {
794 		btrfs_err(info, "zoned: space cache v1 is not supported");
795 		return -EINVAL;
796 	}
797 
798 	if (btrfs_test_opt(info, NODATACOW)) {
799 		btrfs_err(info, "zoned: NODATACOW not supported");
800 		return -EINVAL;
801 	}
802 
803 	return 0;
804 }
805 
806 static int sb_log_location(struct block_device *bdev, struct blk_zone *zones,
807 			   int rw, u64 *bytenr_ret)
808 {
809 	u64 wp;
810 	int ret;
811 
812 	if (zones[0].type == BLK_ZONE_TYPE_CONVENTIONAL) {
813 		*bytenr_ret = zones[0].start << SECTOR_SHIFT;
814 		return 0;
815 	}
816 
817 	ret = sb_write_pointer(bdev, zones, &wp);
818 	if (ret != -ENOENT && ret < 0)
819 		return ret;
820 
821 	if (rw == WRITE) {
822 		struct blk_zone *reset = NULL;
823 
824 		if (wp == zones[0].start << SECTOR_SHIFT)
825 			reset = &zones[0];
826 		else if (wp == zones[1].start << SECTOR_SHIFT)
827 			reset = &zones[1];
828 
829 		if (reset && reset->cond != BLK_ZONE_COND_EMPTY) {
830 			ASSERT(sb_zone_is_full(reset));
831 
832 			ret = blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
833 					       reset->start, reset->len,
834 					       GFP_NOFS);
835 			if (ret)
836 				return ret;
837 
838 			reset->cond = BLK_ZONE_COND_EMPTY;
839 			reset->wp = reset->start;
840 		}
841 	} else if (ret != -ENOENT) {
842 		/*
843 		 * For READ, we want the previous one. Move write pointer to
844 		 * the end of a zone, if it is at the head of a zone.
845 		 */
846 		u64 zone_end = 0;
847 
848 		if (wp == zones[0].start << SECTOR_SHIFT)
849 			zone_end = zones[1].start + zones[1].capacity;
850 		else if (wp == zones[1].start << SECTOR_SHIFT)
851 			zone_end = zones[0].start + zones[0].capacity;
852 		if (zone_end)
853 			wp = ALIGN_DOWN(zone_end << SECTOR_SHIFT,
854 					BTRFS_SUPER_INFO_SIZE);
855 
856 		wp -= BTRFS_SUPER_INFO_SIZE;
857 	}
858 
859 	*bytenr_ret = wp;
860 	return 0;
861 
862 }
863 
864 int btrfs_sb_log_location_bdev(struct block_device *bdev, int mirror, int rw,
865 			       u64 *bytenr_ret)
866 {
867 	struct blk_zone zones[BTRFS_NR_SB_LOG_ZONES];
868 	sector_t zone_sectors;
869 	u32 sb_zone;
870 	int ret;
871 	u8 zone_sectors_shift;
872 	sector_t nr_sectors;
873 	u32 nr_zones;
874 
875 	if (!bdev_is_zoned(bdev)) {
876 		*bytenr_ret = btrfs_sb_offset(mirror);
877 		return 0;
878 	}
879 
880 	ASSERT(rw == READ || rw == WRITE);
881 
882 	zone_sectors = bdev_zone_sectors(bdev);
883 	if (!is_power_of_2(zone_sectors))
884 		return -EINVAL;
885 	zone_sectors_shift = ilog2(zone_sectors);
886 	nr_sectors = bdev_nr_sectors(bdev);
887 	nr_zones = nr_sectors >> zone_sectors_shift;
888 
889 	sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
890 	if (sb_zone + 1 >= nr_zones)
891 		return -ENOENT;
892 
893 	ret = blkdev_report_zones(bdev, zone_start_sector(sb_zone, bdev),
894 				  BTRFS_NR_SB_LOG_ZONES, copy_zone_info_cb,
895 				  zones);
896 	if (ret < 0)
897 		return ret;
898 	if (ret != BTRFS_NR_SB_LOG_ZONES)
899 		return -EIO;
900 
901 	return sb_log_location(bdev, zones, rw, bytenr_ret);
902 }
903 
904 int btrfs_sb_log_location(struct btrfs_device *device, int mirror, int rw,
905 			  u64 *bytenr_ret)
906 {
907 	struct btrfs_zoned_device_info *zinfo = device->zone_info;
908 	u32 zone_num;
909 
910 	/*
911 	 * For a zoned filesystem on a non-zoned block device, use the same
912 	 * super block locations as regular filesystem. Doing so, the super
913 	 * block can always be retrieved and the zoned flag of the volume
914 	 * detected from the super block information.
915 	 */
916 	if (!bdev_is_zoned(device->bdev)) {
917 		*bytenr_ret = btrfs_sb_offset(mirror);
918 		return 0;
919 	}
920 
921 	zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
922 	if (zone_num + 1 >= zinfo->nr_zones)
923 		return -ENOENT;
924 
925 	return sb_log_location(device->bdev,
926 			       &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror],
927 			       rw, bytenr_ret);
928 }
929 
930 static inline bool is_sb_log_zone(struct btrfs_zoned_device_info *zinfo,
931 				  int mirror)
932 {
933 	u32 zone_num;
934 
935 	if (!zinfo)
936 		return false;
937 
938 	zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
939 	if (zone_num + 1 >= zinfo->nr_zones)
940 		return false;
941 
942 	if (!test_bit(zone_num, zinfo->seq_zones))
943 		return false;
944 
945 	return true;
946 }
947 
948 int btrfs_advance_sb_log(struct btrfs_device *device, int mirror)
949 {
950 	struct btrfs_zoned_device_info *zinfo = device->zone_info;
951 	struct blk_zone *zone;
952 	int i;
953 
954 	if (!is_sb_log_zone(zinfo, mirror))
955 		return 0;
956 
957 	zone = &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror];
958 	for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
959 		/* Advance the next zone */
960 		if (zone->cond == BLK_ZONE_COND_FULL) {
961 			zone++;
962 			continue;
963 		}
964 
965 		if (zone->cond == BLK_ZONE_COND_EMPTY)
966 			zone->cond = BLK_ZONE_COND_IMP_OPEN;
967 
968 		zone->wp += SUPER_INFO_SECTORS;
969 
970 		if (sb_zone_is_full(zone)) {
971 			/*
972 			 * No room left to write new superblock. Since
973 			 * superblock is written with REQ_SYNC, it is safe to
974 			 * finish the zone now.
975 			 *
976 			 * If the write pointer is exactly at the capacity,
977 			 * explicit ZONE_FINISH is not necessary.
978 			 */
979 			if (zone->wp != zone->start + zone->capacity) {
980 				int ret;
981 
982 				ret = blkdev_zone_mgmt(device->bdev,
983 						REQ_OP_ZONE_FINISH, zone->start,
984 						zone->len, GFP_NOFS);
985 				if (ret)
986 					return ret;
987 			}
988 
989 			zone->wp = zone->start + zone->len;
990 			zone->cond = BLK_ZONE_COND_FULL;
991 		}
992 		return 0;
993 	}
994 
995 	/* All the zones are FULL. Should not reach here. */
996 	ASSERT(0);
997 	return -EIO;
998 }
999 
1000 int btrfs_reset_sb_log_zones(struct block_device *bdev, int mirror)
1001 {
1002 	sector_t zone_sectors;
1003 	sector_t nr_sectors;
1004 	u8 zone_sectors_shift;
1005 	u32 sb_zone;
1006 	u32 nr_zones;
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 	return blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
1018 				zone_start_sector(sb_zone, bdev),
1019 				zone_sectors * BTRFS_NR_SB_LOG_ZONES, GFP_NOFS);
1020 }
1021 
1022 /*
1023  * Find allocatable zones within a given region.
1024  *
1025  * @device:	the device to allocate a region on
1026  * @hole_start: the position of the hole to allocate the region
1027  * @num_bytes:	size of wanted region
1028  * @hole_end:	the end of the hole
1029  * @return:	position of allocatable zones
1030  *
1031  * Allocatable region should not contain any superblock locations.
1032  */
1033 u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start,
1034 				 u64 hole_end, u64 num_bytes)
1035 {
1036 	struct btrfs_zoned_device_info *zinfo = device->zone_info;
1037 	const u8 shift = zinfo->zone_size_shift;
1038 	u64 nzones = num_bytes >> shift;
1039 	u64 pos = hole_start;
1040 	u64 begin, end;
1041 	bool have_sb;
1042 	int i;
1043 
1044 	ASSERT(IS_ALIGNED(hole_start, zinfo->zone_size));
1045 	ASSERT(IS_ALIGNED(num_bytes, zinfo->zone_size));
1046 
1047 	while (pos < hole_end) {
1048 		begin = pos >> shift;
1049 		end = begin + nzones;
1050 
1051 		if (end > zinfo->nr_zones)
1052 			return hole_end;
1053 
1054 		/* Check if zones in the region are all empty */
1055 		if (btrfs_dev_is_sequential(device, pos) &&
1056 		    find_next_zero_bit(zinfo->empty_zones, end, begin) != end) {
1057 			pos += zinfo->zone_size;
1058 			continue;
1059 		}
1060 
1061 		have_sb = false;
1062 		for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1063 			u32 sb_zone;
1064 			u64 sb_pos;
1065 
1066 			sb_zone = sb_zone_number(shift, i);
1067 			if (!(end <= sb_zone ||
1068 			      sb_zone + BTRFS_NR_SB_LOG_ZONES <= begin)) {
1069 				have_sb = true;
1070 				pos = zone_start_physical(
1071 					sb_zone + BTRFS_NR_SB_LOG_ZONES, zinfo);
1072 				break;
1073 			}
1074 
1075 			/* We also need to exclude regular superblock positions */
1076 			sb_pos = btrfs_sb_offset(i);
1077 			if (!(pos + num_bytes <= sb_pos ||
1078 			      sb_pos + BTRFS_SUPER_INFO_SIZE <= pos)) {
1079 				have_sb = true;
1080 				pos = ALIGN(sb_pos + BTRFS_SUPER_INFO_SIZE,
1081 					    zinfo->zone_size);
1082 				break;
1083 			}
1084 		}
1085 		if (!have_sb)
1086 			break;
1087 	}
1088 
1089 	return pos;
1090 }
1091 
1092 static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos)
1093 {
1094 	struct btrfs_zoned_device_info *zone_info = device->zone_info;
1095 	unsigned int zno = (pos >> zone_info->zone_size_shift);
1096 
1097 	/* We can use any number of zones */
1098 	if (zone_info->max_active_zones == 0)
1099 		return true;
1100 
1101 	if (!test_bit(zno, zone_info->active_zones)) {
1102 		/* Active zone left? */
1103 		if (atomic_dec_if_positive(&zone_info->active_zones_left) < 0)
1104 			return false;
1105 		if (test_and_set_bit(zno, zone_info->active_zones)) {
1106 			/* Someone already set the bit */
1107 			atomic_inc(&zone_info->active_zones_left);
1108 		}
1109 	}
1110 
1111 	return true;
1112 }
1113 
1114 static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos)
1115 {
1116 	struct btrfs_zoned_device_info *zone_info = device->zone_info;
1117 	unsigned int zno = (pos >> zone_info->zone_size_shift);
1118 
1119 	/* We can use any number of zones */
1120 	if (zone_info->max_active_zones == 0)
1121 		return;
1122 
1123 	if (test_and_clear_bit(zno, zone_info->active_zones))
1124 		atomic_inc(&zone_info->active_zones_left);
1125 }
1126 
1127 int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical,
1128 			    u64 length, u64 *bytes)
1129 {
1130 	int ret;
1131 
1132 	*bytes = 0;
1133 	ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_RESET,
1134 			       physical >> SECTOR_SHIFT, length >> SECTOR_SHIFT,
1135 			       GFP_NOFS);
1136 	if (ret)
1137 		return ret;
1138 
1139 	*bytes = length;
1140 	while (length) {
1141 		btrfs_dev_set_zone_empty(device, physical);
1142 		btrfs_dev_clear_active_zone(device, physical);
1143 		physical += device->zone_info->zone_size;
1144 		length -= device->zone_info->zone_size;
1145 	}
1146 
1147 	return 0;
1148 }
1149 
1150 int btrfs_ensure_empty_zones(struct btrfs_device *device, u64 start, u64 size)
1151 {
1152 	struct btrfs_zoned_device_info *zinfo = device->zone_info;
1153 	const u8 shift = zinfo->zone_size_shift;
1154 	unsigned long begin = start >> shift;
1155 	unsigned long end = (start + size) >> shift;
1156 	u64 pos;
1157 	int ret;
1158 
1159 	ASSERT(IS_ALIGNED(start, zinfo->zone_size));
1160 	ASSERT(IS_ALIGNED(size, zinfo->zone_size));
1161 
1162 	if (end > zinfo->nr_zones)
1163 		return -ERANGE;
1164 
1165 	/* All the zones are conventional */
1166 	if (find_next_bit(zinfo->seq_zones, begin, end) == end)
1167 		return 0;
1168 
1169 	/* All the zones are sequential and empty */
1170 	if (find_next_zero_bit(zinfo->seq_zones, begin, end) == end &&
1171 	    find_next_zero_bit(zinfo->empty_zones, begin, end) == end)
1172 		return 0;
1173 
1174 	for (pos = start; pos < start + size; pos += zinfo->zone_size) {
1175 		u64 reset_bytes;
1176 
1177 		if (!btrfs_dev_is_sequential(device, pos) ||
1178 		    btrfs_dev_is_empty_zone(device, pos))
1179 			continue;
1180 
1181 		/* Free regions should be empty */
1182 		btrfs_warn_in_rcu(
1183 			device->fs_info,
1184 		"zoned: resetting device %s (devid %llu) zone %llu for allocation",
1185 			rcu_str_deref(device->name), device->devid, pos >> shift);
1186 		WARN_ON_ONCE(1);
1187 
1188 		ret = btrfs_reset_device_zone(device, pos, zinfo->zone_size,
1189 					      &reset_bytes);
1190 		if (ret)
1191 			return ret;
1192 	}
1193 
1194 	return 0;
1195 }
1196 
1197 /*
1198  * Calculate an allocation pointer from the extent allocation information
1199  * for a block group consist of conventional zones. It is pointed to the
1200  * end of the highest addressed extent in the block group as an allocation
1201  * offset.
1202  */
1203 static int calculate_alloc_pointer(struct btrfs_block_group *cache,
1204 				   u64 *offset_ret, bool new)
1205 {
1206 	struct btrfs_fs_info *fs_info = cache->fs_info;
1207 	struct btrfs_root *root;
1208 	struct btrfs_path *path;
1209 	struct btrfs_key key;
1210 	struct btrfs_key found_key;
1211 	int ret;
1212 	u64 length;
1213 
1214 	/*
1215 	 * Avoid  tree lookups for a new block group, there's no use for it.
1216 	 * It must always be 0.
1217 	 *
1218 	 * Also, we have a lock chain of extent buffer lock -> chunk mutex.
1219 	 * For new a block group, this function is called from
1220 	 * btrfs_make_block_group() which is already taking the chunk mutex.
1221 	 * Thus, we cannot call calculate_alloc_pointer() which takes extent
1222 	 * buffer locks to avoid deadlock.
1223 	 */
1224 	if (new) {
1225 		*offset_ret = 0;
1226 		return 0;
1227 	}
1228 
1229 	path = btrfs_alloc_path();
1230 	if (!path)
1231 		return -ENOMEM;
1232 
1233 	key.objectid = cache->start + cache->length;
1234 	key.type = 0;
1235 	key.offset = 0;
1236 
1237 	root = btrfs_extent_root(fs_info, key.objectid);
1238 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1239 	/* We should not find the exact match */
1240 	if (!ret)
1241 		ret = -EUCLEAN;
1242 	if (ret < 0)
1243 		goto out;
1244 
1245 	ret = btrfs_previous_extent_item(root, path, cache->start);
1246 	if (ret) {
1247 		if (ret == 1) {
1248 			ret = 0;
1249 			*offset_ret = 0;
1250 		}
1251 		goto out;
1252 	}
1253 
1254 	btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
1255 
1256 	if (found_key.type == BTRFS_EXTENT_ITEM_KEY)
1257 		length = found_key.offset;
1258 	else
1259 		length = fs_info->nodesize;
1260 
1261 	if (!(found_key.objectid >= cache->start &&
1262 	       found_key.objectid + length <= cache->start + cache->length)) {
1263 		ret = -EUCLEAN;
1264 		goto out;
1265 	}
1266 	*offset_ret = found_key.objectid + length - cache->start;
1267 	ret = 0;
1268 
1269 out:
1270 	btrfs_free_path(path);
1271 	return ret;
1272 }
1273 
1274 int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new)
1275 {
1276 	struct btrfs_fs_info *fs_info = cache->fs_info;
1277 	struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1278 	struct extent_map *em;
1279 	struct map_lookup *map;
1280 	struct btrfs_device *device;
1281 	u64 logical = cache->start;
1282 	u64 length = cache->length;
1283 	int ret;
1284 	int i;
1285 	unsigned int nofs_flag;
1286 	u64 *alloc_offsets = NULL;
1287 	u64 *caps = NULL;
1288 	u64 *physical = NULL;
1289 	unsigned long *active = NULL;
1290 	u64 last_alloc = 0;
1291 	u32 num_sequential = 0, num_conventional = 0;
1292 
1293 	if (!btrfs_is_zoned(fs_info))
1294 		return 0;
1295 
1296 	/* Sanity check */
1297 	if (!IS_ALIGNED(length, fs_info->zone_size)) {
1298 		btrfs_err(fs_info,
1299 		"zoned: block group %llu len %llu unaligned to zone size %llu",
1300 			  logical, length, fs_info->zone_size);
1301 		return -EIO;
1302 	}
1303 
1304 	/* Get the chunk mapping */
1305 	read_lock(&em_tree->lock);
1306 	em = lookup_extent_mapping(em_tree, logical, length);
1307 	read_unlock(&em_tree->lock);
1308 
1309 	if (!em)
1310 		return -EINVAL;
1311 
1312 	map = em->map_lookup;
1313 
1314 	cache->physical_map = kmemdup(map, map_lookup_size(map->num_stripes), GFP_NOFS);
1315 	if (!cache->physical_map) {
1316 		ret = -ENOMEM;
1317 		goto out;
1318 	}
1319 
1320 	alloc_offsets = kcalloc(map->num_stripes, sizeof(*alloc_offsets), GFP_NOFS);
1321 	if (!alloc_offsets) {
1322 		ret = -ENOMEM;
1323 		goto out;
1324 	}
1325 
1326 	caps = kcalloc(map->num_stripes, sizeof(*caps), GFP_NOFS);
1327 	if (!caps) {
1328 		ret = -ENOMEM;
1329 		goto out;
1330 	}
1331 
1332 	physical = kcalloc(map->num_stripes, sizeof(*physical), GFP_NOFS);
1333 	if (!physical) {
1334 		ret = -ENOMEM;
1335 		goto out;
1336 	}
1337 
1338 	active = bitmap_zalloc(map->num_stripes, GFP_NOFS);
1339 	if (!active) {
1340 		ret = -ENOMEM;
1341 		goto out;
1342 	}
1343 
1344 	for (i = 0; i < map->num_stripes; i++) {
1345 		bool is_sequential;
1346 		struct blk_zone zone;
1347 		struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1348 		int dev_replace_is_ongoing = 0;
1349 
1350 		device = map->stripes[i].dev;
1351 		physical[i] = map->stripes[i].physical;
1352 
1353 		if (device->bdev == NULL) {
1354 			alloc_offsets[i] = WP_MISSING_DEV;
1355 			continue;
1356 		}
1357 
1358 		is_sequential = btrfs_dev_is_sequential(device, physical[i]);
1359 		if (is_sequential)
1360 			num_sequential++;
1361 		else
1362 			num_conventional++;
1363 
1364 		/*
1365 		 * Consider a zone as active if we can allow any number of
1366 		 * active zones.
1367 		 */
1368 		if (!device->zone_info->max_active_zones)
1369 			__set_bit(i, active);
1370 
1371 		if (!is_sequential) {
1372 			alloc_offsets[i] = WP_CONVENTIONAL;
1373 			continue;
1374 		}
1375 
1376 		/*
1377 		 * This zone will be used for allocation, so mark this zone
1378 		 * non-empty.
1379 		 */
1380 		btrfs_dev_clear_zone_empty(device, physical[i]);
1381 
1382 		down_read(&dev_replace->rwsem);
1383 		dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
1384 		if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
1385 			btrfs_dev_clear_zone_empty(dev_replace->tgtdev, physical[i]);
1386 		up_read(&dev_replace->rwsem);
1387 
1388 		/*
1389 		 * The group is mapped to a sequential zone. Get the zone write
1390 		 * pointer to determine the allocation offset within the zone.
1391 		 */
1392 		WARN_ON(!IS_ALIGNED(physical[i], fs_info->zone_size));
1393 		nofs_flag = memalloc_nofs_save();
1394 		ret = btrfs_get_dev_zone(device, physical[i], &zone);
1395 		memalloc_nofs_restore(nofs_flag);
1396 		if (ret == -EIO || ret == -EOPNOTSUPP) {
1397 			ret = 0;
1398 			alloc_offsets[i] = WP_MISSING_DEV;
1399 			continue;
1400 		} else if (ret) {
1401 			goto out;
1402 		}
1403 
1404 		if (zone.type == BLK_ZONE_TYPE_CONVENTIONAL) {
1405 			btrfs_err_in_rcu(fs_info,
1406 	"zoned: unexpected conventional zone %llu on device %s (devid %llu)",
1407 				zone.start << SECTOR_SHIFT,
1408 				rcu_str_deref(device->name), device->devid);
1409 			ret = -EIO;
1410 			goto out;
1411 		}
1412 
1413 		caps[i] = (zone.capacity << SECTOR_SHIFT);
1414 
1415 		switch (zone.cond) {
1416 		case BLK_ZONE_COND_OFFLINE:
1417 		case BLK_ZONE_COND_READONLY:
1418 			btrfs_err(fs_info,
1419 		"zoned: offline/readonly zone %llu on device %s (devid %llu)",
1420 				  physical[i] >> device->zone_info->zone_size_shift,
1421 				  rcu_str_deref(device->name), device->devid);
1422 			alloc_offsets[i] = WP_MISSING_DEV;
1423 			break;
1424 		case BLK_ZONE_COND_EMPTY:
1425 			alloc_offsets[i] = 0;
1426 			break;
1427 		case BLK_ZONE_COND_FULL:
1428 			alloc_offsets[i] = caps[i];
1429 			break;
1430 		default:
1431 			/* Partially used zone */
1432 			alloc_offsets[i] =
1433 					((zone.wp - zone.start) << SECTOR_SHIFT);
1434 			__set_bit(i, active);
1435 			break;
1436 		}
1437 	}
1438 
1439 	if (num_sequential > 0)
1440 		set_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &cache->runtime_flags);
1441 
1442 	if (num_conventional > 0) {
1443 		/* Zone capacity is always zone size in emulation */
1444 		cache->zone_capacity = cache->length;
1445 		ret = calculate_alloc_pointer(cache, &last_alloc, new);
1446 		if (ret) {
1447 			btrfs_err(fs_info,
1448 			"zoned: failed to determine allocation offset of bg %llu",
1449 				  cache->start);
1450 			goto out;
1451 		} else if (map->num_stripes == num_conventional) {
1452 			cache->alloc_offset = last_alloc;
1453 			set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags);
1454 			goto out;
1455 		}
1456 	}
1457 
1458 	switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1459 	case 0: /* single */
1460 		if (alloc_offsets[0] == WP_MISSING_DEV) {
1461 			btrfs_err(fs_info,
1462 			"zoned: cannot recover write pointer for zone %llu",
1463 				physical[0]);
1464 			ret = -EIO;
1465 			goto out;
1466 		}
1467 		cache->alloc_offset = alloc_offsets[0];
1468 		cache->zone_capacity = caps[0];
1469 		if (test_bit(0, active))
1470 			set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags);
1471 		break;
1472 	case BTRFS_BLOCK_GROUP_DUP:
1473 		if (map->type & BTRFS_BLOCK_GROUP_DATA) {
1474 			btrfs_err(fs_info, "zoned: profile DUP not yet supported on data bg");
1475 			ret = -EINVAL;
1476 			goto out;
1477 		}
1478 		if (alloc_offsets[0] == WP_MISSING_DEV) {
1479 			btrfs_err(fs_info,
1480 			"zoned: cannot recover write pointer for zone %llu",
1481 				physical[0]);
1482 			ret = -EIO;
1483 			goto out;
1484 		}
1485 		if (alloc_offsets[1] == WP_MISSING_DEV) {
1486 			btrfs_err(fs_info,
1487 			"zoned: cannot recover write pointer for zone %llu",
1488 				physical[1]);
1489 			ret = -EIO;
1490 			goto out;
1491 		}
1492 		if (alloc_offsets[0] != alloc_offsets[1]) {
1493 			btrfs_err(fs_info,
1494 			"zoned: write pointer offset mismatch of zones in DUP profile");
1495 			ret = -EIO;
1496 			goto out;
1497 		}
1498 		if (test_bit(0, active) != test_bit(1, active)) {
1499 			if (!btrfs_zone_activate(cache)) {
1500 				ret = -EIO;
1501 				goto out;
1502 			}
1503 		} else {
1504 			if (test_bit(0, active))
1505 				set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
1506 					&cache->runtime_flags);
1507 		}
1508 		cache->alloc_offset = alloc_offsets[0];
1509 		cache->zone_capacity = min(caps[0], caps[1]);
1510 		break;
1511 	case BTRFS_BLOCK_GROUP_RAID1:
1512 	case BTRFS_BLOCK_GROUP_RAID0:
1513 	case BTRFS_BLOCK_GROUP_RAID10:
1514 	case BTRFS_BLOCK_GROUP_RAID5:
1515 	case BTRFS_BLOCK_GROUP_RAID6:
1516 		/* non-single profiles are not supported yet */
1517 	default:
1518 		btrfs_err(fs_info, "zoned: profile %s not yet supported",
1519 			  btrfs_bg_type_to_raid_name(map->type));
1520 		ret = -EINVAL;
1521 		goto out;
1522 	}
1523 
1524 out:
1525 	if (cache->alloc_offset > fs_info->zone_size) {
1526 		btrfs_err(fs_info,
1527 			"zoned: invalid write pointer %llu in block group %llu",
1528 			cache->alloc_offset, cache->start);
1529 		ret = -EIO;
1530 	}
1531 
1532 	if (cache->alloc_offset > cache->zone_capacity) {
1533 		btrfs_err(fs_info,
1534 "zoned: invalid write pointer %llu (larger than zone capacity %llu) in block group %llu",
1535 			  cache->alloc_offset, cache->zone_capacity,
1536 			  cache->start);
1537 		ret = -EIO;
1538 	}
1539 
1540 	/* An extent is allocated after the write pointer */
1541 	if (!ret && num_conventional && last_alloc > cache->alloc_offset) {
1542 		btrfs_err(fs_info,
1543 			  "zoned: got wrong write pointer in BG %llu: %llu > %llu",
1544 			  logical, last_alloc, cache->alloc_offset);
1545 		ret = -EIO;
1546 	}
1547 
1548 	if (!ret) {
1549 		cache->meta_write_pointer = cache->alloc_offset + cache->start;
1550 		if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags)) {
1551 			btrfs_get_block_group(cache);
1552 			spin_lock(&fs_info->zone_active_bgs_lock);
1553 			list_add_tail(&cache->active_bg_list,
1554 				      &fs_info->zone_active_bgs);
1555 			spin_unlock(&fs_info->zone_active_bgs_lock);
1556 		}
1557 	} else {
1558 		kfree(cache->physical_map);
1559 		cache->physical_map = NULL;
1560 	}
1561 	bitmap_free(active);
1562 	kfree(physical);
1563 	kfree(caps);
1564 	kfree(alloc_offsets);
1565 	free_extent_map(em);
1566 
1567 	return ret;
1568 }
1569 
1570 void btrfs_calc_zone_unusable(struct btrfs_block_group *cache)
1571 {
1572 	u64 unusable, free;
1573 
1574 	if (!btrfs_is_zoned(cache->fs_info))
1575 		return;
1576 
1577 	WARN_ON(cache->bytes_super != 0);
1578 	unusable = (cache->alloc_offset - cache->used) +
1579 		   (cache->length - cache->zone_capacity);
1580 	free = cache->zone_capacity - cache->alloc_offset;
1581 
1582 	/* We only need ->free_space in ALLOC_SEQ block groups */
1583 	cache->cached = BTRFS_CACHE_FINISHED;
1584 	cache->free_space_ctl->free_space = free;
1585 	cache->zone_unusable = unusable;
1586 }
1587 
1588 void btrfs_redirty_list_add(struct btrfs_transaction *trans,
1589 			    struct extent_buffer *eb)
1590 {
1591 	struct btrfs_fs_info *fs_info = eb->fs_info;
1592 
1593 	if (!btrfs_is_zoned(fs_info) ||
1594 	    btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN) ||
1595 	    !list_empty(&eb->release_list))
1596 		return;
1597 
1598 	set_extent_buffer_dirty(eb);
1599 	set_extent_bits_nowait(&trans->dirty_pages, eb->start,
1600 			       eb->start + eb->len - 1, EXTENT_DIRTY);
1601 	memzero_extent_buffer(eb, 0, eb->len);
1602 	set_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags);
1603 
1604 	spin_lock(&trans->releasing_ebs_lock);
1605 	list_add_tail(&eb->release_list, &trans->releasing_ebs);
1606 	spin_unlock(&trans->releasing_ebs_lock);
1607 	atomic_inc(&eb->refs);
1608 }
1609 
1610 void btrfs_free_redirty_list(struct btrfs_transaction *trans)
1611 {
1612 	spin_lock(&trans->releasing_ebs_lock);
1613 	while (!list_empty(&trans->releasing_ebs)) {
1614 		struct extent_buffer *eb;
1615 
1616 		eb = list_first_entry(&trans->releasing_ebs,
1617 				      struct extent_buffer, release_list);
1618 		list_del_init(&eb->release_list);
1619 		free_extent_buffer(eb);
1620 	}
1621 	spin_unlock(&trans->releasing_ebs_lock);
1622 }
1623 
1624 bool btrfs_use_zone_append(struct btrfs_inode *inode, u64 start)
1625 {
1626 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1627 	struct btrfs_block_group *cache;
1628 	bool ret = false;
1629 
1630 	if (!btrfs_is_zoned(fs_info))
1631 		return false;
1632 
1633 	if (!is_data_inode(&inode->vfs_inode))
1634 		return false;
1635 
1636 	/*
1637 	 * Using REQ_OP_ZONE_APPNED for relocation can break assumptions on the
1638 	 * extent layout the relocation code has.
1639 	 * Furthermore we have set aside own block-group from which only the
1640 	 * relocation "process" can allocate and make sure only one process at a
1641 	 * time can add pages to an extent that gets relocated, so it's safe to
1642 	 * use regular REQ_OP_WRITE for this special case.
1643 	 */
1644 	if (btrfs_is_data_reloc_root(inode->root))
1645 		return false;
1646 
1647 	cache = btrfs_lookup_block_group(fs_info, start);
1648 	ASSERT(cache);
1649 	if (!cache)
1650 		return false;
1651 
1652 	ret = !!test_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &cache->runtime_flags);
1653 	btrfs_put_block_group(cache);
1654 
1655 	return ret;
1656 }
1657 
1658 void btrfs_record_physical_zoned(struct inode *inode, u64 file_offset,
1659 				 struct bio *bio)
1660 {
1661 	struct btrfs_ordered_extent *ordered;
1662 	const u64 physical = bio->bi_iter.bi_sector << SECTOR_SHIFT;
1663 
1664 	if (bio_op(bio) != REQ_OP_ZONE_APPEND)
1665 		return;
1666 
1667 	ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), file_offset);
1668 	if (WARN_ON(!ordered))
1669 		return;
1670 
1671 	ordered->physical = physical;
1672 	ordered->bdev = bio->bi_bdev;
1673 
1674 	btrfs_put_ordered_extent(ordered);
1675 }
1676 
1677 void btrfs_rewrite_logical_zoned(struct btrfs_ordered_extent *ordered)
1678 {
1679 	struct btrfs_inode *inode = BTRFS_I(ordered->inode);
1680 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1681 	struct extent_map_tree *em_tree;
1682 	struct extent_map *em;
1683 	struct btrfs_ordered_sum *sum;
1684 	u64 orig_logical = ordered->disk_bytenr;
1685 	u64 *logical = NULL;
1686 	int nr, stripe_len;
1687 
1688 	/* Zoned devices should not have partitions. So, we can assume it is 0 */
1689 	ASSERT(!bdev_is_partition(ordered->bdev));
1690 	if (WARN_ON(!ordered->bdev))
1691 		return;
1692 
1693 	if (WARN_ON(btrfs_rmap_block(fs_info, orig_logical, ordered->bdev,
1694 				     ordered->physical, &logical, &nr,
1695 				     &stripe_len)))
1696 		goto out;
1697 
1698 	WARN_ON(nr != 1);
1699 
1700 	if (orig_logical == *logical)
1701 		goto out;
1702 
1703 	ordered->disk_bytenr = *logical;
1704 
1705 	em_tree = &inode->extent_tree;
1706 	write_lock(&em_tree->lock);
1707 	em = search_extent_mapping(em_tree, ordered->file_offset,
1708 				   ordered->num_bytes);
1709 	em->block_start = *logical;
1710 	free_extent_map(em);
1711 	write_unlock(&em_tree->lock);
1712 
1713 	list_for_each_entry(sum, &ordered->list, list) {
1714 		if (*logical < orig_logical)
1715 			sum->bytenr -= orig_logical - *logical;
1716 		else
1717 			sum->bytenr += *logical - orig_logical;
1718 	}
1719 
1720 out:
1721 	kfree(logical);
1722 }
1723 
1724 bool btrfs_check_meta_write_pointer(struct btrfs_fs_info *fs_info,
1725 				    struct extent_buffer *eb,
1726 				    struct btrfs_block_group **cache_ret)
1727 {
1728 	struct btrfs_block_group *cache;
1729 	bool ret = true;
1730 
1731 	if (!btrfs_is_zoned(fs_info))
1732 		return true;
1733 
1734 	cache = btrfs_lookup_block_group(fs_info, eb->start);
1735 	if (!cache)
1736 		return true;
1737 
1738 	if (cache->meta_write_pointer != eb->start) {
1739 		btrfs_put_block_group(cache);
1740 		cache = NULL;
1741 		ret = false;
1742 	} else {
1743 		cache->meta_write_pointer = eb->start + eb->len;
1744 	}
1745 
1746 	*cache_ret = cache;
1747 
1748 	return ret;
1749 }
1750 
1751 void btrfs_revert_meta_write_pointer(struct btrfs_block_group *cache,
1752 				     struct extent_buffer *eb)
1753 {
1754 	if (!btrfs_is_zoned(eb->fs_info) || !cache)
1755 		return;
1756 
1757 	ASSERT(cache->meta_write_pointer == eb->start + eb->len);
1758 	cache->meta_write_pointer = eb->start;
1759 }
1760 
1761 int btrfs_zoned_issue_zeroout(struct btrfs_device *device, u64 physical, u64 length)
1762 {
1763 	if (!btrfs_dev_is_sequential(device, physical))
1764 		return -EOPNOTSUPP;
1765 
1766 	return blkdev_issue_zeroout(device->bdev, physical >> SECTOR_SHIFT,
1767 				    length >> SECTOR_SHIFT, GFP_NOFS, 0);
1768 }
1769 
1770 static int read_zone_info(struct btrfs_fs_info *fs_info, u64 logical,
1771 			  struct blk_zone *zone)
1772 {
1773 	struct btrfs_io_context *bioc = NULL;
1774 	u64 mapped_length = PAGE_SIZE;
1775 	unsigned int nofs_flag;
1776 	int nmirrors;
1777 	int i, ret;
1778 
1779 	ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
1780 			       &mapped_length, &bioc);
1781 	if (ret || !bioc || mapped_length < PAGE_SIZE) {
1782 		ret = -EIO;
1783 		goto out_put_bioc;
1784 	}
1785 
1786 	if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
1787 		ret = -EINVAL;
1788 		goto out_put_bioc;
1789 	}
1790 
1791 	nofs_flag = memalloc_nofs_save();
1792 	nmirrors = (int)bioc->num_stripes;
1793 	for (i = 0; i < nmirrors; i++) {
1794 		u64 physical = bioc->stripes[i].physical;
1795 		struct btrfs_device *dev = bioc->stripes[i].dev;
1796 
1797 		/* Missing device */
1798 		if (!dev->bdev)
1799 			continue;
1800 
1801 		ret = btrfs_get_dev_zone(dev, physical, zone);
1802 		/* Failing device */
1803 		if (ret == -EIO || ret == -EOPNOTSUPP)
1804 			continue;
1805 		break;
1806 	}
1807 	memalloc_nofs_restore(nofs_flag);
1808 out_put_bioc:
1809 	btrfs_put_bioc(bioc);
1810 	return ret;
1811 }
1812 
1813 /*
1814  * Synchronize write pointer in a zone at @physical_start on @tgt_dev, by
1815  * filling zeros between @physical_pos to a write pointer of dev-replace
1816  * source device.
1817  */
1818 int btrfs_sync_zone_write_pointer(struct btrfs_device *tgt_dev, u64 logical,
1819 				    u64 physical_start, u64 physical_pos)
1820 {
1821 	struct btrfs_fs_info *fs_info = tgt_dev->fs_info;
1822 	struct blk_zone zone;
1823 	u64 length;
1824 	u64 wp;
1825 	int ret;
1826 
1827 	if (!btrfs_dev_is_sequential(tgt_dev, physical_pos))
1828 		return 0;
1829 
1830 	ret = read_zone_info(fs_info, logical, &zone);
1831 	if (ret)
1832 		return ret;
1833 
1834 	wp = physical_start + ((zone.wp - zone.start) << SECTOR_SHIFT);
1835 
1836 	if (physical_pos == wp)
1837 		return 0;
1838 
1839 	if (physical_pos > wp)
1840 		return -EUCLEAN;
1841 
1842 	length = wp - physical_pos;
1843 	return btrfs_zoned_issue_zeroout(tgt_dev, physical_pos, length);
1844 }
1845 
1846 struct btrfs_device *btrfs_zoned_get_device(struct btrfs_fs_info *fs_info,
1847 					    u64 logical, u64 length)
1848 {
1849 	struct btrfs_device *device;
1850 	struct extent_map *em;
1851 	struct map_lookup *map;
1852 
1853 	em = btrfs_get_chunk_map(fs_info, logical, length);
1854 	if (IS_ERR(em))
1855 		return ERR_CAST(em);
1856 
1857 	map = em->map_lookup;
1858 	/* We only support single profile for now */
1859 	device = map->stripes[0].dev;
1860 
1861 	free_extent_map(em);
1862 
1863 	return device;
1864 }
1865 
1866 /*
1867  * Activate block group and underlying device zones
1868  *
1869  * @block_group: the block group to activate
1870  *
1871  * Return: true on success, false otherwise
1872  */
1873 bool btrfs_zone_activate(struct btrfs_block_group *block_group)
1874 {
1875 	struct btrfs_fs_info *fs_info = block_group->fs_info;
1876 	struct btrfs_space_info *space_info = block_group->space_info;
1877 	struct map_lookup *map;
1878 	struct btrfs_device *device;
1879 	u64 physical;
1880 	bool ret;
1881 	int i;
1882 
1883 	if (!btrfs_is_zoned(block_group->fs_info))
1884 		return true;
1885 
1886 	map = block_group->physical_map;
1887 
1888 	spin_lock(&space_info->lock);
1889 	spin_lock(&block_group->lock);
1890 	if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
1891 		ret = true;
1892 		goto out_unlock;
1893 	}
1894 
1895 	/* No space left */
1896 	if (btrfs_zoned_bg_is_full(block_group)) {
1897 		ret = false;
1898 		goto out_unlock;
1899 	}
1900 
1901 	for (i = 0; i < map->num_stripes; i++) {
1902 		device = map->stripes[i].dev;
1903 		physical = map->stripes[i].physical;
1904 
1905 		if (device->zone_info->max_active_zones == 0)
1906 			continue;
1907 
1908 		if (!btrfs_dev_set_active_zone(device, physical)) {
1909 			/* Cannot activate the zone */
1910 			ret = false;
1911 			goto out_unlock;
1912 		}
1913 	}
1914 
1915 	/* Successfully activated all the zones */
1916 	set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
1917 	space_info->active_total_bytes += block_group->length;
1918 	spin_unlock(&block_group->lock);
1919 	btrfs_try_granting_tickets(fs_info, space_info);
1920 	spin_unlock(&space_info->lock);
1921 
1922 	/* For the active block group list */
1923 	btrfs_get_block_group(block_group);
1924 
1925 	spin_lock(&fs_info->zone_active_bgs_lock);
1926 	list_add_tail(&block_group->active_bg_list, &fs_info->zone_active_bgs);
1927 	spin_unlock(&fs_info->zone_active_bgs_lock);
1928 
1929 	return true;
1930 
1931 out_unlock:
1932 	spin_unlock(&block_group->lock);
1933 	spin_unlock(&space_info->lock);
1934 	return ret;
1935 }
1936 
1937 static void wait_eb_writebacks(struct btrfs_block_group *block_group)
1938 {
1939 	struct btrfs_fs_info *fs_info = block_group->fs_info;
1940 	const u64 end = block_group->start + block_group->length;
1941 	struct radix_tree_iter iter;
1942 	struct extent_buffer *eb;
1943 	void __rcu **slot;
1944 
1945 	rcu_read_lock();
1946 	radix_tree_for_each_slot(slot, &fs_info->buffer_radix, &iter,
1947 				 block_group->start >> fs_info->sectorsize_bits) {
1948 		eb = radix_tree_deref_slot(slot);
1949 		if (!eb)
1950 			continue;
1951 		if (radix_tree_deref_retry(eb)) {
1952 			slot = radix_tree_iter_retry(&iter);
1953 			continue;
1954 		}
1955 
1956 		if (eb->start < block_group->start)
1957 			continue;
1958 		if (eb->start >= end)
1959 			break;
1960 
1961 		slot = radix_tree_iter_resume(slot, &iter);
1962 		rcu_read_unlock();
1963 		wait_on_extent_buffer_writeback(eb);
1964 		rcu_read_lock();
1965 	}
1966 	rcu_read_unlock();
1967 }
1968 
1969 static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_written)
1970 {
1971 	struct btrfs_fs_info *fs_info = block_group->fs_info;
1972 	struct map_lookup *map;
1973 	const bool is_metadata = (block_group->flags &
1974 			(BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM));
1975 	int ret = 0;
1976 	int i;
1977 
1978 	spin_lock(&block_group->lock);
1979 	if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
1980 		spin_unlock(&block_group->lock);
1981 		return 0;
1982 	}
1983 
1984 	/* Check if we have unwritten allocated space */
1985 	if (is_metadata &&
1986 	    block_group->start + block_group->alloc_offset > block_group->meta_write_pointer) {
1987 		spin_unlock(&block_group->lock);
1988 		return -EAGAIN;
1989 	}
1990 
1991 	/*
1992 	 * If we are sure that the block group is full (= no more room left for
1993 	 * new allocation) and the IO for the last usable block is completed, we
1994 	 * don't need to wait for the other IOs. This holds because we ensure
1995 	 * the sequential IO submissions using the ZONE_APPEND command for data
1996 	 * and block_group->meta_write_pointer for metadata.
1997 	 */
1998 	if (!fully_written) {
1999 		spin_unlock(&block_group->lock);
2000 
2001 		ret = btrfs_inc_block_group_ro(block_group, false);
2002 		if (ret)
2003 			return ret;
2004 
2005 		/* Ensure all writes in this block group finish */
2006 		btrfs_wait_block_group_reservations(block_group);
2007 		/* No need to wait for NOCOW writers. Zoned mode does not allow that */
2008 		btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group->start,
2009 					 block_group->length);
2010 		/* Wait for extent buffers to be written. */
2011 		if (is_metadata)
2012 			wait_eb_writebacks(block_group);
2013 
2014 		spin_lock(&block_group->lock);
2015 
2016 		/*
2017 		 * Bail out if someone already deactivated the block group, or
2018 		 * allocated space is left in the block group.
2019 		 */
2020 		if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2021 			      &block_group->runtime_flags)) {
2022 			spin_unlock(&block_group->lock);
2023 			btrfs_dec_block_group_ro(block_group);
2024 			return 0;
2025 		}
2026 
2027 		if (block_group->reserved) {
2028 			spin_unlock(&block_group->lock);
2029 			btrfs_dec_block_group_ro(block_group);
2030 			return -EAGAIN;
2031 		}
2032 	}
2033 
2034 	clear_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
2035 	block_group->alloc_offset = block_group->zone_capacity;
2036 	block_group->free_space_ctl->free_space = 0;
2037 	btrfs_clear_treelog_bg(block_group);
2038 	btrfs_clear_data_reloc_bg(block_group);
2039 	spin_unlock(&block_group->lock);
2040 
2041 	map = block_group->physical_map;
2042 	for (i = 0; i < map->num_stripes; i++) {
2043 		struct btrfs_device *device = map->stripes[i].dev;
2044 		const u64 physical = map->stripes[i].physical;
2045 
2046 		if (device->zone_info->max_active_zones == 0)
2047 			continue;
2048 
2049 		ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_FINISH,
2050 				       physical >> SECTOR_SHIFT,
2051 				       device->zone_info->zone_size >> SECTOR_SHIFT,
2052 				       GFP_NOFS);
2053 
2054 		if (ret)
2055 			return ret;
2056 
2057 		btrfs_dev_clear_active_zone(device, physical);
2058 	}
2059 
2060 	if (!fully_written)
2061 		btrfs_dec_block_group_ro(block_group);
2062 
2063 	spin_lock(&fs_info->zone_active_bgs_lock);
2064 	ASSERT(!list_empty(&block_group->active_bg_list));
2065 	list_del_init(&block_group->active_bg_list);
2066 	spin_unlock(&fs_info->zone_active_bgs_lock);
2067 
2068 	/* For active_bg_list */
2069 	btrfs_put_block_group(block_group);
2070 
2071 	clear_and_wake_up_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2072 
2073 	return 0;
2074 }
2075 
2076 int btrfs_zone_finish(struct btrfs_block_group *block_group)
2077 {
2078 	if (!btrfs_is_zoned(block_group->fs_info))
2079 		return 0;
2080 
2081 	return do_zone_finish(block_group, false);
2082 }
2083 
2084 bool btrfs_can_activate_zone(struct btrfs_fs_devices *fs_devices, u64 flags)
2085 {
2086 	struct btrfs_fs_info *fs_info = fs_devices->fs_info;
2087 	struct btrfs_device *device;
2088 	bool ret = false;
2089 
2090 	if (!btrfs_is_zoned(fs_info))
2091 		return true;
2092 
2093 	/* Check if there is a device with active zones left */
2094 	mutex_lock(&fs_info->chunk_mutex);
2095 	list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
2096 		struct btrfs_zoned_device_info *zinfo = device->zone_info;
2097 
2098 		if (!device->bdev)
2099 			continue;
2100 
2101 		if (!zinfo->max_active_zones ||
2102 		    atomic_read(&zinfo->active_zones_left)) {
2103 			ret = true;
2104 			break;
2105 		}
2106 	}
2107 	mutex_unlock(&fs_info->chunk_mutex);
2108 
2109 	if (!ret)
2110 		set_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2111 
2112 	return ret;
2113 }
2114 
2115 void btrfs_zone_finish_endio(struct btrfs_fs_info *fs_info, u64 logical, u64 length)
2116 {
2117 	struct btrfs_block_group *block_group;
2118 	u64 min_alloc_bytes;
2119 
2120 	if (!btrfs_is_zoned(fs_info))
2121 		return;
2122 
2123 	block_group = btrfs_lookup_block_group(fs_info, logical);
2124 	ASSERT(block_group);
2125 
2126 	/* No MIXED_BG on zoned btrfs. */
2127 	if (block_group->flags & BTRFS_BLOCK_GROUP_DATA)
2128 		min_alloc_bytes = fs_info->sectorsize;
2129 	else
2130 		min_alloc_bytes = fs_info->nodesize;
2131 
2132 	/* Bail out if we can allocate more data from this block group. */
2133 	if (logical + length + min_alloc_bytes <=
2134 	    block_group->start + block_group->zone_capacity)
2135 		goto out;
2136 
2137 	do_zone_finish(block_group, true);
2138 
2139 out:
2140 	btrfs_put_block_group(block_group);
2141 }
2142 
2143 static void btrfs_zone_finish_endio_workfn(struct work_struct *work)
2144 {
2145 	struct btrfs_block_group *bg =
2146 		container_of(work, struct btrfs_block_group, zone_finish_work);
2147 
2148 	wait_on_extent_buffer_writeback(bg->last_eb);
2149 	free_extent_buffer(bg->last_eb);
2150 	btrfs_zone_finish_endio(bg->fs_info, bg->start, bg->length);
2151 	btrfs_put_block_group(bg);
2152 }
2153 
2154 void btrfs_schedule_zone_finish_bg(struct btrfs_block_group *bg,
2155 				   struct extent_buffer *eb)
2156 {
2157 	if (!test_bit(BLOCK_GROUP_FLAG_SEQUENTIAL_ZONE, &bg->runtime_flags) ||
2158 	    eb->start + eb->len * 2 <= bg->start + bg->zone_capacity)
2159 		return;
2160 
2161 	if (WARN_ON(bg->zone_finish_work.func == btrfs_zone_finish_endio_workfn)) {
2162 		btrfs_err(bg->fs_info, "double scheduling of bg %llu zone finishing",
2163 			  bg->start);
2164 		return;
2165 	}
2166 
2167 	/* For the work */
2168 	btrfs_get_block_group(bg);
2169 	atomic_inc(&eb->refs);
2170 	bg->last_eb = eb;
2171 	INIT_WORK(&bg->zone_finish_work, btrfs_zone_finish_endio_workfn);
2172 	queue_work(system_unbound_wq, &bg->zone_finish_work);
2173 }
2174 
2175 void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg)
2176 {
2177 	struct btrfs_fs_info *fs_info = bg->fs_info;
2178 
2179 	spin_lock(&fs_info->relocation_bg_lock);
2180 	if (fs_info->data_reloc_bg == bg->start)
2181 		fs_info->data_reloc_bg = 0;
2182 	spin_unlock(&fs_info->relocation_bg_lock);
2183 }
2184 
2185 void btrfs_free_zone_cache(struct btrfs_fs_info *fs_info)
2186 {
2187 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2188 	struct btrfs_device *device;
2189 
2190 	if (!btrfs_is_zoned(fs_info))
2191 		return;
2192 
2193 	mutex_lock(&fs_devices->device_list_mutex);
2194 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2195 		if (device->zone_info) {
2196 			vfree(device->zone_info->zone_cache);
2197 			device->zone_info->zone_cache = NULL;
2198 		}
2199 	}
2200 	mutex_unlock(&fs_devices->device_list_mutex);
2201 }
2202 
2203 bool btrfs_zoned_should_reclaim(struct btrfs_fs_info *fs_info)
2204 {
2205 	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2206 	struct btrfs_device *device;
2207 	u64 used = 0;
2208 	u64 total = 0;
2209 	u64 factor;
2210 
2211 	ASSERT(btrfs_is_zoned(fs_info));
2212 
2213 	if (fs_info->bg_reclaim_threshold == 0)
2214 		return false;
2215 
2216 	mutex_lock(&fs_devices->device_list_mutex);
2217 	list_for_each_entry(device, &fs_devices->devices, dev_list) {
2218 		if (!device->bdev)
2219 			continue;
2220 
2221 		total += device->disk_total_bytes;
2222 		used += device->bytes_used;
2223 	}
2224 	mutex_unlock(&fs_devices->device_list_mutex);
2225 
2226 	factor = div64_u64(used * 100, total);
2227 	return factor >= fs_info->bg_reclaim_threshold;
2228 }
2229 
2230 void btrfs_zoned_release_data_reloc_bg(struct btrfs_fs_info *fs_info, u64 logical,
2231 				       u64 length)
2232 {
2233 	struct btrfs_block_group *block_group;
2234 
2235 	if (!btrfs_is_zoned(fs_info))
2236 		return;
2237 
2238 	block_group = btrfs_lookup_block_group(fs_info, logical);
2239 	/* It should be called on a previous data relocation block group. */
2240 	ASSERT(block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA));
2241 
2242 	spin_lock(&block_group->lock);
2243 	if (!test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))
2244 		goto out;
2245 
2246 	/* All relocation extents are written. */
2247 	if (block_group->start + block_group->alloc_offset == logical + length) {
2248 		/* Now, release this block group for further allocations. */
2249 		clear_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC,
2250 			  &block_group->runtime_flags);
2251 	}
2252 
2253 out:
2254 	spin_unlock(&block_group->lock);
2255 	btrfs_put_block_group(block_group);
2256 }
2257 
2258 int btrfs_zone_finish_one_bg(struct btrfs_fs_info *fs_info)
2259 {
2260 	struct btrfs_block_group *block_group;
2261 	struct btrfs_block_group *min_bg = NULL;
2262 	u64 min_avail = U64_MAX;
2263 	int ret;
2264 
2265 	spin_lock(&fs_info->zone_active_bgs_lock);
2266 	list_for_each_entry(block_group, &fs_info->zone_active_bgs,
2267 			    active_bg_list) {
2268 		u64 avail;
2269 
2270 		spin_lock(&block_group->lock);
2271 		if (block_group->reserved ||
2272 		    (block_group->flags & BTRFS_BLOCK_GROUP_SYSTEM)) {
2273 			spin_unlock(&block_group->lock);
2274 			continue;
2275 		}
2276 
2277 		avail = block_group->zone_capacity - block_group->alloc_offset;
2278 		if (min_avail > avail) {
2279 			if (min_bg)
2280 				btrfs_put_block_group(min_bg);
2281 			min_bg = block_group;
2282 			min_avail = avail;
2283 			btrfs_get_block_group(min_bg);
2284 		}
2285 		spin_unlock(&block_group->lock);
2286 	}
2287 	spin_unlock(&fs_info->zone_active_bgs_lock);
2288 
2289 	if (!min_bg)
2290 		return 0;
2291 
2292 	ret = btrfs_zone_finish(min_bg);
2293 	btrfs_put_block_group(min_bg);
2294 
2295 	return ret < 0 ? ret : 1;
2296 }
2297 
2298 int btrfs_zoned_activate_one_bg(struct btrfs_fs_info *fs_info,
2299 				struct btrfs_space_info *space_info,
2300 				bool do_finish)
2301 {
2302 	struct btrfs_block_group *bg;
2303 	int index;
2304 
2305 	if (!btrfs_is_zoned(fs_info) || (space_info->flags & BTRFS_BLOCK_GROUP_DATA))
2306 		return 0;
2307 
2308 	/* No more block groups to activate */
2309 	if (space_info->active_total_bytes == space_info->total_bytes)
2310 		return 0;
2311 
2312 	for (;;) {
2313 		int ret;
2314 		bool need_finish = false;
2315 
2316 		down_read(&space_info->groups_sem);
2317 		for (index = 0; index < BTRFS_NR_RAID_TYPES; index++) {
2318 			list_for_each_entry(bg, &space_info->block_groups[index],
2319 					    list) {
2320 				if (!spin_trylock(&bg->lock))
2321 					continue;
2322 				if (btrfs_zoned_bg_is_full(bg) ||
2323 				    test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2324 					     &bg->runtime_flags)) {
2325 					spin_unlock(&bg->lock);
2326 					continue;
2327 				}
2328 				spin_unlock(&bg->lock);
2329 
2330 				if (btrfs_zone_activate(bg)) {
2331 					up_read(&space_info->groups_sem);
2332 					return 1;
2333 				}
2334 
2335 				need_finish = true;
2336 			}
2337 		}
2338 		up_read(&space_info->groups_sem);
2339 
2340 		if (!do_finish || !need_finish)
2341 			break;
2342 
2343 		ret = btrfs_zone_finish_one_bg(fs_info);
2344 		if (ret == 0)
2345 			break;
2346 		if (ret < 0)
2347 			return ret;
2348 	}
2349 
2350 	return 0;
2351 }
2352