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