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