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