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