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