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