btrfs: zoned: fix btrfs_can_activate_zone() to support DUP profile
[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                 /* Overcommit does not work well with active zone tacking. */
542                 set_bit(BTRFS_FS_NO_OVERCOMMIT, &fs_info->flags);
543         }
544
545         /* Validate superblock log */
546         nr_zones = BTRFS_NR_SB_LOG_ZONES;
547         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
548                 u32 sb_zone;
549                 u64 sb_wp;
550                 int sb_pos = BTRFS_NR_SB_LOG_ZONES * i;
551
552                 sb_zone = sb_zone_number(zone_info->zone_size_shift, i);
553                 if (sb_zone + 1 >= zone_info->nr_zones)
554                         continue;
555
556                 ret = btrfs_get_dev_zones(device,
557                                           zone_start_physical(sb_zone, zone_info),
558                                           &zone_info->sb_zones[sb_pos],
559                                           &nr_zones);
560                 if (ret)
561                         goto out;
562
563                 if (nr_zones != BTRFS_NR_SB_LOG_ZONES) {
564                         btrfs_err_in_rcu(device->fs_info,
565         "zoned: failed to read super block log zone info at devid %llu zone %u",
566                                          device->devid, sb_zone);
567                         ret = -EUCLEAN;
568                         goto out;
569                 }
570
571                 /*
572                  * If zones[0] is conventional, always use the beginning of the
573                  * zone to record superblock. No need to validate in that case.
574                  */
575                 if (zone_info->sb_zones[BTRFS_NR_SB_LOG_ZONES * i].type ==
576                     BLK_ZONE_TYPE_CONVENTIONAL)
577                         continue;
578
579                 ret = sb_write_pointer(device->bdev,
580                                        &zone_info->sb_zones[sb_pos], &sb_wp);
581                 if (ret != -ENOENT && ret) {
582                         btrfs_err_in_rcu(device->fs_info,
583                         "zoned: super block log zone corrupted devid %llu zone %u",
584                                          device->devid, sb_zone);
585                         ret = -EUCLEAN;
586                         goto out;
587                 }
588         }
589
590
591         kvfree(zones);
592
593         switch (bdev_zoned_model(bdev)) {
594         case BLK_ZONED_HM:
595                 model = "host-managed zoned";
596                 emulated = "";
597                 break;
598         case BLK_ZONED_HA:
599                 model = "host-aware zoned";
600                 emulated = "";
601                 break;
602         case BLK_ZONED_NONE:
603                 model = "regular";
604                 emulated = "emulated ";
605                 break;
606         default:
607                 /* Just in case */
608                 btrfs_err_in_rcu(fs_info, "zoned: unsupported model %d on %s",
609                                  bdev_zoned_model(bdev),
610                                  rcu_str_deref(device->name));
611                 ret = -EOPNOTSUPP;
612                 goto out_free_zone_info;
613         }
614
615         btrfs_info_in_rcu(fs_info,
616                 "%s block device %s, %u %szones of %llu bytes",
617                 model, rcu_str_deref(device->name), zone_info->nr_zones,
618                 emulated, zone_info->zone_size);
619
620         return 0;
621
622 out:
623         kvfree(zones);
624 out_free_zone_info:
625         btrfs_destroy_dev_zone_info(device);
626
627         return ret;
628 }
629
630 void btrfs_destroy_dev_zone_info(struct btrfs_device *device)
631 {
632         struct btrfs_zoned_device_info *zone_info = device->zone_info;
633
634         if (!zone_info)
635                 return;
636
637         bitmap_free(zone_info->active_zones);
638         bitmap_free(zone_info->seq_zones);
639         bitmap_free(zone_info->empty_zones);
640         vfree(zone_info->zone_cache);
641         kfree(zone_info);
642         device->zone_info = NULL;
643 }
644
645 struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *orig_dev)
646 {
647         struct btrfs_zoned_device_info *zone_info;
648
649         zone_info = kmemdup(orig_dev->zone_info, sizeof(*zone_info), GFP_KERNEL);
650         if (!zone_info)
651                 return NULL;
652
653         zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
654         if (!zone_info->seq_zones)
655                 goto out;
656
657         bitmap_copy(zone_info->seq_zones, orig_dev->zone_info->seq_zones,
658                     zone_info->nr_zones);
659
660         zone_info->empty_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
661         if (!zone_info->empty_zones)
662                 goto out;
663
664         bitmap_copy(zone_info->empty_zones, orig_dev->zone_info->empty_zones,
665                     zone_info->nr_zones);
666
667         zone_info->active_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
668         if (!zone_info->active_zones)
669                 goto out;
670
671         bitmap_copy(zone_info->active_zones, orig_dev->zone_info->active_zones,
672                     zone_info->nr_zones);
673         zone_info->zone_cache = NULL;
674
675         return zone_info;
676
677 out:
678         bitmap_free(zone_info->seq_zones);
679         bitmap_free(zone_info->empty_zones);
680         bitmap_free(zone_info->active_zones);
681         kfree(zone_info);
682         return NULL;
683 }
684
685 int btrfs_get_dev_zone(struct btrfs_device *device, u64 pos,
686                        struct blk_zone *zone)
687 {
688         unsigned int nr_zones = 1;
689         int ret;
690
691         ret = btrfs_get_dev_zones(device, pos, zone, &nr_zones);
692         if (ret != 0 || !nr_zones)
693                 return ret ? ret : -EIO;
694
695         return 0;
696 }
697
698 static int btrfs_check_for_zoned_device(struct btrfs_fs_info *fs_info)
699 {
700         struct btrfs_device *device;
701
702         list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
703                 if (device->bdev &&
704                     bdev_zoned_model(device->bdev) == BLK_ZONED_HM) {
705                         btrfs_err(fs_info,
706                                 "zoned: mode not enabled but zoned device found: %pg",
707                                 device->bdev);
708                         return -EINVAL;
709                 }
710         }
711
712         return 0;
713 }
714
715 int btrfs_check_zoned_mode(struct btrfs_fs_info *fs_info)
716 {
717         struct btrfs_device *device;
718         u64 zone_size = 0;
719         u64 max_zone_append_size = 0;
720         int ret;
721
722         /*
723          * Host-Managed devices can't be used without the ZONED flag.  With the
724          * ZONED all devices can be used, using zone emulation if required.
725          */
726         if (!btrfs_fs_incompat(fs_info, ZONED))
727                 return btrfs_check_for_zoned_device(fs_info);
728
729         list_for_each_entry(device, &fs_info->fs_devices->devices, dev_list) {
730                 struct btrfs_zoned_device_info *zone_info = device->zone_info;
731
732                 if (!device->bdev)
733                         continue;
734
735                 if (!zone_size) {
736                         zone_size = zone_info->zone_size;
737                 } else if (zone_info->zone_size != zone_size) {
738                         btrfs_err(fs_info,
739                 "zoned: unequal block device zone sizes: have %llu found %llu",
740                                   zone_info->zone_size, zone_size);
741                         return -EINVAL;
742                 }
743                 if (!max_zone_append_size ||
744                     (zone_info->max_zone_append_size &&
745                      zone_info->max_zone_append_size < max_zone_append_size))
746                         max_zone_append_size = zone_info->max_zone_append_size;
747         }
748
749         /*
750          * stripe_size is always aligned to BTRFS_STRIPE_LEN in
751          * btrfs_create_chunk(). Since we want stripe_len == zone_size,
752          * check the alignment here.
753          */
754         if (!IS_ALIGNED(zone_size, BTRFS_STRIPE_LEN)) {
755                 btrfs_err(fs_info,
756                           "zoned: zone size %llu not aligned to stripe %u",
757                           zone_size, BTRFS_STRIPE_LEN);
758                 return -EINVAL;
759         }
760
761         if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
762                 btrfs_err(fs_info, "zoned: mixed block groups not supported");
763                 return -EINVAL;
764         }
765
766         fs_info->zone_size = zone_size;
767         fs_info->max_zone_append_size = ALIGN_DOWN(max_zone_append_size,
768                                                    fs_info->sectorsize);
769         fs_info->fs_devices->chunk_alloc_policy = BTRFS_CHUNK_ALLOC_ZONED;
770         if (fs_info->max_zone_append_size < fs_info->max_extent_size)
771                 fs_info->max_extent_size = fs_info->max_zone_append_size;
772
773         /*
774          * Check mount options here, because we might change fs_info->zoned
775          * from fs_info->zone_size.
776          */
777         ret = btrfs_check_mountopts_zoned(fs_info);
778         if (ret)
779                 return ret;
780
781         btrfs_info(fs_info, "zoned mode enabled with zone size %llu", zone_size);
782         return 0;
783 }
784
785 int btrfs_check_mountopts_zoned(struct btrfs_fs_info *info)
786 {
787         if (!btrfs_is_zoned(info))
788                 return 0;
789
790         /*
791          * Space cache writing is not COWed. Disable that to avoid write errors
792          * in sequential zones.
793          */
794         if (btrfs_test_opt(info, SPACE_CACHE)) {
795                 btrfs_err(info, "zoned: space cache v1 is not supported");
796                 return -EINVAL;
797         }
798
799         if (btrfs_test_opt(info, NODATACOW)) {
800                 btrfs_err(info, "zoned: NODATACOW not supported");
801                 return -EINVAL;
802         }
803
804         return 0;
805 }
806
807 static int sb_log_location(struct block_device *bdev, struct blk_zone *zones,
808                            int rw, u64 *bytenr_ret)
809 {
810         u64 wp;
811         int ret;
812
813         if (zones[0].type == BLK_ZONE_TYPE_CONVENTIONAL) {
814                 *bytenr_ret = zones[0].start << SECTOR_SHIFT;
815                 return 0;
816         }
817
818         ret = sb_write_pointer(bdev, zones, &wp);
819         if (ret != -ENOENT && ret < 0)
820                 return ret;
821
822         if (rw == WRITE) {
823                 struct blk_zone *reset = NULL;
824
825                 if (wp == zones[0].start << SECTOR_SHIFT)
826                         reset = &zones[0];
827                 else if (wp == zones[1].start << SECTOR_SHIFT)
828                         reset = &zones[1];
829
830                 if (reset && reset->cond != BLK_ZONE_COND_EMPTY) {
831                         ASSERT(sb_zone_is_full(reset));
832
833                         ret = blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
834                                                reset->start, reset->len,
835                                                GFP_NOFS);
836                         if (ret)
837                                 return ret;
838
839                         reset->cond = BLK_ZONE_COND_EMPTY;
840                         reset->wp = reset->start;
841                 }
842         } else if (ret != -ENOENT) {
843                 /*
844                  * For READ, we want the previous one. Move write pointer to
845                  * the end of a zone, if it is at the head of a zone.
846                  */
847                 u64 zone_end = 0;
848
849                 if (wp == zones[0].start << SECTOR_SHIFT)
850                         zone_end = zones[1].start + zones[1].capacity;
851                 else if (wp == zones[1].start << SECTOR_SHIFT)
852                         zone_end = zones[0].start + zones[0].capacity;
853                 if (zone_end)
854                         wp = ALIGN_DOWN(zone_end << SECTOR_SHIFT,
855                                         BTRFS_SUPER_INFO_SIZE);
856
857                 wp -= BTRFS_SUPER_INFO_SIZE;
858         }
859
860         *bytenr_ret = wp;
861         return 0;
862
863 }
864
865 int btrfs_sb_log_location_bdev(struct block_device *bdev, int mirror, int rw,
866                                u64 *bytenr_ret)
867 {
868         struct blk_zone zones[BTRFS_NR_SB_LOG_ZONES];
869         sector_t zone_sectors;
870         u32 sb_zone;
871         int ret;
872         u8 zone_sectors_shift;
873         sector_t nr_sectors;
874         u32 nr_zones;
875
876         if (!bdev_is_zoned(bdev)) {
877                 *bytenr_ret = btrfs_sb_offset(mirror);
878                 return 0;
879         }
880
881         ASSERT(rw == READ || rw == WRITE);
882
883         zone_sectors = bdev_zone_sectors(bdev);
884         if (!is_power_of_2(zone_sectors))
885                 return -EINVAL;
886         zone_sectors_shift = ilog2(zone_sectors);
887         nr_sectors = bdev_nr_sectors(bdev);
888         nr_zones = nr_sectors >> zone_sectors_shift;
889
890         sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
891         if (sb_zone + 1 >= nr_zones)
892                 return -ENOENT;
893
894         ret = blkdev_report_zones(bdev, zone_start_sector(sb_zone, bdev),
895                                   BTRFS_NR_SB_LOG_ZONES, copy_zone_info_cb,
896                                   zones);
897         if (ret < 0)
898                 return ret;
899         if (ret != BTRFS_NR_SB_LOG_ZONES)
900                 return -EIO;
901
902         return sb_log_location(bdev, zones, rw, bytenr_ret);
903 }
904
905 int btrfs_sb_log_location(struct btrfs_device *device, int mirror, int rw,
906                           u64 *bytenr_ret)
907 {
908         struct btrfs_zoned_device_info *zinfo = device->zone_info;
909         u32 zone_num;
910
911         /*
912          * For a zoned filesystem on a non-zoned block device, use the same
913          * super block locations as regular filesystem. Doing so, the super
914          * block can always be retrieved and the zoned flag of the volume
915          * detected from the super block information.
916          */
917         if (!bdev_is_zoned(device->bdev)) {
918                 *bytenr_ret = btrfs_sb_offset(mirror);
919                 return 0;
920         }
921
922         zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
923         if (zone_num + 1 >= zinfo->nr_zones)
924                 return -ENOENT;
925
926         return sb_log_location(device->bdev,
927                                &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror],
928                                rw, bytenr_ret);
929 }
930
931 static inline bool is_sb_log_zone(struct btrfs_zoned_device_info *zinfo,
932                                   int mirror)
933 {
934         u32 zone_num;
935
936         if (!zinfo)
937                 return false;
938
939         zone_num = sb_zone_number(zinfo->zone_size_shift, mirror);
940         if (zone_num + 1 >= zinfo->nr_zones)
941                 return false;
942
943         if (!test_bit(zone_num, zinfo->seq_zones))
944                 return false;
945
946         return true;
947 }
948
949 int btrfs_advance_sb_log(struct btrfs_device *device, int mirror)
950 {
951         struct btrfs_zoned_device_info *zinfo = device->zone_info;
952         struct blk_zone *zone;
953         int i;
954
955         if (!is_sb_log_zone(zinfo, mirror))
956                 return 0;
957
958         zone = &zinfo->sb_zones[BTRFS_NR_SB_LOG_ZONES * mirror];
959         for (i = 0; i < BTRFS_NR_SB_LOG_ZONES; i++) {
960                 /* Advance the next zone */
961                 if (zone->cond == BLK_ZONE_COND_FULL) {
962                         zone++;
963                         continue;
964                 }
965
966                 if (zone->cond == BLK_ZONE_COND_EMPTY)
967                         zone->cond = BLK_ZONE_COND_IMP_OPEN;
968
969                 zone->wp += SUPER_INFO_SECTORS;
970
971                 if (sb_zone_is_full(zone)) {
972                         /*
973                          * No room left to write new superblock. Since
974                          * superblock is written with REQ_SYNC, it is safe to
975                          * finish the zone now.
976                          *
977                          * If the write pointer is exactly at the capacity,
978                          * explicit ZONE_FINISH is not necessary.
979                          */
980                         if (zone->wp != zone->start + zone->capacity) {
981                                 int ret;
982
983                                 ret = blkdev_zone_mgmt(device->bdev,
984                                                 REQ_OP_ZONE_FINISH, zone->start,
985                                                 zone->len, GFP_NOFS);
986                                 if (ret)
987                                         return ret;
988                         }
989
990                         zone->wp = zone->start + zone->len;
991                         zone->cond = BLK_ZONE_COND_FULL;
992                 }
993                 return 0;
994         }
995
996         /* All the zones are FULL. Should not reach here. */
997         ASSERT(0);
998         return -EIO;
999 }
1000
1001 int btrfs_reset_sb_log_zones(struct block_device *bdev, int mirror)
1002 {
1003         sector_t zone_sectors;
1004         sector_t nr_sectors;
1005         u8 zone_sectors_shift;
1006         u32 sb_zone;
1007         u32 nr_zones;
1008
1009         zone_sectors = bdev_zone_sectors(bdev);
1010         zone_sectors_shift = ilog2(zone_sectors);
1011         nr_sectors = bdev_nr_sectors(bdev);
1012         nr_zones = nr_sectors >> zone_sectors_shift;
1013
1014         sb_zone = sb_zone_number(zone_sectors_shift + SECTOR_SHIFT, mirror);
1015         if (sb_zone + 1 >= nr_zones)
1016                 return -ENOENT;
1017
1018         return blkdev_zone_mgmt(bdev, REQ_OP_ZONE_RESET,
1019                                 zone_start_sector(sb_zone, bdev),
1020                                 zone_sectors * BTRFS_NR_SB_LOG_ZONES, GFP_NOFS);
1021 }
1022
1023 /**
1024  * btrfs_find_allocatable_zones - find allocatable zones within a given region
1025  *
1026  * @device:     the device to allocate a region on
1027  * @hole_start: the position of the hole to allocate the region
1028  * @num_bytes:  size of wanted region
1029  * @hole_end:   the end of the hole
1030  * @return:     position of allocatable zones
1031  *
1032  * Allocatable region should not contain any superblock locations.
1033  */
1034 u64 btrfs_find_allocatable_zones(struct btrfs_device *device, u64 hole_start,
1035                                  u64 hole_end, u64 num_bytes)
1036 {
1037         struct btrfs_zoned_device_info *zinfo = device->zone_info;
1038         const u8 shift = zinfo->zone_size_shift;
1039         u64 nzones = num_bytes >> shift;
1040         u64 pos = hole_start;
1041         u64 begin, end;
1042         bool have_sb;
1043         int i;
1044
1045         ASSERT(IS_ALIGNED(hole_start, zinfo->zone_size));
1046         ASSERT(IS_ALIGNED(num_bytes, zinfo->zone_size));
1047
1048         while (pos < hole_end) {
1049                 begin = pos >> shift;
1050                 end = begin + nzones;
1051
1052                 if (end > zinfo->nr_zones)
1053                         return hole_end;
1054
1055                 /* Check if zones in the region are all empty */
1056                 if (btrfs_dev_is_sequential(device, pos) &&
1057                     find_next_zero_bit(zinfo->empty_zones, end, begin) != end) {
1058                         pos += zinfo->zone_size;
1059                         continue;
1060                 }
1061
1062                 have_sb = false;
1063                 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1064                         u32 sb_zone;
1065                         u64 sb_pos;
1066
1067                         sb_zone = sb_zone_number(shift, i);
1068                         if (!(end <= sb_zone ||
1069                               sb_zone + BTRFS_NR_SB_LOG_ZONES <= begin)) {
1070                                 have_sb = true;
1071                                 pos = zone_start_physical(
1072                                         sb_zone + BTRFS_NR_SB_LOG_ZONES, zinfo);
1073                                 break;
1074                         }
1075
1076                         /* We also need to exclude regular superblock positions */
1077                         sb_pos = btrfs_sb_offset(i);
1078                         if (!(pos + num_bytes <= sb_pos ||
1079                               sb_pos + BTRFS_SUPER_INFO_SIZE <= pos)) {
1080                                 have_sb = true;
1081                                 pos = ALIGN(sb_pos + BTRFS_SUPER_INFO_SIZE,
1082                                             zinfo->zone_size);
1083                                 break;
1084                         }
1085                 }
1086                 if (!have_sb)
1087                         break;
1088         }
1089
1090         return pos;
1091 }
1092
1093 static bool btrfs_dev_set_active_zone(struct btrfs_device *device, u64 pos)
1094 {
1095         struct btrfs_zoned_device_info *zone_info = device->zone_info;
1096         unsigned int zno = (pos >> zone_info->zone_size_shift);
1097
1098         /* We can use any number of zones */
1099         if (zone_info->max_active_zones == 0)
1100                 return true;
1101
1102         if (!test_bit(zno, zone_info->active_zones)) {
1103                 /* Active zone left? */
1104                 if (atomic_dec_if_positive(&zone_info->active_zones_left) < 0)
1105                         return false;
1106                 if (test_and_set_bit(zno, zone_info->active_zones)) {
1107                         /* Someone already set the bit */
1108                         atomic_inc(&zone_info->active_zones_left);
1109                 }
1110         }
1111
1112         return true;
1113 }
1114
1115 static void btrfs_dev_clear_active_zone(struct btrfs_device *device, u64 pos)
1116 {
1117         struct btrfs_zoned_device_info *zone_info = device->zone_info;
1118         unsigned int zno = (pos >> zone_info->zone_size_shift);
1119
1120         /* We can use any number of zones */
1121         if (zone_info->max_active_zones == 0)
1122                 return;
1123
1124         if (test_and_clear_bit(zno, zone_info->active_zones))
1125                 atomic_inc(&zone_info->active_zones_left);
1126 }
1127
1128 int btrfs_reset_device_zone(struct btrfs_device *device, u64 physical,
1129                             u64 length, u64 *bytes)
1130 {
1131         int ret;
1132
1133         *bytes = 0;
1134         ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_RESET,
1135                                physical >> SECTOR_SHIFT, length >> SECTOR_SHIFT,
1136                                GFP_NOFS);
1137         if (ret)
1138                 return ret;
1139
1140         *bytes = length;
1141         while (length) {
1142                 btrfs_dev_set_zone_empty(device, physical);
1143                 btrfs_dev_clear_active_zone(device, physical);
1144                 physical += device->zone_info->zone_size;
1145                 length -= device->zone_info->zone_size;
1146         }
1147
1148         return 0;
1149 }
1150
1151 int btrfs_ensure_empty_zones(struct btrfs_device *device, u64 start, u64 size)
1152 {
1153         struct btrfs_zoned_device_info *zinfo = device->zone_info;
1154         const u8 shift = zinfo->zone_size_shift;
1155         unsigned long begin = start >> shift;
1156         unsigned long end = (start + size) >> shift;
1157         u64 pos;
1158         int ret;
1159
1160         ASSERT(IS_ALIGNED(start, zinfo->zone_size));
1161         ASSERT(IS_ALIGNED(size, zinfo->zone_size));
1162
1163         if (end > zinfo->nr_zones)
1164                 return -ERANGE;
1165
1166         /* All the zones are conventional */
1167         if (find_next_bit(zinfo->seq_zones, begin, end) == end)
1168                 return 0;
1169
1170         /* All the zones are sequential and empty */
1171         if (find_next_zero_bit(zinfo->seq_zones, begin, end) == end &&
1172             find_next_zero_bit(zinfo->empty_zones, begin, end) == end)
1173                 return 0;
1174
1175         for (pos = start; pos < start + size; pos += zinfo->zone_size) {
1176                 u64 reset_bytes;
1177
1178                 if (!btrfs_dev_is_sequential(device, pos) ||
1179                     btrfs_dev_is_empty_zone(device, pos))
1180                         continue;
1181
1182                 /* Free regions should be empty */
1183                 btrfs_warn_in_rcu(
1184                         device->fs_info,
1185                 "zoned: resetting device %s (devid %llu) zone %llu for allocation",
1186                         rcu_str_deref(device->name), device->devid, pos >> shift);
1187                 WARN_ON_ONCE(1);
1188
1189                 ret = btrfs_reset_device_zone(device, pos, zinfo->zone_size,
1190                                               &reset_bytes);
1191                 if (ret)
1192                         return ret;
1193         }
1194
1195         return 0;
1196 }
1197
1198 /*
1199  * Calculate an allocation pointer from the extent allocation information
1200  * for a block group consist of conventional zones. It is pointed to the
1201  * end of the highest addressed extent in the block group as an allocation
1202  * offset.
1203  */
1204 static int calculate_alloc_pointer(struct btrfs_block_group *cache,
1205                                    u64 *offset_ret, bool new)
1206 {
1207         struct btrfs_fs_info *fs_info = cache->fs_info;
1208         struct btrfs_root *root;
1209         struct btrfs_path *path;
1210         struct btrfs_key key;
1211         struct btrfs_key found_key;
1212         int ret;
1213         u64 length;
1214
1215         /*
1216          * Avoid  tree lookups for a new block group, there's no use for it.
1217          * It must always be 0.
1218          *
1219          * Also, we have a lock chain of extent buffer lock -> chunk mutex.
1220          * For new a block group, this function is called from
1221          * btrfs_make_block_group() which is already taking the chunk mutex.
1222          * Thus, we cannot call calculate_alloc_pointer() which takes extent
1223          * buffer locks to avoid deadlock.
1224          */
1225         if (new) {
1226                 *offset_ret = 0;
1227                 return 0;
1228         }
1229
1230         path = btrfs_alloc_path();
1231         if (!path)
1232                 return -ENOMEM;
1233
1234         key.objectid = cache->start + cache->length;
1235         key.type = 0;
1236         key.offset = 0;
1237
1238         root = btrfs_extent_root(fs_info, key.objectid);
1239         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1240         /* We should not find the exact match */
1241         if (!ret)
1242                 ret = -EUCLEAN;
1243         if (ret < 0)
1244                 goto out;
1245
1246         ret = btrfs_previous_extent_item(root, path, cache->start);
1247         if (ret) {
1248                 if (ret == 1) {
1249                         ret = 0;
1250                         *offset_ret = 0;
1251                 }
1252                 goto out;
1253         }
1254
1255         btrfs_item_key_to_cpu(path->nodes[0], &found_key, path->slots[0]);
1256
1257         if (found_key.type == BTRFS_EXTENT_ITEM_KEY)
1258                 length = found_key.offset;
1259         else
1260                 length = fs_info->nodesize;
1261
1262         if (!(found_key.objectid >= cache->start &&
1263                found_key.objectid + length <= cache->start + cache->length)) {
1264                 ret = -EUCLEAN;
1265                 goto out;
1266         }
1267         *offset_ret = found_key.objectid + length - cache->start;
1268         ret = 0;
1269
1270 out:
1271         btrfs_free_path(path);
1272         return ret;
1273 }
1274
1275 int btrfs_load_block_group_zone_info(struct btrfs_block_group *cache, bool new)
1276 {
1277         struct btrfs_fs_info *fs_info = cache->fs_info;
1278         struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1279         struct extent_map *em;
1280         struct map_lookup *map;
1281         struct btrfs_device *device;
1282         u64 logical = cache->start;
1283         u64 length = cache->length;
1284         int ret;
1285         int i;
1286         unsigned int nofs_flag;
1287         u64 *alloc_offsets = NULL;
1288         u64 *caps = NULL;
1289         u64 *physical = NULL;
1290         unsigned long *active = NULL;
1291         u64 last_alloc = 0;
1292         u32 num_sequential = 0, num_conventional = 0;
1293
1294         if (!btrfs_is_zoned(fs_info))
1295                 return 0;
1296
1297         /* Sanity check */
1298         if (!IS_ALIGNED(length, fs_info->zone_size)) {
1299                 btrfs_err(fs_info,
1300                 "zoned: block group %llu len %llu unaligned to zone size %llu",
1301                           logical, length, fs_info->zone_size);
1302                 return -EIO;
1303         }
1304
1305         /* Get the chunk mapping */
1306         read_lock(&em_tree->lock);
1307         em = lookup_extent_mapping(em_tree, logical, length);
1308         read_unlock(&em_tree->lock);
1309
1310         if (!em)
1311                 return -EINVAL;
1312
1313         map = em->map_lookup;
1314
1315         cache->physical_map = kmemdup(map, map_lookup_size(map->num_stripes), GFP_NOFS);
1316         if (!cache->physical_map) {
1317                 ret = -ENOMEM;
1318                 goto out;
1319         }
1320
1321         alloc_offsets = kcalloc(map->num_stripes, sizeof(*alloc_offsets), GFP_NOFS);
1322         if (!alloc_offsets) {
1323                 ret = -ENOMEM;
1324                 goto out;
1325         }
1326
1327         caps = kcalloc(map->num_stripes, sizeof(*caps), GFP_NOFS);
1328         if (!caps) {
1329                 ret = -ENOMEM;
1330                 goto out;
1331         }
1332
1333         physical = kcalloc(map->num_stripes, sizeof(*physical), GFP_NOFS);
1334         if (!physical) {
1335                 ret = -ENOMEM;
1336                 goto out;
1337         }
1338
1339         active = bitmap_zalloc(map->num_stripes, GFP_NOFS);
1340         if (!active) {
1341                 ret = -ENOMEM;
1342                 goto out;
1343         }
1344
1345         for (i = 0; i < map->num_stripes; i++) {
1346                 bool is_sequential;
1347                 struct blk_zone zone;
1348                 struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1349                 int dev_replace_is_ongoing = 0;
1350
1351                 device = map->stripes[i].dev;
1352                 physical[i] = map->stripes[i].physical;
1353
1354                 if (device->bdev == NULL) {
1355                         alloc_offsets[i] = WP_MISSING_DEV;
1356                         continue;
1357                 }
1358
1359                 is_sequential = btrfs_dev_is_sequential(device, physical[i]);
1360                 if (is_sequential)
1361                         num_sequential++;
1362                 else
1363                         num_conventional++;
1364
1365                 /*
1366                  * Consider a zone as active if we can allow any number of
1367                  * active zones.
1368                  */
1369                 if (!device->zone_info->max_active_zones)
1370                         __set_bit(i, active);
1371
1372                 if (!is_sequential) {
1373                         alloc_offsets[i] = WP_CONVENTIONAL;
1374                         continue;
1375                 }
1376
1377                 /*
1378                  * This zone will be used for allocation, so mark this zone
1379                  * non-empty.
1380                  */
1381                 btrfs_dev_clear_zone_empty(device, physical[i]);
1382
1383                 down_read(&dev_replace->rwsem);
1384                 dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
1385                 if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
1386                         btrfs_dev_clear_zone_empty(dev_replace->tgtdev, physical[i]);
1387                 up_read(&dev_replace->rwsem);
1388
1389                 /*
1390                  * The group is mapped to a sequential zone. Get the zone write
1391                  * pointer to determine the allocation offset within the zone.
1392                  */
1393                 WARN_ON(!IS_ALIGNED(physical[i], fs_info->zone_size));
1394                 nofs_flag = memalloc_nofs_save();
1395                 ret = btrfs_get_dev_zone(device, physical[i], &zone);
1396                 memalloc_nofs_restore(nofs_flag);
1397                 if (ret == -EIO || ret == -EOPNOTSUPP) {
1398                         ret = 0;
1399                         alloc_offsets[i] = WP_MISSING_DEV;
1400                         continue;
1401                 } else if (ret) {
1402                         goto out;
1403                 }
1404
1405                 if (zone.type == BLK_ZONE_TYPE_CONVENTIONAL) {
1406                         btrfs_err_in_rcu(fs_info,
1407         "zoned: unexpected conventional zone %llu on device %s (devid %llu)",
1408                                 zone.start << SECTOR_SHIFT,
1409                                 rcu_str_deref(device->name), device->devid);
1410                         ret = -EIO;
1411                         goto out;
1412                 }
1413
1414                 caps[i] = (zone.capacity << SECTOR_SHIFT);
1415
1416                 switch (zone.cond) {
1417                 case BLK_ZONE_COND_OFFLINE:
1418                 case BLK_ZONE_COND_READONLY:
1419                         btrfs_err(fs_info,
1420                 "zoned: offline/readonly zone %llu on device %s (devid %llu)",
1421                                   physical[i] >> device->zone_info->zone_size_shift,
1422                                   rcu_str_deref(device->name), device->devid);
1423                         alloc_offsets[i] = WP_MISSING_DEV;
1424                         break;
1425                 case BLK_ZONE_COND_EMPTY:
1426                         alloc_offsets[i] = 0;
1427                         break;
1428                 case BLK_ZONE_COND_FULL:
1429                         alloc_offsets[i] = caps[i];
1430                         break;
1431                 default:
1432                         /* Partially used zone */
1433                         alloc_offsets[i] =
1434                                         ((zone.wp - zone.start) << SECTOR_SHIFT);
1435                         __set_bit(i, active);
1436                         break;
1437                 }
1438         }
1439
1440         if (num_sequential > 0)
1441                 cache->seq_zone = true;
1442
1443         if (num_conventional > 0) {
1444                 /* Zone capacity is always zone size in emulation */
1445                 cache->zone_capacity = cache->length;
1446                 ret = calculate_alloc_pointer(cache, &last_alloc, new);
1447                 if (ret) {
1448                         btrfs_err(fs_info,
1449                         "zoned: failed to determine allocation offset of bg %llu",
1450                                   cache->start);
1451                         goto out;
1452                 } else if (map->num_stripes == num_conventional) {
1453                         cache->alloc_offset = last_alloc;
1454                         set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags);
1455                         goto out;
1456                 }
1457         }
1458
1459         switch (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
1460         case 0: /* single */
1461                 if (alloc_offsets[0] == WP_MISSING_DEV) {
1462                         btrfs_err(fs_info,
1463                         "zoned: cannot recover write pointer for zone %llu",
1464                                 physical[0]);
1465                         ret = -EIO;
1466                         goto out;
1467                 }
1468                 cache->alloc_offset = alloc_offsets[0];
1469                 cache->zone_capacity = caps[0];
1470                 if (test_bit(0, active))
1471                         set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags);
1472                 break;
1473         case BTRFS_BLOCK_GROUP_DUP:
1474                 if (map->type & BTRFS_BLOCK_GROUP_DATA) {
1475                         btrfs_err(fs_info, "zoned: profile DUP not yet supported on data bg");
1476                         ret = -EINVAL;
1477                         goto out;
1478                 }
1479                 if (alloc_offsets[0] == WP_MISSING_DEV) {
1480                         btrfs_err(fs_info,
1481                         "zoned: cannot recover write pointer for zone %llu",
1482                                 physical[0]);
1483                         ret = -EIO;
1484                         goto out;
1485                 }
1486                 if (alloc_offsets[1] == WP_MISSING_DEV) {
1487                         btrfs_err(fs_info,
1488                         "zoned: cannot recover write pointer for zone %llu",
1489                                 physical[1]);
1490                         ret = -EIO;
1491                         goto out;
1492                 }
1493                 if (alloc_offsets[0] != alloc_offsets[1]) {
1494                         btrfs_err(fs_info,
1495                         "zoned: write pointer offset mismatch of zones in DUP profile");
1496                         ret = -EIO;
1497                         goto out;
1498                 }
1499                 if (test_bit(0, active) != test_bit(1, active)) {
1500                         if (!btrfs_zone_activate(cache)) {
1501                                 ret = -EIO;
1502                                 goto out;
1503                         }
1504                 } else {
1505                         if (test_bit(0, active))
1506                                 set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
1507                                         &cache->runtime_flags);
1508                 }
1509                 cache->alloc_offset = alloc_offsets[0];
1510                 cache->zone_capacity = min(caps[0], caps[1]);
1511                 break;
1512         case BTRFS_BLOCK_GROUP_RAID1:
1513         case BTRFS_BLOCK_GROUP_RAID0:
1514         case BTRFS_BLOCK_GROUP_RAID10:
1515         case BTRFS_BLOCK_GROUP_RAID5:
1516         case BTRFS_BLOCK_GROUP_RAID6:
1517                 /* non-single profiles are not supported yet */
1518         default:
1519                 btrfs_err(fs_info, "zoned: profile %s not yet supported",
1520                           btrfs_bg_type_to_raid_name(map->type));
1521                 ret = -EINVAL;
1522                 goto out;
1523         }
1524
1525 out:
1526         if (cache->alloc_offset > fs_info->zone_size) {
1527                 btrfs_err(fs_info,
1528                         "zoned: invalid write pointer %llu in block group %llu",
1529                         cache->alloc_offset, cache->start);
1530                 ret = -EIO;
1531         }
1532
1533         if (cache->alloc_offset > cache->zone_capacity) {
1534                 btrfs_err(fs_info,
1535 "zoned: invalid write pointer %llu (larger than zone capacity %llu) in block group %llu",
1536                           cache->alloc_offset, cache->zone_capacity,
1537                           cache->start);
1538                 ret = -EIO;
1539         }
1540
1541         /* An extent is allocated after the write pointer */
1542         if (!ret && num_conventional && last_alloc > cache->alloc_offset) {
1543                 btrfs_err(fs_info,
1544                           "zoned: got wrong write pointer in BG %llu: %llu > %llu",
1545                           logical, last_alloc, cache->alloc_offset);
1546                 ret = -EIO;
1547         }
1548
1549         if (!ret) {
1550                 cache->meta_write_pointer = cache->alloc_offset + cache->start;
1551                 if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &cache->runtime_flags)) {
1552                         btrfs_get_block_group(cache);
1553                         spin_lock(&fs_info->zone_active_bgs_lock);
1554                         list_add_tail(&cache->active_bg_list,
1555                                       &fs_info->zone_active_bgs);
1556                         spin_unlock(&fs_info->zone_active_bgs_lock);
1557                 }
1558         } else {
1559                 kfree(cache->physical_map);
1560                 cache->physical_map = NULL;
1561         }
1562         bitmap_free(active);
1563         kfree(physical);
1564         kfree(caps);
1565         kfree(alloc_offsets);
1566         free_extent_map(em);
1567
1568         return ret;
1569 }
1570
1571 void btrfs_calc_zone_unusable(struct btrfs_block_group *cache)
1572 {
1573         u64 unusable, free;
1574
1575         if (!btrfs_is_zoned(cache->fs_info))
1576                 return;
1577
1578         WARN_ON(cache->bytes_super != 0);
1579         unusable = (cache->alloc_offset - cache->used) +
1580                    (cache->length - cache->zone_capacity);
1581         free = cache->zone_capacity - cache->alloc_offset;
1582
1583         /* We only need ->free_space in ALLOC_SEQ block groups */
1584         cache->cached = BTRFS_CACHE_FINISHED;
1585         cache->free_space_ctl->free_space = free;
1586         cache->zone_unusable = unusable;
1587 }
1588
1589 void btrfs_redirty_list_add(struct btrfs_transaction *trans,
1590                             struct extent_buffer *eb)
1591 {
1592         struct btrfs_fs_info *fs_info = eb->fs_info;
1593
1594         if (!btrfs_is_zoned(fs_info) ||
1595             btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN) ||
1596             !list_empty(&eb->release_list))
1597                 return;
1598
1599         set_extent_buffer_dirty(eb);
1600         set_extent_bits_nowait(&trans->dirty_pages, eb->start,
1601                                eb->start + eb->len - 1, EXTENT_DIRTY);
1602         memzero_extent_buffer(eb, 0, eb->len);
1603         set_bit(EXTENT_BUFFER_NO_CHECK, &eb->bflags);
1604
1605         spin_lock(&trans->releasing_ebs_lock);
1606         list_add_tail(&eb->release_list, &trans->releasing_ebs);
1607         spin_unlock(&trans->releasing_ebs_lock);
1608         atomic_inc(&eb->refs);
1609 }
1610
1611 void btrfs_free_redirty_list(struct btrfs_transaction *trans)
1612 {
1613         spin_lock(&trans->releasing_ebs_lock);
1614         while (!list_empty(&trans->releasing_ebs)) {
1615                 struct extent_buffer *eb;
1616
1617                 eb = list_first_entry(&trans->releasing_ebs,
1618                                       struct extent_buffer, release_list);
1619                 list_del_init(&eb->release_list);
1620                 free_extent_buffer(eb);
1621         }
1622         spin_unlock(&trans->releasing_ebs_lock);
1623 }
1624
1625 bool btrfs_use_zone_append(struct btrfs_inode *inode, u64 start)
1626 {
1627         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1628         struct btrfs_block_group *cache;
1629         bool ret = false;
1630
1631         if (!btrfs_is_zoned(fs_info))
1632                 return false;
1633
1634         if (!is_data_inode(&inode->vfs_inode))
1635                 return false;
1636
1637         /*
1638          * Using REQ_OP_ZONE_APPNED for relocation can break assumptions on the
1639          * extent layout the relocation code has.
1640          * Furthermore we have set aside own block-group from which only the
1641          * relocation "process" can allocate and make sure only one process at a
1642          * time can add pages to an extent that gets relocated, so it's safe to
1643          * use regular REQ_OP_WRITE for this special case.
1644          */
1645         if (btrfs_is_data_reloc_root(inode->root))
1646                 return false;
1647
1648         cache = btrfs_lookup_block_group(fs_info, start);
1649         ASSERT(cache);
1650         if (!cache)
1651                 return false;
1652
1653         ret = cache->seq_zone;
1654         btrfs_put_block_group(cache);
1655
1656         return ret;
1657 }
1658
1659 void btrfs_record_physical_zoned(struct inode *inode, u64 file_offset,
1660                                  struct bio *bio)
1661 {
1662         struct btrfs_ordered_extent *ordered;
1663         const u64 physical = bio->bi_iter.bi_sector << SECTOR_SHIFT;
1664
1665         if (bio_op(bio) != REQ_OP_ZONE_APPEND)
1666                 return;
1667
1668         ordered = btrfs_lookup_ordered_extent(BTRFS_I(inode), file_offset);
1669         if (WARN_ON(!ordered))
1670                 return;
1671
1672         ordered->physical = physical;
1673         ordered->bdev = bio->bi_bdev;
1674
1675         btrfs_put_ordered_extent(ordered);
1676 }
1677
1678 void btrfs_rewrite_logical_zoned(struct btrfs_ordered_extent *ordered)
1679 {
1680         struct btrfs_inode *inode = BTRFS_I(ordered->inode);
1681         struct btrfs_fs_info *fs_info = inode->root->fs_info;
1682         struct extent_map_tree *em_tree;
1683         struct extent_map *em;
1684         struct btrfs_ordered_sum *sum;
1685         u64 orig_logical = ordered->disk_bytenr;
1686         u64 *logical = NULL;
1687         int nr, stripe_len;
1688
1689         /* Zoned devices should not have partitions. So, we can assume it is 0 */
1690         ASSERT(!bdev_is_partition(ordered->bdev));
1691         if (WARN_ON(!ordered->bdev))
1692                 return;
1693
1694         if (WARN_ON(btrfs_rmap_block(fs_info, orig_logical, ordered->bdev,
1695                                      ordered->physical, &logical, &nr,
1696                                      &stripe_len)))
1697                 goto out;
1698
1699         WARN_ON(nr != 1);
1700
1701         if (orig_logical == *logical)
1702                 goto out;
1703
1704         ordered->disk_bytenr = *logical;
1705
1706         em_tree = &inode->extent_tree;
1707         write_lock(&em_tree->lock);
1708         em = search_extent_mapping(em_tree, ordered->file_offset,
1709                                    ordered->num_bytes);
1710         em->block_start = *logical;
1711         free_extent_map(em);
1712         write_unlock(&em_tree->lock);
1713
1714         list_for_each_entry(sum, &ordered->list, list) {
1715                 if (*logical < orig_logical)
1716                         sum->bytenr -= orig_logical - *logical;
1717                 else
1718                         sum->bytenr += *logical - orig_logical;
1719         }
1720
1721 out:
1722         kfree(logical);
1723 }
1724
1725 bool btrfs_check_meta_write_pointer(struct btrfs_fs_info *fs_info,
1726                                     struct extent_buffer *eb,
1727                                     struct btrfs_block_group **cache_ret)
1728 {
1729         struct btrfs_block_group *cache;
1730         bool ret = true;
1731
1732         if (!btrfs_is_zoned(fs_info))
1733                 return true;
1734
1735         cache = btrfs_lookup_block_group(fs_info, eb->start);
1736         if (!cache)
1737                 return true;
1738
1739         if (cache->meta_write_pointer != eb->start) {
1740                 btrfs_put_block_group(cache);
1741                 cache = NULL;
1742                 ret = false;
1743         } else {
1744                 cache->meta_write_pointer = eb->start + eb->len;
1745         }
1746
1747         *cache_ret = cache;
1748
1749         return ret;
1750 }
1751
1752 void btrfs_revert_meta_write_pointer(struct btrfs_block_group *cache,
1753                                      struct extent_buffer *eb)
1754 {
1755         if (!btrfs_is_zoned(eb->fs_info) || !cache)
1756                 return;
1757
1758         ASSERT(cache->meta_write_pointer == eb->start + eb->len);
1759         cache->meta_write_pointer = eb->start;
1760 }
1761
1762 int btrfs_zoned_issue_zeroout(struct btrfs_device *device, u64 physical, u64 length)
1763 {
1764         if (!btrfs_dev_is_sequential(device, physical))
1765                 return -EOPNOTSUPP;
1766
1767         return blkdev_issue_zeroout(device->bdev, physical >> SECTOR_SHIFT,
1768                                     length >> SECTOR_SHIFT, GFP_NOFS, 0);
1769 }
1770
1771 static int read_zone_info(struct btrfs_fs_info *fs_info, u64 logical,
1772                           struct blk_zone *zone)
1773 {
1774         struct btrfs_io_context *bioc = NULL;
1775         u64 mapped_length = PAGE_SIZE;
1776         unsigned int nofs_flag;
1777         int nmirrors;
1778         int i, ret;
1779
1780         ret = btrfs_map_sblock(fs_info, BTRFS_MAP_GET_READ_MIRRORS, logical,
1781                                &mapped_length, &bioc);
1782         if (ret || !bioc || mapped_length < PAGE_SIZE) {
1783                 ret = -EIO;
1784                 goto out_put_bioc;
1785         }
1786
1787         if (bioc->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
1788                 ret = -EINVAL;
1789                 goto out_put_bioc;
1790         }
1791
1792         nofs_flag = memalloc_nofs_save();
1793         nmirrors = (int)bioc->num_stripes;
1794         for (i = 0; i < nmirrors; i++) {
1795                 u64 physical = bioc->stripes[i].physical;
1796                 struct btrfs_device *dev = bioc->stripes[i].dev;
1797
1798                 /* Missing device */
1799                 if (!dev->bdev)
1800                         continue;
1801
1802                 ret = btrfs_get_dev_zone(dev, physical, zone);
1803                 /* Failing device */
1804                 if (ret == -EIO || ret == -EOPNOTSUPP)
1805                         continue;
1806                 break;
1807         }
1808         memalloc_nofs_restore(nofs_flag);
1809 out_put_bioc:
1810         btrfs_put_bioc(bioc);
1811         return ret;
1812 }
1813
1814 /*
1815  * Synchronize write pointer in a zone at @physical_start on @tgt_dev, by
1816  * filling zeros between @physical_pos to a write pointer of dev-replace
1817  * source device.
1818  */
1819 int btrfs_sync_zone_write_pointer(struct btrfs_device *tgt_dev, u64 logical,
1820                                     u64 physical_start, u64 physical_pos)
1821 {
1822         struct btrfs_fs_info *fs_info = tgt_dev->fs_info;
1823         struct blk_zone zone;
1824         u64 length;
1825         u64 wp;
1826         int ret;
1827
1828         if (!btrfs_dev_is_sequential(tgt_dev, physical_pos))
1829                 return 0;
1830
1831         ret = read_zone_info(fs_info, logical, &zone);
1832         if (ret)
1833                 return ret;
1834
1835         wp = physical_start + ((zone.wp - zone.start) << SECTOR_SHIFT);
1836
1837         if (physical_pos == wp)
1838                 return 0;
1839
1840         if (physical_pos > wp)
1841                 return -EUCLEAN;
1842
1843         length = wp - physical_pos;
1844         return btrfs_zoned_issue_zeroout(tgt_dev, physical_pos, length);
1845 }
1846
1847 struct btrfs_device *btrfs_zoned_get_device(struct btrfs_fs_info *fs_info,
1848                                             u64 logical, u64 length)
1849 {
1850         struct btrfs_device *device;
1851         struct extent_map *em;
1852         struct map_lookup *map;
1853
1854         em = btrfs_get_chunk_map(fs_info, logical, length);
1855         if (IS_ERR(em))
1856                 return ERR_CAST(em);
1857
1858         map = em->map_lookup;
1859         /* We only support single profile for now */
1860         device = map->stripes[0].dev;
1861
1862         free_extent_map(em);
1863
1864         return device;
1865 }
1866
1867 /**
1868  * Activate block group and underlying device zones
1869  *
1870  * @block_group: the block group to activate
1871  *
1872  * Return: true on success, false otherwise
1873  */
1874 bool btrfs_zone_activate(struct btrfs_block_group *block_group)
1875 {
1876         struct btrfs_fs_info *fs_info = block_group->fs_info;
1877         struct btrfs_space_info *space_info = block_group->space_info;
1878         struct map_lookup *map;
1879         struct btrfs_device *device;
1880         u64 physical;
1881         bool ret;
1882         int i;
1883
1884         if (!btrfs_is_zoned(block_group->fs_info))
1885                 return true;
1886
1887         map = block_group->physical_map;
1888
1889         spin_lock(&space_info->lock);
1890         spin_lock(&block_group->lock);
1891         if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
1892                 ret = true;
1893                 goto out_unlock;
1894         }
1895
1896         /* No space left */
1897         if (btrfs_zoned_bg_is_full(block_group)) {
1898                 ret = false;
1899                 goto out_unlock;
1900         }
1901
1902         for (i = 0; i < map->num_stripes; i++) {
1903                 device = map->stripes[i].dev;
1904                 physical = map->stripes[i].physical;
1905
1906                 if (device->zone_info->max_active_zones == 0)
1907                         continue;
1908
1909                 if (!btrfs_dev_set_active_zone(device, physical)) {
1910                         /* Cannot activate the zone */
1911                         ret = false;
1912                         goto out_unlock;
1913                 }
1914         }
1915
1916         /* Successfully activated all the zones */
1917         set_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
1918         space_info->active_total_bytes += block_group->length;
1919         spin_unlock(&block_group->lock);
1920         btrfs_try_granting_tickets(fs_info, space_info);
1921         spin_unlock(&space_info->lock);
1922
1923         /* For the active block group list */
1924         btrfs_get_block_group(block_group);
1925
1926         spin_lock(&fs_info->zone_active_bgs_lock);
1927         list_add_tail(&block_group->active_bg_list, &fs_info->zone_active_bgs);
1928         spin_unlock(&fs_info->zone_active_bgs_lock);
1929
1930         return true;
1931
1932 out_unlock:
1933         spin_unlock(&block_group->lock);
1934         spin_unlock(&space_info->lock);
1935         return ret;
1936 }
1937
1938 static void wait_eb_writebacks(struct btrfs_block_group *block_group)
1939 {
1940         struct btrfs_fs_info *fs_info = block_group->fs_info;
1941         const u64 end = block_group->start + block_group->length;
1942         struct radix_tree_iter iter;
1943         struct extent_buffer *eb;
1944         void __rcu **slot;
1945
1946         rcu_read_lock();
1947         radix_tree_for_each_slot(slot, &fs_info->buffer_radix, &iter,
1948                                  block_group->start >> fs_info->sectorsize_bits) {
1949                 eb = radix_tree_deref_slot(slot);
1950                 if (!eb)
1951                         continue;
1952                 if (radix_tree_deref_retry(eb)) {
1953                         slot = radix_tree_iter_retry(&iter);
1954                         continue;
1955                 }
1956
1957                 if (eb->start < block_group->start)
1958                         continue;
1959                 if (eb->start >= end)
1960                         break;
1961
1962                 slot = radix_tree_iter_resume(slot, &iter);
1963                 rcu_read_unlock();
1964                 wait_on_extent_buffer_writeback(eb);
1965                 rcu_read_lock();
1966         }
1967         rcu_read_unlock();
1968 }
1969
1970 static int do_zone_finish(struct btrfs_block_group *block_group, bool fully_written)
1971 {
1972         struct btrfs_fs_info *fs_info = block_group->fs_info;
1973         struct map_lookup *map;
1974         const bool is_metadata = (block_group->flags &
1975                         (BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_SYSTEM));
1976         int ret = 0;
1977         int i;
1978
1979         spin_lock(&block_group->lock);
1980         if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags)) {
1981                 spin_unlock(&block_group->lock);
1982                 return 0;
1983         }
1984
1985         /* Check if we have unwritten allocated space */
1986         if (is_metadata &&
1987             block_group->start + block_group->alloc_offset > block_group->meta_write_pointer) {
1988                 spin_unlock(&block_group->lock);
1989                 return -EAGAIN;
1990         }
1991
1992         /*
1993          * If we are sure that the block group is full (= no more room left for
1994          * new allocation) and the IO for the last usable block is completed, we
1995          * don't need to wait for the other IOs. This holds because we ensure
1996          * the sequential IO submissions using the ZONE_APPEND command for data
1997          * and block_group->meta_write_pointer for metadata.
1998          */
1999         if (!fully_written) {
2000                 spin_unlock(&block_group->lock);
2001
2002                 ret = btrfs_inc_block_group_ro(block_group, false);
2003                 if (ret)
2004                         return ret;
2005
2006                 /* Ensure all writes in this block group finish */
2007                 btrfs_wait_block_group_reservations(block_group);
2008                 /* No need to wait for NOCOW writers. Zoned mode does not allow that */
2009                 btrfs_wait_ordered_roots(fs_info, U64_MAX, block_group->start,
2010                                          block_group->length);
2011                 /* Wait for extent buffers to be written. */
2012                 if (is_metadata)
2013                         wait_eb_writebacks(block_group);
2014
2015                 spin_lock(&block_group->lock);
2016
2017                 /*
2018                  * Bail out if someone already deactivated the block group, or
2019                  * allocated space is left in the block group.
2020                  */
2021                 if (!test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2022                               &block_group->runtime_flags)) {
2023                         spin_unlock(&block_group->lock);
2024                         btrfs_dec_block_group_ro(block_group);
2025                         return 0;
2026                 }
2027
2028                 if (block_group->reserved) {
2029                         spin_unlock(&block_group->lock);
2030                         btrfs_dec_block_group_ro(block_group);
2031                         return -EAGAIN;
2032                 }
2033         }
2034
2035         clear_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags);
2036         block_group->alloc_offset = block_group->zone_capacity;
2037         block_group->free_space_ctl->free_space = 0;
2038         btrfs_clear_treelog_bg(block_group);
2039         btrfs_clear_data_reloc_bg(block_group);
2040         spin_unlock(&block_group->lock);
2041
2042         map = block_group->physical_map;
2043         for (i = 0; i < map->num_stripes; i++) {
2044                 struct btrfs_device *device = map->stripes[i].dev;
2045                 const u64 physical = map->stripes[i].physical;
2046
2047                 if (device->zone_info->max_active_zones == 0)
2048                         continue;
2049
2050                 ret = blkdev_zone_mgmt(device->bdev, REQ_OP_ZONE_FINISH,
2051                                        physical >> SECTOR_SHIFT,
2052                                        device->zone_info->zone_size >> SECTOR_SHIFT,
2053                                        GFP_NOFS);
2054
2055                 if (ret)
2056                         return ret;
2057
2058                 btrfs_dev_clear_active_zone(device, physical);
2059         }
2060
2061         if (!fully_written)
2062                 btrfs_dec_block_group_ro(block_group);
2063
2064         spin_lock(&fs_info->zone_active_bgs_lock);
2065         ASSERT(!list_empty(&block_group->active_bg_list));
2066         list_del_init(&block_group->active_bg_list);
2067         spin_unlock(&fs_info->zone_active_bgs_lock);
2068
2069         /* For active_bg_list */
2070         btrfs_put_block_group(block_group);
2071
2072         clear_and_wake_up_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2073
2074         return 0;
2075 }
2076
2077 int btrfs_zone_finish(struct btrfs_block_group *block_group)
2078 {
2079         if (!btrfs_is_zoned(block_group->fs_info))
2080                 return 0;
2081
2082         return do_zone_finish(block_group, false);
2083 }
2084
2085 bool btrfs_can_activate_zone(struct btrfs_fs_devices *fs_devices, u64 flags)
2086 {
2087         struct btrfs_fs_info *fs_info = fs_devices->fs_info;
2088         struct btrfs_device *device;
2089         bool ret = false;
2090
2091         if (!btrfs_is_zoned(fs_info))
2092                 return true;
2093
2094         /* Check if there is a device with active zones left */
2095         mutex_lock(&fs_info->chunk_mutex);
2096         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
2097                 struct btrfs_zoned_device_info *zinfo = device->zone_info;
2098
2099                 if (!device->bdev)
2100                         continue;
2101
2102                 if (!zinfo->max_active_zones) {
2103                         ret = true;
2104                         break;
2105                 }
2106
2107                 switch (flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
2108                 case 0: /* single */
2109                         ret = (atomic_read(&zinfo->active_zones_left) >= 1);
2110                         break;
2111                 case BTRFS_BLOCK_GROUP_DUP:
2112                         ret = (atomic_read(&zinfo->active_zones_left) >= 2);
2113                         break;
2114                 }
2115                 if (ret)
2116                         break;
2117         }
2118         mutex_unlock(&fs_info->chunk_mutex);
2119
2120         if (!ret)
2121                 set_bit(BTRFS_FS_NEED_ZONE_FINISH, &fs_info->flags);
2122
2123         return ret;
2124 }
2125
2126 void btrfs_zone_finish_endio(struct btrfs_fs_info *fs_info, u64 logical, u64 length)
2127 {
2128         struct btrfs_block_group *block_group;
2129         u64 min_alloc_bytes;
2130
2131         if (!btrfs_is_zoned(fs_info))
2132                 return;
2133
2134         block_group = btrfs_lookup_block_group(fs_info, logical);
2135         ASSERT(block_group);
2136
2137         /* No MIXED_BG on zoned btrfs. */
2138         if (block_group->flags & BTRFS_BLOCK_GROUP_DATA)
2139                 min_alloc_bytes = fs_info->sectorsize;
2140         else
2141                 min_alloc_bytes = fs_info->nodesize;
2142
2143         /* Bail out if we can allocate more data from this block group. */
2144         if (logical + length + min_alloc_bytes <=
2145             block_group->start + block_group->zone_capacity)
2146                 goto out;
2147
2148         do_zone_finish(block_group, true);
2149
2150 out:
2151         btrfs_put_block_group(block_group);
2152 }
2153
2154 static void btrfs_zone_finish_endio_workfn(struct work_struct *work)
2155 {
2156         struct btrfs_block_group *bg =
2157                 container_of(work, struct btrfs_block_group, zone_finish_work);
2158
2159         wait_on_extent_buffer_writeback(bg->last_eb);
2160         free_extent_buffer(bg->last_eb);
2161         btrfs_zone_finish_endio(bg->fs_info, bg->start, bg->length);
2162         btrfs_put_block_group(bg);
2163 }
2164
2165 void btrfs_schedule_zone_finish_bg(struct btrfs_block_group *bg,
2166                                    struct extent_buffer *eb)
2167 {
2168         if (!bg->seq_zone || eb->start + eb->len * 2 <= bg->start + bg->zone_capacity)
2169                 return;
2170
2171         if (WARN_ON(bg->zone_finish_work.func == btrfs_zone_finish_endio_workfn)) {
2172                 btrfs_err(bg->fs_info, "double scheduling of bg %llu zone finishing",
2173                           bg->start);
2174                 return;
2175         }
2176
2177         /* For the work */
2178         btrfs_get_block_group(bg);
2179         atomic_inc(&eb->refs);
2180         bg->last_eb = eb;
2181         INIT_WORK(&bg->zone_finish_work, btrfs_zone_finish_endio_workfn);
2182         queue_work(system_unbound_wq, &bg->zone_finish_work);
2183 }
2184
2185 void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg)
2186 {
2187         struct btrfs_fs_info *fs_info = bg->fs_info;
2188
2189         spin_lock(&fs_info->relocation_bg_lock);
2190         if (fs_info->data_reloc_bg == bg->start)
2191                 fs_info->data_reloc_bg = 0;
2192         spin_unlock(&fs_info->relocation_bg_lock);
2193 }
2194
2195 void btrfs_free_zone_cache(struct btrfs_fs_info *fs_info)
2196 {
2197         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2198         struct btrfs_device *device;
2199
2200         if (!btrfs_is_zoned(fs_info))
2201                 return;
2202
2203         mutex_lock(&fs_devices->device_list_mutex);
2204         list_for_each_entry(device, &fs_devices->devices, dev_list) {
2205                 if (device->zone_info) {
2206                         vfree(device->zone_info->zone_cache);
2207                         device->zone_info->zone_cache = NULL;
2208                 }
2209         }
2210         mutex_unlock(&fs_devices->device_list_mutex);
2211 }
2212
2213 bool btrfs_zoned_should_reclaim(struct btrfs_fs_info *fs_info)
2214 {
2215         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2216         struct btrfs_device *device;
2217         u64 used = 0;
2218         u64 total = 0;
2219         u64 factor;
2220
2221         ASSERT(btrfs_is_zoned(fs_info));
2222
2223         if (fs_info->bg_reclaim_threshold == 0)
2224                 return false;
2225
2226         mutex_lock(&fs_devices->device_list_mutex);
2227         list_for_each_entry(device, &fs_devices->devices, dev_list) {
2228                 if (!device->bdev)
2229                         continue;
2230
2231                 total += device->disk_total_bytes;
2232                 used += device->bytes_used;
2233         }
2234         mutex_unlock(&fs_devices->device_list_mutex);
2235
2236         factor = div64_u64(used * 100, total);
2237         return factor >= fs_info->bg_reclaim_threshold;
2238 }
2239
2240 void btrfs_zoned_release_data_reloc_bg(struct btrfs_fs_info *fs_info, u64 logical,
2241                                        u64 length)
2242 {
2243         struct btrfs_block_group *block_group;
2244
2245         if (!btrfs_is_zoned(fs_info))
2246                 return;
2247
2248         block_group = btrfs_lookup_block_group(fs_info, logical);
2249         /* It should be called on a previous data relocation block group. */
2250         ASSERT(block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA));
2251
2252         spin_lock(&block_group->lock);
2253         if (!test_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC, &block_group->runtime_flags))
2254                 goto out;
2255
2256         /* All relocation extents are written. */
2257         if (block_group->start + block_group->alloc_offset == logical + length) {
2258                 /* Now, release this block group for further allocations. */
2259                 clear_bit(BLOCK_GROUP_FLAG_ZONED_DATA_RELOC,
2260                           &block_group->runtime_flags);
2261         }
2262
2263 out:
2264         spin_unlock(&block_group->lock);
2265         btrfs_put_block_group(block_group);
2266 }
2267
2268 int btrfs_zone_finish_one_bg(struct btrfs_fs_info *fs_info)
2269 {
2270         struct btrfs_block_group *block_group;
2271         struct btrfs_block_group *min_bg = NULL;
2272         u64 min_avail = U64_MAX;
2273         int ret;
2274
2275         spin_lock(&fs_info->zone_active_bgs_lock);
2276         list_for_each_entry(block_group, &fs_info->zone_active_bgs,
2277                             active_bg_list) {
2278                 u64 avail;
2279
2280                 spin_lock(&block_group->lock);
2281                 if (block_group->reserved ||
2282                     (block_group->flags & BTRFS_BLOCK_GROUP_SYSTEM)) {
2283                         spin_unlock(&block_group->lock);
2284                         continue;
2285                 }
2286
2287                 avail = block_group->zone_capacity - block_group->alloc_offset;
2288                 if (min_avail > avail) {
2289                         if (min_bg)
2290                                 btrfs_put_block_group(min_bg);
2291                         min_bg = block_group;
2292                         min_avail = avail;
2293                         btrfs_get_block_group(min_bg);
2294                 }
2295                 spin_unlock(&block_group->lock);
2296         }
2297         spin_unlock(&fs_info->zone_active_bgs_lock);
2298
2299         if (!min_bg)
2300                 return 0;
2301
2302         ret = btrfs_zone_finish(min_bg);
2303         btrfs_put_block_group(min_bg);
2304
2305         return ret < 0 ? ret : 1;
2306 }
2307
2308 int btrfs_zoned_activate_one_bg(struct btrfs_fs_info *fs_info,
2309                                 struct btrfs_space_info *space_info,
2310                                 bool do_finish)
2311 {
2312         struct btrfs_block_group *bg;
2313         int index;
2314
2315         if (!btrfs_is_zoned(fs_info) || (space_info->flags & BTRFS_BLOCK_GROUP_DATA))
2316                 return 0;
2317
2318         /* No more block groups to activate */
2319         if (space_info->active_total_bytes == space_info->total_bytes)
2320                 return 0;
2321
2322         for (;;) {
2323                 int ret;
2324                 bool need_finish = false;
2325
2326                 down_read(&space_info->groups_sem);
2327                 for (index = 0; index < BTRFS_NR_RAID_TYPES; index++) {
2328                         list_for_each_entry(bg, &space_info->block_groups[index],
2329                                             list) {
2330                                 if (!spin_trylock(&bg->lock))
2331                                         continue;
2332                                 if (btrfs_zoned_bg_is_full(bg) ||
2333                                     test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
2334                                              &bg->runtime_flags)) {
2335                                         spin_unlock(&bg->lock);
2336                                         continue;
2337                                 }
2338                                 spin_unlock(&bg->lock);
2339
2340                                 if (btrfs_zone_activate(bg)) {
2341                                         up_read(&space_info->groups_sem);
2342                                         return 1;
2343                                 }
2344
2345                                 need_finish = true;
2346                         }
2347                 }
2348                 up_read(&space_info->groups_sem);
2349
2350                 if (!do_finish || !need_finish)
2351                         break;
2352
2353                 ret = btrfs_zone_finish_one_bg(fs_info);
2354                 if (ret == 0)
2355                         break;
2356                 if (ret < 0)
2357                         return ret;
2358         }
2359
2360         return 0;
2361 }