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