btrfs: move ffe_ctl one level up
[linux-block.git] / fs / btrfs / zoned.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include <linux/bitops.h>
4 #include <linux/slab.h>
5 #include <linux/blkdev.h>
6 #include <linux/sched/mm.h>
7 #include <linux/atomic.h>
8 #include "ctree.h"
9 #include "volumes.h"
10 #include "zoned.h"
11 #include "rcu-string.h"
12 #include "disk-io.h"
13 #include "block-group.h"
14 #include "transaction.h"
15 #include "dev-replace.h"
16 #include "space-info.h"
17
18 /* Maximum number of zones to report per blkdev_report_zones() call */
19 #define BTRFS_REPORT_NR_ZONES   4096
20 /* Invalid allocation pointer value for missing devices */
21 #define WP_MISSING_DEV ((u64)-1)
22 /* Pseudo write pointer value for conventional zone */
23 #define WP_CONVENTIONAL ((u64)-2)
24
25 /*
26  * Location of the first zone of superblock logging zone pairs.
27  *
28  * - primary superblock:    0B (zone 0)
29  * - first copy:          512G (zone starting at that offset)
30  * - second copy:           4T (zone starting at that offset)
31  */
32 #define BTRFS_SB_LOG_PRIMARY_OFFSET     (0ULL)
33 #define BTRFS_SB_LOG_FIRST_OFFSET       (512ULL * SZ_1G)
34 #define BTRFS_SB_LOG_SECOND_OFFSET      (4096ULL * SZ_1G)
35
36 #define BTRFS_SB_LOG_FIRST_SHIFT        const_ilog2(BTRFS_SB_LOG_FIRST_OFFSET)
37 #define BTRFS_SB_LOG_SECOND_SHIFT       const_ilog2(BTRFS_SB_LOG_SECOND_OFFSET)
38
39 /* Number of superblock log zones */
40 #define BTRFS_NR_SB_LOG_ZONES 2
41
42 /*
43  * Minimum of active zones we need:
44  *
45  * - BTRFS_SUPER_MIRROR_MAX zones for superblock mirrors
46  * - 3 zones to ensure at least one zone per SYSTEM, META and DATA block group
47  * - 1 zone for tree-log dedicated block group
48  * - 1 zone for relocation
49  */
50 #define BTRFS_MIN_ACTIVE_ZONES          (BTRFS_SUPER_MIRROR_MAX + 5)
51
52 /*
53  * Maximum supported zone size. Currently, SMR disks have a zone size of
54  * 256MiB, and we are expecting ZNS drives to be in the 1-4GiB range. We do not
55  * expect the zone size to become larger than 8GiB in the near future.
56  */
57 #define BTRFS_MAX_ZONE_SIZE             SZ_8G
58
59 #define SUPER_INFO_SECTORS      ((u64)BTRFS_SUPER_INFO_SIZE >> SECTOR_SHIFT)
60
61 static inline bool sb_zone_is_full(const struct blk_zone *zone)
62 {
63         return (zone->cond == BLK_ZONE_COND_FULL) ||
64                 (zone->wp + SUPER_INFO_SECTORS > zone->start + zone->capacity);
65 }
66
67 static int copy_zone_info_cb(struct blk_zone *zone, unsigned int idx, void *data)
68 {
69         struct blk_zone *zones = data;
70
71         memcpy(&zones[idx], zone, sizeof(*zone));
72
73         return 0;
74 }
75
76 static int sb_write_pointer(struct block_device *bdev, struct blk_zone *zones,
77                             u64 *wp_ret)
78 {
79         bool empty[BTRFS_NR_SB_LOG_ZONES];
80         bool full[BTRFS_NR_SB_LOG_ZONES];
81         sector_t sector;
82         int i;
83
84         for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
85                 ASSERT(zones[i].type != BLK_ZONE_TYPE_CONVENTIONAL);
86                 empty[i] = (zones[i].cond == BLK_ZONE_COND_EMPTY);
87                 full[i] = sb_zone_is_full(&zones[i]);
88         }
89
90         /*
91          * Possible states of log buffer zones
92          *
93          *           Empty[0]  In use[0]  Full[0]
94          * Empty[1]         *          x        0
95          * In use[1]        0          x        0
96          * Full[1]          1          1        C
97          *
98          * Log position:
99          *   *: Special case, no superblock is written
100          *   0: Use write pointer of zones[0]
101          *   1: Use write pointer of zones[1]
102          *   C: Compare super blocks from zones[0] and zones[1], use the latest
103          *      one determined by generation
104          *   x: Invalid state
105          */
106
107         if (empty[0] && empty[1]) {
108                 /* Special case to distinguish no superblock to read */
109                 *wp_ret = zones[0].start << SECTOR_SHIFT;
110                 return -ENOENT;
111         } else if (full[0] && full[1]) {
112                 /* Compare two super blocks */
113                 struct address_space *mapping = bdev->bd_inode->i_mapping;
114                 struct page *page[BTRFS_NR_SB_LOG_ZONES];
115                 struct btrfs_super_block *super[BTRFS_NR_SB_LOG_ZONES];
116                 int i;
117
118                 for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
119                         u64 bytenr;
120
121                         bytenr = ((zones[i].start + zones[i].len)
122                                    << SECTOR_SHIFT) - BTRFS_SUPER_INFO_SIZE;
123
124                         page[i] = read_cache_page_gfp(mapping,
125                                         bytenr >> PAGE_SHIFT, GFP_NOFS);
126                         if (IS_ERR(page[i])) {
127                                 if (i == 1)
128                                         btrfs_release_disk_super(super[0]);
129                                 return PTR_ERR(page[i]);
130                         }
131                         super[i] = page_address(page[i]);
132                 }
133
134                 if (super[0]->generation > super[1]->generation)
135                         sector = zones[1].start;
136                 else
137                         sector = zones[0].start;
138
139                 for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++)
140                         btrfs_release_disk_super(super[i]);
141         } else if (!full[0] && (empty[1] || full[1])) {
142                 sector = zones[0].wp;
143         } else if (full[0]) {
144                 sector = zones[1].wp;
145         } else {
146                 return -EUCLEAN;
147         }
148         *wp_ret = sector << SECTOR_SHIFT;
149         return 0;
150 }
151
152 /*
153  * Get the first zone number of the superblock mirror
154  */
155 static inline u32 sb_zone_number(int shift, int mirror)
156 {
157         u64 zone;
158
159         ASSERT(mirror < BTRFS_SUPER_MIRROR_MAX);
160         switch (mirror) {
161         case 0: zone = 0; break;
162         case 1: zone = 1ULL << (BTRFS_SB_LOG_FIRST_SHIFT - shift); break;
163         case 2: zone = 1ULL << (BTRFS_SB_LOG_SECOND_SHIFT - shift); break;
164         }
165
166         ASSERT(zone <= U32_MAX);
167
168         return (u32)zone;
169 }
170
171 static inline sector_t zone_start_sector(u32 zone_number,
172                                          struct block_device *bdev)
173 {
174         return (sector_t)zone_number << ilog2(bdev_zone_sectors(bdev));
175 }
176
177 static inline u64 zone_start_physical(u32 zone_number,
178                                       struct btrfs_zoned_device_info *zone_info)
179 {
180         return (u64)zone_number << zone_info->zone_size_shift;
181 }
182
183 /*
184  * Emulate blkdev_report_zones() for a non-zoned device. It slices up the block
185  * device into static sized chunks and fake a conventional zone on each of
186  * them.
187  */
188 static int emulate_report_zones(struct btrfs_device *device, u64 pos,
189                                 struct blk_zone *zones, unsigned int nr_zones)
190 {
191         const sector_t zone_sectors = device->fs_info->zone_size >> SECTOR_SHIFT;
192         sector_t bdev_size = bdev_nr_sectors(device->bdev);
193         unsigned int i;
194
195         pos >>= SECTOR_SHIFT;
196         for (i = 0; i < nr_zones; i++) {
197                 zones[i].start = i * zone_sectors + pos;
198                 zones[i].len = zone_sectors;
199                 zones[i].capacity = zone_sectors;
200                 zones[i].wp = zones[i].start + zone_sectors;
201                 zones[i].type = BLK_ZONE_TYPE_CONVENTIONAL;
202                 zones[i].cond = BLK_ZONE_COND_NOT_WP;
203
204                 if (zones[i].wp >= bdev_size) {
205                         i++;
206                         break;
207                 }
208         }
209
210         return i;
211 }
212
213 static int btrfs_get_dev_zones(struct btrfs_device *device, u64 pos,
214                                struct blk_zone *zones, unsigned int *nr_zones)
215 {
216         int ret;
217
218         if (!*nr_zones)
219                 return 0;
220
221         if (!bdev_is_zoned(device->bdev)) {
222                 ret = emulate_report_zones(device, pos, zones, *nr_zones);
223                 *nr_zones = ret;
224                 return 0;
225         }
226
227         ret = blkdev_report_zones(device->bdev, pos >> SECTOR_SHIFT, *nr_zones,
228                                   copy_zone_info_cb, zones);
229         if (ret < 0) {
230                 btrfs_err_in_rcu(device->fs_info,
231                                  "zoned: failed to read zone %llu on %s (devid %llu)",
232                                  pos, rcu_str_deref(device->name),
233                                  device->devid);
234                 return ret;
235         }
236         *nr_zones = ret;
237         if (!ret)
238                 return -EIO;
239
240         return 0;
241 }
242
243 /* The emulated zone size is determined from the size of device extent */
244 static int calculate_emulated_zone_size(struct btrfs_fs_info *fs_info)
245 {
246         struct btrfs_path *path;
247         struct btrfs_root *root = fs_info->dev_root;
248         struct btrfs_key key;
249         struct extent_buffer *leaf;
250         struct btrfs_dev_extent *dext;
251         int ret = 0;
252
253         key.objectid = 1;
254         key.type = BTRFS_DEV_EXTENT_KEY;
255         key.offset = 0;
256
257         path = btrfs_alloc_path();
258         if (!path)
259                 return -ENOMEM;
260
261         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
262         if (ret < 0)
263                 goto out;
264
265         if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
266                 ret = btrfs_next_leaf(root, path);
267                 if (ret < 0)
268                         goto out;
269                 /* No dev extents at all? Not good */
270                 if (ret > 0) {
271                         ret = -EUCLEAN;
272                         goto out;
273                 }
274         }
275
276         leaf = path->nodes[0];
277         dext = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
278         fs_info->zone_size = btrfs_dev_extent_length(leaf, dext);
279         ret = 0;
280
281 out:
282         btrfs_free_path(path);
283
284         return ret;
285 }
286
287 int btrfs_get_dev_zone_info_all_devices(struct btrfs_fs_info *fs_info)
288 {
289         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
290         struct btrfs_device *device;
291         int ret = 0;
292
293         /* fs_info->zone_size might not set yet. Use the incomapt flag here. */
294         if (!btrfs_fs_incompat(fs_info, ZONED))
295                 return 0;
296
297         mutex_lock(&fs_devices->device_list_mutex);
298         list_for_each_entry(device, &fs_devices->devices, dev_list) {
299                 /* We can skip reading of zone info for missing devices */
300                 if (!device->bdev)
301                         continue;
302
303                 ret = btrfs_get_dev_zone_info(device);
304                 if (ret)
305                         break;
306         }
307         mutex_unlock(&fs_devices->device_list_mutex);
308
309         return ret;
310 }
311
312 int btrfs_get_dev_zone_info(struct btrfs_device *device)
313 {
314         struct btrfs_fs_info *fs_info = device->fs_info;
315         struct btrfs_zoned_device_info *zone_info = NULL;
316         struct block_device *bdev = device->bdev;
317         struct request_queue *queue = bdev_get_queue(bdev);
318         unsigned int max_active_zones;
319         unsigned int nactive;
320         sector_t nr_sectors;
321         sector_t sector = 0;
322         struct blk_zone *zones = NULL;
323         unsigned int i, nreported = 0, nr_zones;
324         sector_t zone_sectors;
325         char *model, *emulated;
326         int ret;
327
328         /*
329          * Cannot use btrfs_is_zoned here, since fs_info::zone_size might not
330          * yet be set.
331          */
332         if (!btrfs_fs_incompat(fs_info, ZONED))
333                 return 0;
334
335         if (device->zone_info)
336                 return 0;
337
338         zone_info = kzalloc(sizeof(*zone_info), GFP_KERNEL);
339         if (!zone_info)
340                 return -ENOMEM;
341
342         if (!bdev_is_zoned(bdev)) {
343                 if (!fs_info->zone_size) {
344                         ret = calculate_emulated_zone_size(fs_info);
345                         if (ret)
346                                 goto out;
347                 }
348
349                 ASSERT(fs_info->zone_size);
350                 zone_sectors = fs_info->zone_size >> SECTOR_SHIFT;
351         } else {
352                 zone_sectors = bdev_zone_sectors(bdev);
353         }
354
355         /* Check if it's power of 2 (see is_power_of_2) */
356         ASSERT(zone_sectors != 0 && (zone_sectors & (zone_sectors - 1)) == 0);
357         zone_info->zone_size = zone_sectors << SECTOR_SHIFT;
358
359         /* We reject devices with a zone size larger than 8GB */
360         if (zone_info->zone_size > BTRFS_MAX_ZONE_SIZE) {
361                 btrfs_err_in_rcu(fs_info,
362                 "zoned: %s: zone size %llu larger than supported maximum %llu",
363                                  rcu_str_deref(device->name),
364                                  zone_info->zone_size, BTRFS_MAX_ZONE_SIZE);
365                 ret = -EINVAL;
366                 goto out;
367         }
368
369         nr_sectors = bdev_nr_sectors(bdev);
370         zone_info->zone_size_shift = ilog2(zone_info->zone_size);
371         zone_info->nr_zones = nr_sectors >> ilog2(zone_sectors);
372         if (!IS_ALIGNED(nr_sectors, zone_sectors))
373                 zone_info->nr_zones++;
374
375         max_active_zones = queue_max_active_zones(queue);
376         if (max_active_zones && max_active_zones < BTRFS_MIN_ACTIVE_ZONES) {
377                 btrfs_err_in_rcu(fs_info,
378 "zoned: %s: max active zones %u is too small, need at least %u active zones",
379                                  rcu_str_deref(device->name), max_active_zones,
380                                  BTRFS_MIN_ACTIVE_ZONES);
381                 ret = -EINVAL;
382                 goto out;
383         }
384         zone_info->max_active_zones = max_active_zones;
385
386         zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
387         if (!zone_info->seq_zones) {
388                 ret = -ENOMEM;
389                 goto out;
390         }
391
392         zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
393         if (!zone_info->empty_zones) {
394                 ret = -ENOMEM;
395                 goto out;
396         }
397
398         zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
399         if (!zone_info->active_zones) {
400                 ret = -ENOMEM;
401                 goto out;
402         }
403
404         zones = kcalloc(BTRFS_REPORT_NR_ZONES, sizeof(struct blk_zone), GFP_KERNEL);
405         if (!zones) {
406                 ret = -ENOMEM;
407                 goto out;
408         }
409
410         /* Get zones type */
411         nactive = 0;
412         while (sector < nr_sectors) {
413                 nr_zones = BTRFS_REPORT_NR_ZONES;
414                 ret = btrfs_get_dev_zones(device, sector << SECTOR_SHIFT, zones,
415                                           &nr_zones);
416                 if (ret)
417                         goto out;
418
419                 for (i = 0; i < nr_zones; i++) {
420                         if (zones[i].type == BLK_ZONE_TYPE_SEQWRITE_REQ)
421                                 __set_bit(nreported, zone_info->seq_zones);
422                         switch (zones[i].cond) {
423                         case BLK_ZONE_COND_EMPTY:
424                                 __set_bit(nreported, zone_info->empty_zones);
425                                 break;
426                         case BLK_ZONE_COND_IMP_OPEN:
427                         case BLK_ZONE_COND_EXP_OPEN:
428                         case BLK_ZONE_COND_CLOSED:
429                                 __set_bit(nreported, zone_info->active_zones);
430                                 nactive++;
431                                 break;
432                         }
433                         nreported++;
434                 }
435                 sector = zones[nr_zones - 1].start + zones[nr_zones - 1].len;
436         }
437
438         if (nreported != zone_info->nr_zones) {
439                 btrfs_err_in_rcu(device->fs_info,
440                                  "inconsistent number of zones on %s (%u/%u)",
441                                  rcu_str_deref(device->name), nreported,
442                                  zone_info->nr_zones);
443                 ret = -EIO;
444                 goto out;
445         }
446
447         if (max_active_zones) {
448                 if (nactive > max_active_zones) {
449                         btrfs_err_in_rcu(device->fs_info,
450                         "zoned: %u active zones on %s exceeds max_active_zones %u",
451                                          nactive, rcu_str_deref(device->name),
452                                          max_active_zones);
453                         ret = -EIO;
454                         goto out;
455                 }
456                 atomic_set(&zone_info->active_zones_left,
457                            max_active_zones - nactive);
458         }
459
460         /* Validate superblock log */
461         nr_zones = BTRFS_NR_SB_LOG_ZONES;
462         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
463                 u32 sb_zone;
464                 u64 sb_wp;
465                 int sb_pos = BTRFS_NR_SB_LOG_ZONES * i;
466
467                 sb_zone = sb_zone_number(zone_info->zone_size_shift, i);
468                 if (sb_zone + 1 >= zone_info->nr_zones)
469                         continue;
470
471                 ret = btrfs_get_dev_zones(device,
472                                           zone_start_physical(sb_zone, zone_info),
473                                           &zone_info->sb_zones[sb_pos],
474                                           &nr_zones);
475                 if (ret)
476                         goto out;
477
478                 if (nr_zones != BTRFS_NR_SB_LOG_ZONES) {
479                         btrfs_err_in_rcu(device->fs_info,
480         "zoned: failed to read super block log zone info at devid %llu zone %u",
481                                          device->devid, sb_zone);
482                         ret = -EUCLEAN;
483                         goto out;
484                 }
485
486                 /*
487                  * If zones[0] is conventional, always use the beginning of the
488                  * zone to record superblock. No need to validate in that case.
489                  */
490                 if (zone_info->sb_zones[BTRFS_NR_SB_LOG_ZONES * i].type ==
491                     BLK_ZONE_TYPE_CONVENTIONAL)
492                         continue;
493
494                 ret = sb_write_pointer(device->bdev,
495                                        &zone_info->sb_zones[sb_pos], &sb_wp);
496                 if (ret != -ENOENT && ret) {
497                         btrfs_err_in_rcu(device->fs_info,
498                         "zoned: super block log zone corrupted devid %llu zone %u",
499                                          device->devid, sb_zone);
500                         ret = -EUCLEAN;
501                         goto out;
502                 }
503         }
504
505
506         kfree(zones);
507
508         device->zone_info = zone_info;
509
510         switch (bdev_zoned_model(bdev)) {
511         case BLK_ZONED_HM:
512                 model = "host-managed zoned";
513                 emulated = "";
514                 break;
515         case BLK_ZONED_HA:
516                 model = "host-aware zoned";
517                 emulated = "";
518                 break;
519         case BLK_ZONED_NONE:
520                 model = "regular";
521                 emulated = "emulated ";
522                 break;
523         default:
524                 /* Just in case */
525                 btrfs_err_in_rcu(fs_info, "zoned: unsupported model %d on %s",
526                                  bdev_zoned_model(bdev),
527                                  rcu_str_deref(device->name));
528                 ret = -EOPNOTSUPP;
529                 goto out_free_zone_info;
530         }
531
532         btrfs_info_in_rcu(fs_info,
533                 "%s block device %s, %u %szones of %llu bytes",
534                 model, rcu_str_deref(device->name), zone_info->nr_zones,
535                 emulated, zone_info->zone_size);
536
537         return 0;
538
539 out:
540         kfree(zones);
541 out_free_zone_info:
542         bitmap_free(zone_info->active_zones);
543         bitmap_free(zone_info->empty_zones);
544         bitmap_free(zone_info->seq_zones);
545         kfree(zone_info);
546         device->zone_info = NULL;
547
548         return ret;
549 }
550
551 void btrfs_destroy_dev_zone_info(struct btrfs_device *device)
552 {
553         struct btrfs_zoned_device_info *zone_info = device->zone_info;
554
555         if (!zone_info)
556                 return;
557
558         bitmap_free(zone_info->active_zones);
559         bitmap_free(zone_info->seq_zones);
560         bitmap_free(zone_info->empty_zones);
561         kfree(zone_info);
562         device->zone_info = NULL;
563 }
564
565 int btrfs_get_dev_zone(struct btrfs_device *device, u64 pos,
566                        struct blk_zone *zone)
567 {
568         unsigned int nr_zones = 1;
569         int ret;
570
571         ret = btrfs_get_dev_zones(device, pos, zone, &nr_zones);
572         if (ret != 0 || !nr_zones)
573                 return ret ? ret : -EIO;
574
575         return 0;
576 }
577
578 int btrfs_check_zoned_mode(struct btrfs_fs_info *fs_info)
579 {
580         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
581         struct btrfs_device *device;
582         u64 zoned_devices = 0;
583         u64 nr_devices = 0;
584         u64 zone_size = 0;
585         const bool incompat_zoned = btrfs_fs_incompat(fs_info, ZONED);
586         int ret = 0;
587
588         /* Count zoned devices */
589         list_for_each_entry(device, &fs_devices->devices, dev_list) {
590                 enum blk_zoned_model model;
591
592                 if (!device->bdev)
593                         continue;
594
595                 model = bdev_zoned_model(device->bdev);
596                 /*
597                  * A Host-Managed zoned device must be used as a zoned device.
598                  * A Host-Aware zoned device and a non-zoned devices can be
599                  * treated as a zoned device, if ZONED flag is enabled in the
600                  * superblock.
601                  */
602                 if (model == BLK_ZONED_HM ||
603                     (model == BLK_ZONED_HA && incompat_zoned) ||
604                     (model == BLK_ZONED_NONE && incompat_zoned)) {
605                         struct btrfs_zoned_device_info *zone_info =
606                                 device->zone_info;
607
608                         zone_info = device->zone_info;
609                         zoned_devices++;
610                         if (!zone_size) {
611                                 zone_size = zone_info->zone_size;
612                         } else if (zone_info->zone_size != zone_size) {
613                                 btrfs_err(fs_info,
614                 "zoned: unequal block device zone sizes: have %llu found %llu",
615                                           device->zone_info->zone_size,
616                                           zone_size);
617                                 ret = -EINVAL;
618                                 goto out;
619                         }
620                 }
621                 nr_devices++;
622         }
623
624         if (!zoned_devices && !incompat_zoned)
625                 goto out;
626
627         if (!zoned_devices && incompat_zoned) {
628                 /* No zoned block device found on ZONED filesystem */
629                 btrfs_err(fs_info,
630                           "zoned: no zoned devices found on a zoned filesystem");
631                 ret = -EINVAL;
632                 goto out;
633         }
634
635         if (zoned_devices && !incompat_zoned) {
636                 btrfs_err(fs_info,
637                           "zoned: mode not enabled but zoned device found");
638                 ret = -EINVAL;
639                 goto out;
640         }
641
642         if (zoned_devices != nr_devices) {
643                 btrfs_err(fs_info,
644                           "zoned: cannot mix zoned and regular devices");
645                 ret = -EINVAL;
646                 goto out;
647         }
648
649         /*
650          * stripe_size is always aligned to BTRFS_STRIPE_LEN in
651          * btrfs_create_chunk(). Since we want stripe_len == zone_size,
652          * check the alignment here.
653          */
654         if (!IS_ALIGNED(zone_size, BTRFS_STRIPE_LEN)) {
655                 btrfs_err(fs_info,
656                           "zoned: zone size %llu not aligned to stripe %u",
657                           zone_size, BTRFS_STRIPE_LEN);
658                 ret = -EINVAL;
659                 goto out;
660         }
661
662         if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
663                 btrfs_err(fs_info, "zoned: mixed block groups not supported");
664                 ret = -EINVAL;
665                 goto out;
666         }
667
668         fs_info->zone_size = zone_size;
669         fs_info->fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_ZONED;
670
671         /*
672          * Check mount options here, because we might change fs_info->zoned
673          * from fs_info->zone_size.
674          */
675         ret = btrfs_check_mountopts_zoned(fs_info);
676         if (ret)
677                 goto out;
678
679         btrfs_info(fs_info, "zoned mode enabled with zone size %llu", zone_size);
680 out:
681         return ret;
682 }
683
684 int btrfs_check_mountopts_zoned(struct btrfs_fs_info *info)
685 {
686         if (!btrfs_is_zoned(info))
687                 return 0;
688
689         /*
690          * Space cache writing is not COWed. Disable that to avoid write errors
691          * in sequential zones.
692          */
693         if (btrfs_test_opt(info, SPACE_CACHE)) {
694                 btrfs_err(info, "zoned: space cache v1 is not supported");
695                 return -EINVAL;
696         }
697
698         if (btrfs_test_opt(info, NODATACOW)) {
699                 btrfs_err(info, "zoned: NODATACOW not supported");
700                 return -EINVAL;
701         }
702
703         return 0;
704 }
705
706 static int sb_log_location(struct block_device *bdev, struct blk_zone *zones,
707                            int rw, u64 *bytenr_ret)
708 {
709         u64 wp;
710         int ret;
711
712         if (zones[0].type == BLK_ZONE_TYPE_CONVENTIONAL) {
713                 *bytenr_ret = zones[0].start << SECTOR_SHIFT;
714                 return 0;
715         }
716
717         ret = sb_write_pointer(bdev, zones, &wp);
718         if (ret != -ENOENT && ret < 0)
719                 return ret;
720
721         if (rw == WRITE) {
722                 struct blk_zone *reset = NULL;
723
724                 if (wp == zones[0].start << SECTOR_SHIFT)
725                         reset = &zones[0];
726                 else if (wp == zones[1].start << SECTOR_SHIFT)
727                         reset = &zones[1];
728
729                 if (reset && reset->cond != BLK_ZONE_COND_EMPTY) {
730                         ASSERT(sb_zone_is_full(reset));
731
732                         ret = blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
733                                                reset->start, reset->len,
734                                                GFP_NOFS);
735                         if (ret)
736                                 return ret;
737
738                         reset->cond = BLK_ZONE_COND_EMPTY;
739                         reset->wp = reset->start;
740                 }
741         } else if (ret != -ENOENT) {
742                 /*
743                  * For READ, we want the previous one. Move write pointer to
744                  * the end of a zone, if it is at the head of a zone.
745                  */
746                 u64 zone_end = 0;
747
748                 if (wp == zones[0].start << SECTOR_SHIFT)
749                         zone_end = zones[1].start + zones[1].capacity;
750                 else if (wp == zones[1].start << SECTOR_SHIFT)
751                         zone_end = zones[0].start + zones[0].capacity;
752                 if (zone_end)
753                         wp = ALIGN_DOWN(zone_end << SECTOR_SHIFT,
754                                         BTRFS_SUPER_INFO_SIZE);
755
756                 wp -= BTRFS_SUPER_INFO_SIZE;
757         }
758
759         *bytenr_ret = wp;
760         return 0;
761
762 }
763
764 int btrfs_sb_log_location_bdev(struct block_device *bdev, int mirror, int rw,
765                                u64 *bytenr_ret)
766 {
767         struct blk_zone zones[BTRFS_NR_SB_LOG_ZONES];
768         sector_t zone_sectors;
769         u32 sb_zone;
770         int ret;
771         u8 zone_sectors_shift;
772         sector_t nr_sectors;
773         u32 nr_zones;
774
775         if (!bdev_is_zoned(bdev)) {
776                 *bytenr_ret = btrfs_sb_offset(mirror);
777                 return 0;
778         }
779
780         ASSERT(rw == READ || rw == WRITE);
781
782         zone_sectors = bdev_zone_sectors(bdev);
783         if (!is_power_of_2(zone_sectors))
784                 return -EINVAL;
785         zone_sectors_shift = ilog2(zone_sectors);
786         nr_sectors = bdev_nr_sectors(bdev);
787         nr_zones = nr_sectors >> zone_sectors_shift;
788
789         sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
790         if (sb_zone + 1 >= nr_zones)
791                 return -ENOENT;
792
793         ret = blkdev_report_zones(bdev, zone_start_sector(sb_zone, bdev),
794                                   BTRFS_NR_SB_LOG_ZONES, copy_zone_info_cb,
795                                   zones);
796         if (ret < 0)
797                 return ret;
798         if (ret != BTRFS_NR_SB_LOG_ZONES)
799                 return -EIO;
800
801         return sb_log_location(bdev, zones, rw, bytenr_ret);
802 }
803
804 int btrfs_sb_log_location(struct btrfs_device *device, int mirror, int rw,
805                           u64 *bytenr_ret)
806 {
807         struct btrfs_zoned_device_info *zinfo = device->zone_info;
808         u32 zone_num;
809
810         /*
811          * For a zoned filesystem on a non-zoned block device, use the same
812          * super block locations as regular filesystem. Doing so, the super
813          * block can always be retrieved and the zoned flag of the volume
814          * detected from the super block information.
815          */
816         if (!bdev_is_zoned(device->bdev)) {
817                 *bytenr_ret = btrfs_sb_offset(mirror);
818                 return 0;
819         }
820
821         zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
822         if (zone_num + 1 >= zinfo->nr_zones)
823                 return -ENOENT;
824
825         return sb_log_location(device->bdev,
826                                &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror],
827                                rw, bytenr_ret);
828 }
829
830 static inline bool is_sb_log_zone(struct btrfs_zoned_device_info *zinfo,
831                                   int mirror)
832 {
833         u32 zone_num;
834
835         if (!zinfo)
836                 return false;
837
838         zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
839         if (zone_num + 1 >= zinfo->nr_zones)
840                 return false;
841
842         if (!test_bit(zone_num, zinfo->seq_zones))
843                 return false;
844
845         return true;
846 }
847
848 int btrfs_advance_sb_log(struct btrfs_device *device, int mirror)
849 {
850         struct btrfs_zoned_device_info *zinfo = device->zone_info;
851         struct blk_zone *zone;
852         int i;
853
854         if (!is_sb_log_zone(zinfo, mirror))
855                 return 0;
856
857         zone = &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror];
858         for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
859                 /* Advance the next zone */
860                 if (zone->cond == BLK_ZONE_COND_FULL) {
861                         zone++;
862                         continue;
863                 }
864
865                 if (zone->cond == BLK_ZONE_COND_EMPTY)
866                         zone->cond = BLK_ZONE_COND_IMP_OPEN;
867
868                 zone->wp += SUPER_INFO_SECTORS;
869
870                 if (sb_zone_is_full(zone)) {
871                         /*
872                          * No room left to write new superblock. Since
873                          * superblock is written with REQ_SYNC, it is safe to
874                          * finish the zone now.
875                          *
876                          * If the write pointer is exactly at the capacity,
877                          * explicit ZONE_FINISH is not necessary.
878                          */
879                         if (zone->wp != zone->start + zone->capacity) {
880                                 int ret;
881
882                                 ret = blkdev_zone_mgmt(device->bdev,
883                                                 REQ_OP_ZONE_FINISH, zone->start,
884                                                 zone->len, GFP_NOFS);
885                                 if (ret)
886                                         return ret;
887                         }
888
889                         zone->wp = zone->start + zone->len;
890                         zone->cond = BLK_ZONE_COND_FULL;
891                 }
892                 return 0;
893         }
894
895         /* All the zones are FULL. Should not reach here. */
896         ASSERT(0);
897         return -EIO;
898 }
899
900 int btrfs_reset_sb_log_zones(struct block_device *bdev, int mirror)
901 {
902         sector_t zone_sectors;
903         sector_t nr_sectors;
904         u8 zone_sectors_shift;
905         u32 sb_zone;
906         u32 nr_zones;
907
908         zone_sectors = bdev_zone_sectors(bdev);
909         zone_sectors_shift = ilog2(zone_sectors);
910         nr_sectors = bdev_nr_sectors(bdev);
911         nr_zones = nr_sectors >> zone_sectors_shift;
912
913         sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
914         if (sb_zone + 1 >= nr_zones)
915                 return -ENOENT;
916
917         return blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
918                                 zone_start_sector(sb_zone, bdev),
919                                 zone_sectors * BTRFS_NR_SB_LOG_ZONES, GFP_NOFS);
920 }
921
922 /**
923  * btrfs_find_allocatable_zones - find allocatable zones within a given region
924  *
925  * @device:     the device to allocate a region on
926  * @hole_start: the position of the hole to allocate the region
927  * @num_bytes:  size of wanted region
928  * @hole_end:   the end of the hole
929  * @return:     position of allocatable zones
930  *
931  * Allocatable region should not contain any superblock locations.
932  */
933 u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start,
934                                  u64 hole_end, u64 num_bytes)
935 {
936         struct btrfs_zoned_device_info *zinfo = device->zone_info;
937         const u8 shift = zinfo->zone_size_shift;
938         u64 nzones = num_bytes >> shift;
939         u64 pos = hole_start;
940         u64 begin, end;
941         bool have_sb;
942         int i;
943
944         ASSERT(IS_ALIGNED(hole_start, zinfo->zone_size));
945         ASSERT(IS_ALIGNED(num_bytes, zinfo->zone_size));
946
947         while (pos < hole_end) {
948                 begin = pos >> shift;
949                 end = begin + nzones;
950
951                 if (end > zinfo->nr_zones)
952                         return hole_end;
953
954                 /* Check if zones in the region are all empty */
955                 if (btrfs_dev_is_sequential(device, pos) &&
956                     find_next_zero_bit(zinfo->empty_zones, end, begin) != end) {
957                         pos += zinfo->zone_size;
958                         continue;
959                 }
960
961                 have_sb = false;
962                 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
963                         u32 sb_zone;
964                         u64 sb_pos;
965
966                         sb_zone = sb_zone_number(shift, i);
967                         if (!(end <= sb_zone ||
968                               sb_zone + BTRFS_NR_SB_LOG_ZONES <= begin)) {
969                                 have_sb = true;
970                                 pos = zone_start_physical(
971                                         sb_zone + BTRFS_NR_SB_LOG_ZONES, zinfo);
972                                 break;
973                         }
974
975                         /* We also need to exclude regular superblock positions */
976                         sb_pos = btrfs_sb_offset(i);
977                         if (!(pos + num_bytes <= sb_pos ||
978                               sb_pos + BTRFS_SUPER_INFO_SIZE <= pos)) {
979                                 have_sb = true;
980                                 pos = ALIGN(sb_pos + BTRFS_SUPER_INFO_SIZE,
981                                             zinfo->zone_size);
982                                 break;
983                         }
984                 }
985                 if (!have_sb)
986                         break;
987         }
988
989         return pos;
990 }
991
992 static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos)
993 {
994         struct btrfs_zoned_device_info *zone_info = device->zone_info;
995         unsigned int zno = (pos >> zone_info->zone_size_shift);
996
997         /* We can use any number of zones */
998         if (zone_info->max_active_zones == 0)
999                 return true;
1000
1001         if (!test_bit(zno, zone_info->active_zones)) {
1002                 /* Active zone left? */
1003                 if (atomic_dec_if_positive(&zone_info->active_zones_left) < 0)
1004                         return false;
1005                 if (test_and_set_bit(zno, zone_info->active_zones)) {
1006                         /* Someone already set the bit */
1007                         atomic_inc(&zone_info->active_zones_left);
1008                 }
1009         }
1010
1011         return true;
1012 }
1013
1014 static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos)
1015 {
1016         struct btrfs_zoned_device_info *zone_info = device->zone_info;
1017         unsigned int zno = (pos >> zone_info->zone_size_shift);
1018
1019         /* We can use any number of zones */
1020         if (zone_info->max_active_zones == 0)
1021                 return;
1022
1023         if (test_and_clear_bit(zno, zone_info->active_zones))
1024                 atomic_inc(&zone_info->active_zones_left);
1025 }
1026
1027 int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical,
1028                             u64 length, u64 *bytes)
1029 {
1030         int ret;
1031
1032         *bytes = 0;
1033         ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_RESET,
1034                                physical >> SECTOR_SHIFT, length >> SECTOR_SHIFT,
1035                                GFP_NOFS);
1036         if (ret)
1037                 return ret;
1038
1039         *bytes = length;
1040         while (length) {
1041                 btrfs_dev_set_zone_empty(device, physical);
1042                 btrfs_dev_clear_active_zone(device, physical);
1043                 physical += device->zone_info->zone_size;
1044                 length -= device->zone_info->zone_size;
1045         }
1046
1047         return 0;
1048 }
1049
1050 int btrfs_ensure_empty_zones(struct btrfs_device *device, u64 start, u64 size)
1051 {
1052         struct btrfs_zoned_device_info *zinfo = device->zone_info;
1053         const u8 shift = zinfo->zone_size_shift;
1054         unsigned long begin = start >> shift;
1055         unsigned long end = (start + size) >> shift;
1056         u64 pos;
1057         int ret;
1058
1059         ASSERT(IS_ALIGNED(start, zinfo->zone_size));
1060         ASSERT(IS_ALIGNED(size, zinfo->zone_size));
1061
1062         if (end > zinfo->nr_zones)
1063                 return -ERANGE;
1064
1065         /* All the zones are conventional */
1066         if (find_next_bit(zinfo->seq_zones, begin, end) == end)
1067                 return 0;
1068
1069         /* All the zones are sequential and empty */
1070         if (find_next_zero_bit(zinfo->seq_zones, begin, end) == end &&
1071             find_next_zero_bit(zinfo->empty_zones, begin, end) == end)
1072                 return 0;
1073
1074         for (pos = start; pos < start + size; pos += zinfo->zone_size) {
1075                 u64 reset_bytes;
1076
1077                 if (!btrfs_dev_is_sequential(device, pos) ||
1078                     btrfs_dev_is_empty_zone(device, pos))
1079                         continue;
1080
1081                 /* Free regions should be empty */
1082                 btrfs_warn_in_rcu(
1083                         device->fs_info,
1084                 "zoned: resetting device %s (devid %llu) zone %llu for allocation",
1085                         rcu_str_deref(device->name), device->devid, pos >> shift);
1086                 WARN_ON_ONCE(1);
1087
1088                 ret = btrfs_reset_device_zone(device, pos, zinfo->zone_size,
1089                                               &reset_bytes);
1090                 if (ret)
1091                         return ret;
1092         }
1093
1094         return 0;
1095 }
1096
1097 /*
1098  * Calculate an allocation pointer from the extent allocation information
1099  * for a block group consist of conventional zones. It is pointed to the
1100  * end of the highest addressed extent in the block group as an allocation
1101  * offset.
1102  */
1103 static int calculate_alloc_pointer(struct btrfs_block_group *cache,
1104                                    u64 *offset_ret)
1105 {
1106         struct btrfs_fs_info *fs_info = cache->fs_info;
1107         struct btrfs_root *root = fs_info->extent_root;
1108         struct btrfs_path *path;
1109         struct btrfs_key key;
1110         struct btrfs_key found_key;
1111         int ret;
1112         u64 length;
1113
1114         path = btrfs_alloc_path();
1115         if (!path)
1116                 return -ENOMEM;
1117
1118         key.objectid = cache->start + cache->length;
1119         key.type = 0;
1120         key.offset = 0;
1121
1122         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1123         /* We should not find the exact match */
1124         if (!ret)
1125                 ret = -EUCLEAN;
1126         if (ret < 0)
1127                 goto out;
1128
1129         ret = btrfs_previous_extent_item(root, path, cache->start);
1130         if (ret) {
1131                 if (ret == 1) {
1132                         ret = 0;
1133                         *offset_ret = 0;
1134                 }
1135                 goto out;
1136         }
1137
1138         btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
1139
1140         if (found_key.type == BTRFS_EXTENT_ITEM_KEY)
1141                 length = found_key.offset;
1142         else
1143                 length = fs_info->nodesize;
1144
1145         if (!(found_key.objectid >= cache->start &&
1146                found_key.objectid + length <= cache->start + cache->length)) {
1147                 ret = -EUCLEAN;
1148                 goto out;
1149         }
1150         *offset_ret = found_key.objectid + length - cache->start;
1151         ret = 0;
1152
1153 out:
1154         btrfs_free_path(path);
1155         return ret;
1156 }
1157
1158 int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new)
1159 {
1160         struct btrfs_fs_info *fs_info = cache->fs_info;
1161         struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1162         struct extent_map *em;
1163         struct map_lookup *map;
1164         struct btrfs_device *device;
1165         u64 logical = cache->start;
1166         u64 length = cache->length;
1167         u64 physical = 0;
1168         int ret;
1169         int i;
1170         unsigned int nofs_flag;
1171         u64 *alloc_offsets = NULL;
1172         u64 *caps = NULL;
1173         unsigned long *active = NULL;
1174         u64 last_alloc = 0;
1175         u32 num_sequential = 0, num_conventional = 0;
1176
1177         if (!btrfs_is_zoned(fs_info))
1178                 return 0;
1179
1180         /* Sanity check */
1181         if (!IS_ALIGNED(length, fs_info->zone_size)) {
1182                 btrfs_err(fs_info,
1183                 "zoned: block group %llu len %llu unaligned to zone size %llu",
1184                           logical, length, fs_info->zone_size);
1185                 return -EIO;
1186         }
1187
1188         /* Get the chunk mapping */
1189         read_lock(&em_tree->lock);
1190         em = lookup_extent_mapping(em_tree, logical, length);
1191         read_unlock(&em_tree->lock);
1192
1193         if (!em)
1194                 return -EINVAL;
1195
1196         map = em->map_lookup;
1197
1198         cache->physical_map = kmalloc(map_lookup_size(map->num_stripes), GFP_NOFS);
1199         if (!cache->physical_map) {
1200                 ret = -ENOMEM;
1201                 goto out;
1202         }
1203
1204         memcpy(cache->physical_map, map, map_lookup_size(map->num_stripes));
1205
1206         alloc_offsets = kcalloc(map->num_stripes, sizeof(*alloc_offsets), GFP_NOFS);
1207         if (!alloc_offsets) {
1208                 ret = -ENOMEM;
1209                 goto out;
1210         }
1211
1212         caps = kcalloc(map->num_stripes, sizeof(*caps), GFP_NOFS);
1213         if (!caps) {
1214                 ret = -ENOMEM;
1215                 goto out;
1216         }
1217
1218         active = bitmap_zalloc(map->num_stripes, GFP_NOFS);
1219         if (!active) {
1220                 ret = -ENOMEM;
1221                 goto out;
1222         }
1223
1224         for (i = 0; i < map->num_stripes; i++) {
1225                 bool is_sequential;
1226                 struct blk_zone zone;
1227                 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1228                 int dev_replace_is_ongoing = 0;
1229
1230                 device = map->stripes[i].dev;
1231                 physical = map->stripes[i].physical;
1232
1233                 if (device->bdev == NULL) {
1234                         alloc_offsets[i] = WP_MISSING_DEV;
1235                         continue;
1236                 }
1237
1238                 is_sequential = btrfs_dev_is_sequential(device, physical);
1239                 if (is_sequential)
1240                         num_sequential++;
1241                 else
1242                         num_conventional++;
1243
1244                 if (!is_sequential) {
1245                         alloc_offsets[i] = WP_CONVENTIONAL;
1246                         continue;
1247                 }
1248
1249                 /*
1250                  * This zone will be used for allocation, so mark this zone
1251                  * non-empty.
1252                  */
1253                 btrfs_dev_clear_zone_empty(device, physical);
1254
1255                 down_read(&dev_replace->rwsem);
1256                 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
1257                 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
1258                         btrfs_dev_clear_zone_empty(dev_replace->tgtdev, physical);
1259                 up_read(&dev_replace->rwsem);
1260
1261                 /*
1262                  * The group is mapped to a sequential zone. Get the zone write
1263                  * pointer to determine the allocation offset within the zone.
1264                  */
1265                 WARN_ON(!IS_ALIGNED(physical, fs_info->zone_size));
1266                 nofs_flag = memalloc_nofs_save();
1267                 ret = btrfs_get_dev_zone(device, physical, &zone);
1268                 memalloc_nofs_restore(nofs_flag);
1269                 if (ret == -EIO || ret == -EOPNOTSUPP) {
1270                         ret = 0;
1271                         alloc_offsets[i] = WP_MISSING_DEV;
1272                         continue;
1273                 } else if (ret) {
1274                         goto out;
1275                 }
1276
1277                 if (zone.type == BLK_ZONE_TYPE_CONVENTIONAL) {
1278                         btrfs_err_in_rcu(fs_info,
1279         "zoned: unexpected conventional zone %llu on device %s (devid %llu)",
1280                                 zone.start << SECTOR_SHIFT,
1281                                 rcu_str_deref(device->name), device->devid);
1282                         ret = -EIO;
1283                         goto out;
1284                 }
1285
1286                 caps[i] = (zone.capacity << SECTOR_SHIFT);
1287
1288                 switch (zone.cond) {
1289                 case BLK_ZONE_COND_OFFLINE:
1290                 case BLK_ZONE_COND_READONLY:
1291                         btrfs_err(fs_info,
1292                 "zoned: offline/readonly zone %llu on device %s (devid %llu)",
1293                                   physical >> device->zone_info->zone_size_shift,
1294                                   rcu_str_deref(device->name), device->devid);
1295                         alloc_offsets[i] = WP_MISSING_DEV;
1296                         break;
1297                 case BLK_ZONE_COND_EMPTY:
1298                         alloc_offsets[i] = 0;
1299                         break;
1300                 case BLK_ZONE_COND_FULL:
1301                         alloc_offsets[i] = caps[i];
1302                         break;
1303                 default:
1304                         /* Partially used zone */
1305                         alloc_offsets[i] =
1306                                         ((zone.wp - zone.start) << SECTOR_SHIFT);
1307                         __set_bit(i, active);
1308                         break;
1309                 }
1310
1311                 /*
1312                  * Consider a zone as active if we can allow any number of
1313                  * active zones.
1314                  */
1315                 if (!device->zone_info->max_active_zones)
1316                         __set_bit(i, active);
1317         }
1318
1319         if (num_sequential > 0)
1320                 cache->seq_zone = true;
1321
1322         if (num_conventional > 0) {
1323                 /*
1324                  * Avoid calling calculate_alloc_pointer() for new BG. It
1325                  * is no use for new BG. It must be always 0.
1326                  *
1327                  * Also, we have a lock chain of extent buffer lock ->
1328                  * chunk mutex.  For new BG, this function is called from
1329                  * btrfs_make_block_group() which is already taking the
1330                  * chunk mutex. Thus, we cannot call
1331                  * calculate_alloc_pointer() which takes extent buffer
1332                  * locks to avoid deadlock.
1333                  */
1334
1335                 /* Zone capacity is always zone size in emulation */
1336                 cache->zone_capacity = cache->length;
1337                 if (new) {
1338                         cache->alloc_offset = 0;
1339                         goto out;
1340                 }
1341                 ret = calculate_alloc_pointer(cache, &last_alloc);
1342                 if (ret || map->num_stripes == num_conventional) {
1343                         if (!ret)
1344                                 cache->alloc_offset = last_alloc;
1345                         else
1346                                 btrfs_err(fs_info,
1347                         "zoned: failed to determine allocation offset of bg %llu",
1348                                           cache->start);
1349                         goto out;
1350                 }
1351         }
1352
1353         switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1354         case 0: /* single */
1355                 if (alloc_offsets[0] == WP_MISSING_DEV) {
1356                         btrfs_err(fs_info,
1357                         "zoned: cannot recover write pointer for zone %llu",
1358                                 physical);
1359                         ret = -EIO;
1360                         goto out;
1361                 }
1362                 cache->alloc_offset = alloc_offsets[0];
1363                 cache->zone_capacity = caps[0];
1364                 cache->zone_is_active = test_bit(0, active);
1365                 break;
1366         case BTRFS_BLOCK_GROUP_DUP:
1367         case BTRFS_BLOCK_GROUP_RAID1:
1368         case BTRFS_BLOCK_GROUP_RAID0:
1369         case BTRFS_BLOCK_GROUP_RAID10:
1370         case BTRFS_BLOCK_GROUP_RAID5:
1371         case BTRFS_BLOCK_GROUP_RAID6:
1372                 /* non-single profiles are not supported yet */
1373         default:
1374                 btrfs_err(fs_info, "zoned: profile %s not yet supported",
1375                           btrfs_bg_type_to_raid_name(map->type));
1376                 ret = -EINVAL;
1377                 goto out;
1378         }
1379
1380         if (cache->zone_is_active) {
1381                 btrfs_get_block_group(cache);
1382                 spin_lock(&fs_info->zone_active_bgs_lock);
1383                 list_add_tail(&cache->active_bg_list, &fs_info->zone_active_bgs);
1384                 spin_unlock(&fs_info->zone_active_bgs_lock);
1385         }
1386
1387 out:
1388         if (cache->alloc_offset > fs_info->zone_size) {
1389                 btrfs_err(fs_info,
1390                         "zoned: invalid write pointer %llu in block group %llu",
1391                         cache->alloc_offset, cache->start);
1392                 ret = -EIO;
1393         }
1394
1395         if (cache->alloc_offset > cache->zone_capacity) {
1396                 btrfs_err(fs_info,
1397 "zoned: invalid write pointer %llu (larger than zone capacity %llu) in block group %llu",
1398                           cache->alloc_offset, cache->zone_capacity,
1399                           cache->start);
1400                 ret = -EIO;
1401         }
1402
1403         /* An extent is allocated after the write pointer */
1404         if (!ret && num_conventional && last_alloc > cache->alloc_offset) {
1405                 btrfs_err(fs_info,
1406                           "zoned: got wrong write pointer in BG %llu: %llu > %llu",
1407                           logical, last_alloc, cache->alloc_offset);
1408                 ret = -EIO;
1409         }
1410
1411         if (!ret)
1412                 cache->meta_write_pointer = cache->alloc_offset + cache->start;
1413
1414         if (ret) {
1415                 kfree(cache->physical_map);
1416                 cache->physical_map = NULL;
1417         }
1418         bitmap_free(active);
1419         kfree(caps);
1420         kfree(alloc_offsets);
1421         free_extent_map(em);
1422
1423         return ret;
1424 }
1425
1426 void btrfs_calc_zone_unusable(struct btrfs_block_group *cache)
1427 {
1428         u64 unusable, free;
1429
1430         if (!btrfs_is_zoned(cache->fs_info))
1431                 return;
1432
1433         WARN_ON(cache->bytes_super != 0);
1434         unusable = (cache->alloc_offset - cache->used) +
1435                    (cache->length - cache->zone_capacity);
1436         free = cache->zone_capacity - cache->alloc_offset;
1437
1438         /* We only need ->free_space in ALLOC_SEQ block groups */
1439         cache->last_byte_to_unpin = (u64)-1;
1440         cache->cached = BTRFS_CACHE_FINISHED;
1441         cache->free_space_ctl->free_space = free;
1442         cache->zone_unusable = unusable;
1443 }
1444
1445 void btrfs_redirty_list_add(struct btrfs_transaction *trans,
1446                             struct extent_buffer *eb)
1447 {
1448         struct btrfs_fs_info *fs_info = eb->fs_info;
1449
1450         if (!btrfs_is_zoned(fs_info) ||
1451             btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN) ||
1452             !list_empty(&eb->release_list))
1453                 return;
1454
1455         set_extent_buffer_dirty(eb);
1456         set_extent_bits_nowait(&trans->dirty_pages, eb->start,
1457                                eb->start + eb->len - 1, EXTENT_DIRTY);
1458         memzero_extent_buffer(eb, 0, eb->len);
1459         set_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags);
1460
1461         spin_lock(&trans->releasing_ebs_lock);
1462         list_add_tail(&eb->release_list, &trans->releasing_ebs);
1463         spin_unlock(&trans->releasing_ebs_lock);
1464         atomic_inc(&eb->refs);
1465 }
1466
1467 void btrfs_free_redirty_list(struct btrfs_transaction *trans)
1468 {
1469         spin_lock(&trans->releasing_ebs_lock);
1470         while (!list_empty(&trans->releasing_ebs)) {
1471                 struct extent_buffer *eb;
1472
1473                 eb = list_first_entry(&trans->releasing_ebs,
1474                                       struct extent_buffer, release_list);
1475                 list_del_init(&eb->release_list);
1476                 free_extent_buffer(eb);
1477         }
1478         spin_unlock(&trans->releasing_ebs_lock);
1479 }
1480
1481 bool btrfs_use_zone_append(struct btrfs_inode *inode, u64 start)
1482 {
1483         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1484         struct btrfs_block_group *cache;
1485         bool ret = false;
1486
1487         if (!btrfs_is_zoned(fs_info))
1488                 return false;
1489
1490         if (!is_data_inode(&inode->vfs_inode))
1491                 return false;
1492
1493         cache = btrfs_lookup_block_group(fs_info, start);
1494         ASSERT(cache);
1495         if (!cache)
1496                 return false;
1497
1498         ret = cache->seq_zone;
1499         btrfs_put_block_group(cache);
1500
1501         return ret;
1502 }
1503
1504 void btrfs_record_physical_zoned(struct inode *inode, u64 file_offset,
1505                                  struct bio *bio)
1506 {
1507         struct btrfs_ordered_extent *ordered;
1508         const u64 physical = bio->bi_iter.bi_sector << SECTOR_SHIFT;
1509
1510         if (bio_op(bio) != REQ_OP_ZONE_APPEND)
1511                 return;
1512
1513         ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), file_offset);
1514         if (WARN_ON(!ordered))
1515                 return;
1516
1517         ordered->physical = physical;
1518         ordered->bdev = bio->bi_bdev;
1519
1520         btrfs_put_ordered_extent(ordered);
1521 }
1522
1523 void btrfs_rewrite_logical_zoned(struct btrfs_ordered_extent *ordered)
1524 {
1525         struct btrfs_inode *inode = BTRFS_I(ordered->inode);
1526         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1527         struct extent_map_tree *em_tree;
1528         struct extent_map *em;
1529         struct btrfs_ordered_sum *sum;
1530         u64 orig_logical = ordered->disk_bytenr;
1531         u64 *logical = NULL;
1532         int nr, stripe_len;
1533
1534         /* Zoned devices should not have partitions. So, we can assume it is 0 */
1535         ASSERT(!bdev_is_partition(ordered->bdev));
1536         if (WARN_ON(!ordered->bdev))
1537                 return;
1538
1539         if (WARN_ON(btrfs_rmap_block(fs_info, orig_logical, ordered->bdev,
1540                                      ordered->physical, &logical, &nr,
1541                                      &stripe_len)))
1542                 goto out;
1543
1544         WARN_ON(nr != 1);
1545
1546         if (orig_logical == *logical)
1547                 goto out;
1548
1549         ordered->disk_bytenr = *logical;
1550
1551         em_tree = &inode->extent_tree;
1552         write_lock(&em_tree->lock);
1553         em = search_extent_mapping(em_tree, ordered->file_offset,
1554                                    ordered->num_bytes);
1555         em->block_start = *logical;
1556         free_extent_map(em);
1557         write_unlock(&em_tree->lock);
1558
1559         list_for_each_entry(sum, &ordered->list, list) {
1560                 if (*logical < orig_logical)
1561                         sum->bytenr -= orig_logical - *logical;
1562                 else
1563                         sum->bytenr += *logical - orig_logical;
1564         }
1565
1566 out:
1567         kfree(logical);
1568 }
1569
1570 bool btrfs_check_meta_write_pointer(struct btrfs_fs_info *fs_info,
1571                                     struct extent_buffer *eb,
1572                                     struct btrfs_block_group **cache_ret)
1573 {
1574         struct btrfs_block_group *cache;
1575         bool ret = true;
1576
1577         if (!btrfs_is_zoned(fs_info))
1578                 return true;
1579
1580         cache = *cache_ret;
1581
1582         if (cache && (eb->start < cache->start ||
1583                       cache->start + cache->length <= eb->start)) {
1584                 btrfs_put_block_group(cache);
1585                 cache = NULL;
1586                 *cache_ret = NULL;
1587         }
1588
1589         if (!cache)
1590                 cache = btrfs_lookup_block_group(fs_info, eb->start);
1591
1592         if (cache) {
1593                 if (cache->meta_write_pointer != eb->start) {
1594                         btrfs_put_block_group(cache);
1595                         cache = NULL;
1596                         ret = false;
1597                 } else {
1598                         cache->meta_write_pointer = eb->start + eb->len;
1599                 }
1600
1601                 *cache_ret = cache;
1602         }
1603
1604         return ret;
1605 }
1606
1607 void btrfs_revert_meta_write_pointer(struct btrfs_block_group *cache,
1608                                      struct extent_buffer *eb)
1609 {
1610         if (!btrfs_is_zoned(eb->fs_info) || !cache)
1611                 return;
1612
1613         ASSERT(cache->meta_write_pointer == eb->start + eb->len);
1614         cache->meta_write_pointer = eb->start;
1615 }
1616
1617 int btrfs_zoned_issue_zeroout(struct btrfs_device *device, u64 physical, u64 length)
1618 {
1619         if (!btrfs_dev_is_sequential(device, physical))
1620                 return -EOPNOTSUPP;
1621
1622         return blkdev_issue_zeroout(device->bdev, physical >> SECTOR_SHIFT,
1623                                     length >> SECTOR_SHIFT, GFP_NOFS, 0);
1624 }
1625
1626 static int read_zone_info(struct btrfs_fs_info *fs_info, u64 logical,
1627                           struct blk_zone *zone)
1628 {
1629         struct btrfs_bio *bbio = NULL;
1630         u64 mapped_length = PAGE_SIZE;
1631         unsigned int nofs_flag;
1632         int nmirrors;
1633         int i, ret;
1634
1635         ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
1636                                &mapped_length, &bbio);
1637         if (ret || !bbio || mapped_length < PAGE_SIZE) {
1638                 btrfs_put_bbio(bbio);
1639                 return -EIO;
1640         }
1641
1642         if (bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1643                 return -EINVAL;
1644
1645         nofs_flag = memalloc_nofs_save();
1646         nmirrors = (int)bbio->num_stripes;
1647         for (i = 0; i < nmirrors; i++) {
1648                 u64 physical = bbio->stripes[i].physical;
1649                 struct btrfs_device *dev = bbio->stripes[i].dev;
1650
1651                 /* Missing device */
1652                 if (!dev->bdev)
1653                         continue;
1654
1655                 ret = btrfs_get_dev_zone(dev, physical, zone);
1656                 /* Failing device */
1657                 if (ret == -EIO || ret == -EOPNOTSUPP)
1658                         continue;
1659                 break;
1660         }
1661         memalloc_nofs_restore(nofs_flag);
1662
1663         return ret;
1664 }
1665
1666 /*
1667  * Synchronize write pointer in a zone at @physical_start on @tgt_dev, by
1668  * filling zeros between @physical_pos to a write pointer of dev-replace
1669  * source device.
1670  */
1671 int btrfs_sync_zone_write_pointer(struct btrfs_device *tgt_dev, u64 logical,
1672                                     u64 physical_start, u64 physical_pos)
1673 {
1674         struct btrfs_fs_info *fs_info = tgt_dev->fs_info;
1675         struct blk_zone zone;
1676         u64 length;
1677         u64 wp;
1678         int ret;
1679
1680         if (!btrfs_dev_is_sequential(tgt_dev, physical_pos))
1681                 return 0;
1682
1683         ret = read_zone_info(fs_info, logical, &zone);
1684         if (ret)
1685                 return ret;
1686
1687         wp = physical_start + ((zone.wp - zone.start) << SECTOR_SHIFT);
1688
1689         if (physical_pos == wp)
1690                 return 0;
1691
1692         if (physical_pos > wp)
1693                 return -EUCLEAN;
1694
1695         length = wp - physical_pos;
1696         return btrfs_zoned_issue_zeroout(tgt_dev, physical_pos, length);
1697 }
1698
1699 struct btrfs_device *btrfs_zoned_get_device(struct btrfs_fs_info *fs_info,
1700                                             u64 logical, u64 length)
1701 {
1702         struct btrfs_device *device;
1703         struct extent_map *em;
1704         struct map_lookup *map;
1705
1706         em = btrfs_get_chunk_map(fs_info, logical, length);
1707         if (IS_ERR(em))
1708                 return ERR_CAST(em);
1709
1710         map = em->map_lookup;
1711         /* We only support single profile for now */
1712         ASSERT(map->num_stripes == 1);
1713         device = map->stripes[0].dev;
1714
1715         free_extent_map(em);
1716
1717         return device;
1718 }
1719
1720 /**
1721  * Activate block group and underlying device zones
1722  *
1723  * @block_group: the block group to activate
1724  *
1725  * Return: true on success, false otherwise
1726  */
1727 bool btrfs_zone_activate(struct btrfs_block_group *block_group)
1728 {
1729         struct btrfs_fs_info *fs_info = block_group->fs_info;
1730         struct map_lookup *map;
1731         struct btrfs_device *device;
1732         u64 physical;
1733         bool ret;
1734
1735         if (!btrfs_is_zoned(block_group->fs_info))
1736                 return true;
1737
1738         map = block_group->physical_map;
1739         /* Currently support SINGLE profile only */
1740         ASSERT(map->num_stripes == 1);
1741         device = map->stripes[0].dev;
1742         physical = map->stripes[0].physical;
1743
1744         if (device->zone_info->max_active_zones == 0)
1745                 return true;
1746
1747         spin_lock(&block_group->lock);
1748
1749         if (block_group->zone_is_active) {
1750                 ret = true;
1751                 goto out_unlock;
1752         }
1753
1754         /* No space left */
1755         if (block_group->alloc_offset == block_group->zone_capacity) {
1756                 ret = false;
1757                 goto out_unlock;
1758         }
1759
1760         if (!btrfs_dev_set_active_zone(device, physical)) {
1761                 /* Cannot activate the zone */
1762                 ret = false;
1763                 goto out_unlock;
1764         }
1765
1766         /* Successfully activated all the zones */
1767         block_group->zone_is_active = 1;
1768
1769         spin_unlock(&block_group->lock);
1770
1771         /* For the active block group list */
1772         btrfs_get_block_group(block_group);
1773
1774         spin_lock(&fs_info->zone_active_bgs_lock);
1775         ASSERT(list_empty(&block_group->active_bg_list));
1776         list_add_tail(&block_group->active_bg_list, &fs_info->zone_active_bgs);
1777         spin_unlock(&fs_info->zone_active_bgs_lock);
1778
1779         return true;
1780
1781 out_unlock:
1782         spin_unlock(&block_group->lock);
1783         return ret;
1784 }
1785
1786 int btrfs_zone_finish(struct btrfs_block_group *block_group)
1787 {
1788         struct btrfs_fs_info *fs_info = block_group->fs_info;
1789         struct map_lookup *map;
1790         struct btrfs_device *device;
1791         u64 physical;
1792         int ret = 0;
1793
1794         if (!btrfs_is_zoned(fs_info))
1795                 return 0;
1796
1797         map = block_group->physical_map;
1798         /* Currently support SINGLE profile only */
1799         ASSERT(map->num_stripes == 1);
1800
1801         device = map->stripes[0].dev;
1802         physical = map->stripes[0].physical;
1803
1804         if (device->zone_info->max_active_zones == 0)
1805                 return 0;
1806
1807         spin_lock(&block_group->lock);
1808         if (!block_group->zone_is_active) {
1809                 spin_unlock(&block_group->lock);
1810                 return 0;
1811         }
1812
1813         /* Check if we have unwritten allocated space */
1814         if ((block_group->flags &
1815              (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM)) &&
1816             block_group->alloc_offset > block_group->meta_write_pointer) {
1817                 spin_unlock(&block_group->lock);
1818                 return -EAGAIN;
1819         }
1820         spin_unlock(&block_group->lock);
1821
1822         ret = btrfs_inc_block_group_ro(block_group, false);
1823         if (ret)
1824                 return ret;
1825
1826         /* Ensure all writes in this block group finish */
1827         btrfs_wait_block_group_reservations(block_group);
1828         /* No need to wait for NOCOW writers. Zoned mode does not allow that. */
1829         btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group->start,
1830                                  block_group->length);
1831
1832         spin_lock(&block_group->lock);
1833
1834         /*
1835          * Bail out if someone already deactivated the block group, or
1836          * allocated space is left in the block group.
1837          */
1838         if (!block_group->zone_is_active) {
1839                 spin_unlock(&block_group->lock);
1840                 btrfs_dec_block_group_ro(block_group);
1841                 return 0;
1842         }
1843
1844         if (block_group->reserved) {
1845                 spin_unlock(&block_group->lock);
1846                 btrfs_dec_block_group_ro(block_group);
1847                 return -EAGAIN;
1848         }
1849
1850         block_group->zone_is_active = 0;
1851         block_group->alloc_offset = block_group->zone_capacity;
1852         block_group->free_space_ctl->free_space = 0;
1853         btrfs_clear_treelog_bg(block_group);
1854         spin_unlock(&block_group->lock);
1855
1856         ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_FINISH,
1857                                physical >> SECTOR_SHIFT,
1858                                device->zone_info->zone_size >> SECTOR_SHIFT,
1859                                GFP_NOFS);
1860         btrfs_dec_block_group_ro(block_group);
1861
1862         if (!ret) {
1863                 btrfs_dev_clear_active_zone(device, physical);
1864
1865                 spin_lock(&fs_info->zone_active_bgs_lock);
1866                 ASSERT(!list_empty(&block_group->active_bg_list));
1867                 list_del_init(&block_group->active_bg_list);
1868                 spin_unlock(&fs_info->zone_active_bgs_lock);
1869
1870                 /* For active_bg_list */
1871                 btrfs_put_block_group(block_group);
1872         }
1873
1874         return ret;
1875 }