36b68d62597eee1be6e3b7c577d2ccac5d500a15
[fio.git] / zbd.c
1 /*
2  * Copyright (C) 2018 Western Digital Corporation or its affiliates.
3  *
4  * This file is released under the GPL.
5  */
6
7 #include <errno.h>
8 #include <string.h>
9 #include <stdlib.h>
10 #include <fcntl.h>
11 #include <sys/stat.h>
12 #include <unistd.h>
13
14 #include "os/os.h"
15 #include "file.h"
16 #include "fio.h"
17 #include "lib/pow2.h"
18 #include "log.h"
19 #include "oslib/asprintf.h"
20 #include "smalloc.h"
21 #include "verify.h"
22 #include "pshared.h"
23 #include "zbd.h"
24
25 static bool is_valid_offset(const struct fio_file *f, uint64_t offset)
26 {
27         return (uint64_t)(offset - f->file_offset) < f->io_size;
28 }
29
30 static inline unsigned int zbd_zone_idx(const struct fio_file *f,
31                                         struct fio_zone_info *zone)
32 {
33         return zone - f->zbd_info->zone_info;
34 }
35
36 /**
37  * zbd_offset_to_zone_idx - convert an offset into a zone number
38  * @f: file pointer.
39  * @offset: offset in bytes. If this offset is in the first zone_size bytes
40  *          past the disk size then the index of the sentinel is returned.
41  */
42 static unsigned int zbd_offset_to_zone_idx(const struct fio_file *f,
43                                            uint64_t offset)
44 {
45         uint32_t zone_idx;
46
47         if (f->zbd_info->zone_size_log2 > 0)
48                 zone_idx = offset >> f->zbd_info->zone_size_log2;
49         else
50                 zone_idx = offset / f->zbd_info->zone_size;
51
52         return min(zone_idx, f->zbd_info->nr_zones);
53 }
54
55 /**
56  * zbd_zone_end - Return zone end location
57  * @z: zone info pointer.
58  */
59 static inline uint64_t zbd_zone_end(const struct fio_zone_info *z)
60 {
61         return (z+1)->start;
62 }
63
64 /**
65  * zbd_zone_capacity_end - Return zone capacity limit end location
66  * @z: zone info pointer.
67  */
68 static inline uint64_t zbd_zone_capacity_end(const struct fio_zone_info *z)
69 {
70         return z->start + z->capacity;
71 }
72
73 /**
74  * zbd_zone_remainder - Return the number of bytes that are still available for
75  *                      writing before the zone gets full
76  * @z: zone info pointer.
77  */
78 static inline uint64_t zbd_zone_remainder(struct fio_zone_info *z)
79 {
80         if (z->wp >= zbd_zone_capacity_end(z))
81                 return 0;
82
83         return zbd_zone_capacity_end(z) - z->wp;
84 }
85
86 /**
87  * zbd_zone_full - verify whether a minimum number of bytes remain in a zone
88  * @f: file pointer.
89  * @z: zone info pointer.
90  * @required: minimum number of bytes that must remain in a zone.
91  *
92  * The caller must hold z->mutex.
93  */
94 static bool zbd_zone_full(const struct fio_file *f, struct fio_zone_info *z,
95                           uint64_t required)
96 {
97         assert((required & 511) == 0);
98
99         return z->has_wp && required > zbd_zone_remainder(z);
100 }
101
102 static void zone_lock(struct thread_data *td, const struct fio_file *f,
103                       struct fio_zone_info *z)
104 {
105         struct zoned_block_device_info *zbd = f->zbd_info;
106         uint32_t nz = z - zbd->zone_info;
107
108         /* A thread should never lock zones outside its working area. */
109         assert(f->min_zone <= nz && nz < f->max_zone);
110
111         assert(z->has_wp);
112
113         /*
114          * Lock the io_u target zone. The zone will be unlocked if io_u offset
115          * is changed or when io_u completes and zbd_put_io() executed.
116          * To avoid multiple jobs doing asynchronous I/Os from deadlocking each
117          * other waiting for zone locks when building an io_u batch, first
118          * only trylock the zone. If the zone is already locked by another job,
119          * process the currently queued I/Os so that I/O progress is made and
120          * zones unlocked.
121          */
122         if (pthread_mutex_trylock(&z->mutex) != 0) {
123                 if (!td_ioengine_flagged(td, FIO_SYNCIO))
124                         io_u_quiesce(td);
125                 pthread_mutex_lock(&z->mutex);
126         }
127 }
128
129 static inline void zone_unlock(struct fio_zone_info *z)
130 {
131         int ret;
132
133         assert(z->has_wp);
134         ret = pthread_mutex_unlock(&z->mutex);
135         assert(!ret);
136 }
137
138 static inline struct fio_zone_info *zbd_get_zone(const struct fio_file *f,
139                                                  unsigned int zone_idx)
140 {
141         return &f->zbd_info->zone_info[zone_idx];
142 }
143
144 static inline struct fio_zone_info *
145 zbd_offset_to_zone(const struct fio_file *f,  uint64_t offset)
146 {
147         return zbd_get_zone(f, zbd_offset_to_zone_idx(f, offset));
148 }
149
150 static bool accounting_vdb(struct thread_data *td, const struct fio_file *f)
151 {
152         return td->o.zrt.u.f && td_write(td);
153 }
154
155 /**
156  * zbd_get_zoned_model - Get a device zoned model
157  * @td: FIO thread data
158  * @f: FIO file for which to get model information
159  */
160 static int zbd_get_zoned_model(struct thread_data *td, struct fio_file *f,
161                                enum zbd_zoned_model *model)
162 {
163         int ret;
164
165         if (f->filetype == FIO_TYPE_PIPE) {
166                 log_err("zonemode=zbd does not support pipes\n");
167                 return -EINVAL;
168         }
169
170         /* If regular file, always emulate zones inside the file. */
171         if (f->filetype == FIO_TYPE_FILE) {
172                 *model = ZBD_NONE;
173                 return 0;
174         }
175
176         if (td->io_ops && td->io_ops->get_zoned_model)
177                 ret = td->io_ops->get_zoned_model(td, f, model);
178         else
179                 ret = blkzoned_get_zoned_model(td, f, model);
180         if (ret < 0) {
181                 td_verror(td, errno, "get zoned model failed");
182                 log_err("%s: get zoned model failed (%d).\n",
183                         f->file_name, errno);
184         }
185
186         return ret;
187 }
188
189 /**
190  * zbd_report_zones - Get zone information
191  * @td: FIO thread data.
192  * @f: FIO file for which to get zone information
193  * @offset: offset from which to report zones
194  * @zones: Array of struct zbd_zone
195  * @nr_zones: Size of @zones array
196  *
197  * Get zone information into @zones starting from the zone at offset @offset
198  * for the device specified by @f.
199  *
200  * Returns the number of zones reported upon success and a negative error code
201  * upon failure. If the zone report is empty, always assume an error (device
202  * problem) and return -EIO.
203  */
204 static int zbd_report_zones(struct thread_data *td, struct fio_file *f,
205                             uint64_t offset, struct zbd_zone *zones,
206                             unsigned int nr_zones)
207 {
208         int ret;
209
210         if (td->io_ops && td->io_ops->report_zones)
211                 ret = td->io_ops->report_zones(td, f, offset, zones, nr_zones);
212         else
213                 ret = blkzoned_report_zones(td, f, offset, zones, nr_zones);
214         if (ret < 0) {
215                 td_verror(td, errno, "report zones failed");
216                 log_err("%s: report zones from sector %"PRIu64" failed (nr_zones=%d; errno=%d).\n",
217                         f->file_name, offset >> 9, nr_zones, errno);
218         } else if (ret == 0) {
219                 td_verror(td, errno, "Empty zone report");
220                 log_err("%s: report zones from sector %"PRIu64" is empty.\n",
221                         f->file_name, offset >> 9);
222                 ret = -EIO;
223         }
224
225         return ret;
226 }
227
228 /**
229  * zbd_reset_wp - reset the write pointer of a range of zones
230  * @td: FIO thread data.
231  * @f: FIO file for which to reset zones
232  * @offset: Starting offset of the first zone to reset
233  * @length: Length of the range of zones to reset
234  *
235  * Reset the write pointer of all zones in the range @offset...@offset+@length.
236  * Returns 0 upon success and a negative error code upon failure.
237  */
238 static int zbd_reset_wp(struct thread_data *td, struct fio_file *f,
239                         uint64_t offset, uint64_t length)
240 {
241         int ret;
242
243         if (td->io_ops && td->io_ops->reset_wp)
244                 ret = td->io_ops->reset_wp(td, f, offset, length);
245         else
246                 ret = blkzoned_reset_wp(td, f, offset, length);
247         if (ret < 0) {
248                 td_verror(td, errno, "resetting wp failed");
249                 log_err("%s: resetting wp for %"PRIu64" sectors at sector %"PRIu64" failed (%d).\n",
250                         f->file_name, length >> 9, offset >> 9, errno);
251         }
252
253         return ret;
254 }
255
256 /**
257  * zbd_reset_zone - reset the write pointer of a single zone
258  * @td: FIO thread data.
259  * @f: FIO file associated with the disk for which to reset a write pointer.
260  * @z: Zone to reset.
261  *
262  * Returns 0 upon success and a negative error code upon failure.
263  *
264  * The caller must hold z->mutex.
265  */
266 static int zbd_reset_zone(struct thread_data *td, struct fio_file *f,
267                           struct fio_zone_info *z)
268 {
269         uint64_t offset = z->start;
270         uint64_t length = (z+1)->start - offset;
271         uint64_t data_in_zone = z->wp - z->start;
272         int ret = 0;
273
274         if (!data_in_zone)
275                 return 0;
276
277         assert(is_valid_offset(f, offset + length - 1));
278
279         dprint(FD_ZBD, "%s: resetting wp of zone %u.\n",
280                f->file_name, zbd_zone_idx(f, z));
281
282         switch (f->zbd_info->model) {
283         case ZBD_HOST_AWARE:
284         case ZBD_HOST_MANAGED:
285                 ret = zbd_reset_wp(td, f, offset, length);
286                 if (ret < 0)
287                         return ret;
288                 break;
289         default:
290                 break;
291         }
292
293         if (accounting_vdb(td, f)) {
294                 pthread_mutex_lock(&f->zbd_info->mutex);
295                 f->zbd_info->wp_valid_data_bytes -= data_in_zone;
296                 pthread_mutex_unlock(&f->zbd_info->mutex);
297         }
298
299         z->wp = z->start;
300
301         td->ts.nr_zone_resets++;
302
303         return ret;
304 }
305
306 /**
307  * zbd_write_zone_put - Remove a zone from the write target zones array.
308  * @td: FIO thread data.
309  * @f: FIO file that has the write zones array to remove.
310  * @zone_idx: Index of the zone to remove.
311  *
312  * The caller must hold f->zbd_info->mutex.
313  */
314 static void zbd_write_zone_put(struct thread_data *td, const struct fio_file *f,
315                                struct fio_zone_info *z)
316 {
317         uint32_t zi;
318
319         if (!z->write)
320                 return;
321
322         for (zi = 0; zi < f->zbd_info->num_write_zones; zi++) {
323                 if (zbd_get_zone(f, f->zbd_info->write_zones[zi]) == z)
324                         break;
325         }
326         if (zi == f->zbd_info->num_write_zones)
327                 return;
328
329         dprint(FD_ZBD, "%s: removing zone %u from write zone array\n",
330                f->file_name, zbd_zone_idx(f, z));
331
332         memmove(f->zbd_info->write_zones + zi,
333                 f->zbd_info->write_zones + zi + 1,
334                 (ZBD_MAX_WRITE_ZONES - (zi + 1)) *
335                 sizeof(f->zbd_info->write_zones[0]));
336
337         f->zbd_info->num_write_zones--;
338         td->num_write_zones--;
339         z->write = 0;
340 }
341
342 /**
343  * zbd_finish_zone - finish the specified zone
344  * @td: FIO thread data.
345  * @f: FIO file for which to finish a zone
346  * @z: Zone to finish.
347  *
348  * Finish the zone at @offset with open or close status.
349  */
350 static int zbd_finish_zone(struct thread_data *td, struct fio_file *f,
351                            struct fio_zone_info *z)
352 {
353         uint64_t offset = z->start;
354         uint64_t length = f->zbd_info->zone_size;
355         int ret = 0;
356
357         switch (f->zbd_info->model) {
358         case ZBD_HOST_AWARE:
359         case ZBD_HOST_MANAGED:
360                 if (td->io_ops && td->io_ops->finish_zone)
361                         ret = td->io_ops->finish_zone(td, f, offset, length);
362                 else
363                         ret = blkzoned_finish_zone(td, f, offset, length);
364                 break;
365         default:
366                 break;
367         }
368
369         if (ret < 0) {
370                 td_verror(td, errno, "finish zone failed");
371                 log_err("%s: finish zone at sector %"PRIu64" failed (%d).\n",
372                         f->file_name, offset >> 9, errno);
373         } else {
374                 z->wp = (z+1)->start;
375         }
376
377         return ret;
378 }
379
380 /**
381  * zbd_reset_zones - Reset a range of zones.
382  * @td: fio thread data.
383  * @f: fio file for which to reset zones
384  * @zb: first zone to reset.
385  * @ze: first zone not to reset.
386  *
387  * Returns 0 upon success and 1 upon failure.
388  */
389 static int zbd_reset_zones(struct thread_data *td, struct fio_file *f,
390                            struct fio_zone_info *const zb,
391                            struct fio_zone_info *const ze)
392 {
393         struct fio_zone_info *z;
394         const uint64_t min_bs = td->o.min_bs[DDIR_WRITE];
395         int res = 0;
396
397         assert(min_bs);
398
399         dprint(FD_ZBD, "%s: examining zones %u .. %u\n",
400                f->file_name, zbd_zone_idx(f, zb), zbd_zone_idx(f, ze));
401
402         for (z = zb; z < ze; z++) {
403                 if (!z->has_wp)
404                         continue;
405
406                 zone_lock(td, f, z);
407                 pthread_mutex_lock(&f->zbd_info->mutex);
408                 zbd_write_zone_put(td, f, z);
409                 pthread_mutex_unlock(&f->zbd_info->mutex);
410
411                 if (z->wp != z->start) {
412                         dprint(FD_ZBD, "%s: resetting zone %u\n",
413                                f->file_name, zbd_zone_idx(f, z));
414                         if (zbd_reset_zone(td, f, z) < 0)
415                                 res = 1;
416                 }
417
418                 zone_unlock(z);
419         }
420
421         return res;
422 }
423
424 /**
425  * zbd_get_max_open_zones - Get the maximum number of open zones
426  * @td: FIO thread data
427  * @f: FIO file for which to get max open zones
428  * @max_open_zones: Upon success, result will be stored here.
429  *
430  * A @max_open_zones value set to zero means no limit.
431  *
432  * Returns 0 upon success and a negative error code upon failure.
433  */
434 static int zbd_get_max_open_zones(struct thread_data *td, struct fio_file *f,
435                                   unsigned int *max_open_zones)
436 {
437         int ret;
438
439         if (td->io_ops && td->io_ops->get_max_open_zones)
440                 ret = td->io_ops->get_max_open_zones(td, f, max_open_zones);
441         else
442                 ret = blkzoned_get_max_open_zones(td, f, max_open_zones);
443         if (ret < 0) {
444                 td_verror(td, errno, "get max open zones failed");
445                 log_err("%s: get max open zones failed (%d).\n",
446                         f->file_name, errno);
447         }
448
449         return ret;
450 }
451
452 /**
453  * __zbd_write_zone_get - Add a zone to the array of write zones.
454  * @td: fio thread data.
455  * @f: fio file that has the write zones array to add.
456  * @zone_idx: Index of the zone to add.
457  *
458  * Do same operation as @zbd_write_zone_get, except it adds the zone at
459  * @zone_idx to write target zones array even when it does not have remainder
460  * space to write one block.
461  */
462 static bool __zbd_write_zone_get(struct thread_data *td,
463                                  const struct fio_file *f,
464                                  struct fio_zone_info *z)
465 {
466         struct zoned_block_device_info *zbdi = f->zbd_info;
467         uint32_t zone_idx = zbd_zone_idx(f, z);
468         bool res = true;
469
470         if (z->cond == ZBD_ZONE_COND_OFFLINE)
471                 return false;
472
473         /*
474          * Skip full zones with data verification enabled because resetting a
475          * zone causes data loss and hence causes verification to fail.
476          */
477         if (td->o.verify != VERIFY_NONE && zbd_zone_remainder(z) == 0)
478                 return false;
479
480         /*
481          * zbdi->max_write_zones == 0 means that there is no limit on the
482          * maximum number of write target zones. In this case, do no track write
483          * target zones in zbdi->write_zones array.
484          */
485         if (!zbdi->max_write_zones)
486                 return true;
487
488         pthread_mutex_lock(&zbdi->mutex);
489
490         if (z->write) {
491                 /*
492                  * If the zone is going to be completely filled by writes
493                  * already in-flight, handle it as a full zone instead of a
494                  * write target zone.
495                  */
496                 if (!zbd_zone_remainder(z))
497                         res = false;
498                 goto out;
499         }
500
501         res = false;
502         /* Zero means no limit */
503         if (td->o.job_max_open_zones > 0 &&
504             td->num_write_zones >= td->o.job_max_open_zones)
505                 goto out;
506         if (zbdi->num_write_zones >= zbdi->max_write_zones)
507                 goto out;
508
509         dprint(FD_ZBD, "%s: adding zone %u to write zone array\n",
510                f->file_name, zone_idx);
511
512         zbdi->write_zones[zbdi->num_write_zones++] = zone_idx;
513         td->num_write_zones++;
514         z->write = 1;
515         res = true;
516
517 out:
518         pthread_mutex_unlock(&zbdi->mutex);
519         return res;
520 }
521
522 /**
523  * zbd_write_zone_get - Add a zone to the array of write zones.
524  * @td: fio thread data.
525  * @f: fio file that has the open zones to add.
526  * @zone_idx: Index of the zone to add.
527  *
528  * Add a ZBD zone to write target zones array, if it is not yet added. Returns
529  * true if either the zone was already added or if the zone was successfully
530  * added to the array without exceeding the maximum number of write zones.
531  * Returns false if the zone was not already added and addition of the zone
532  * would cause the zone limit to be exceeded.
533  */
534 static bool zbd_write_zone_get(struct thread_data *td, const struct fio_file *f,
535                                struct fio_zone_info *z)
536 {
537         const uint64_t min_bs = td->o.min_bs[DDIR_WRITE];
538
539         /*
540          * Skip full zones with data verification enabled because resetting a
541          * zone causes data loss and hence causes verification to fail.
542          */
543         if (td->o.verify != VERIFY_NONE && zbd_zone_full(f, z, min_bs))
544                 return false;
545
546         return __zbd_write_zone_get(td, f, z);
547 }
548
549 /* Verify whether direct I/O is used for all host-managed zoned block drives. */
550 static bool zbd_using_direct_io(void)
551 {
552         struct fio_file *f;
553         int j;
554
555         for_each_td(td) {
556                 if (td->o.odirect || !(td->o.td_ddir & TD_DDIR_WRITE))
557                         continue;
558                 for_each_file(td, f, j) {
559                         if (f->zbd_info && f->filetype == FIO_TYPE_BLOCK &&
560                             f->zbd_info->model == ZBD_HOST_MANAGED)
561                                 return false;
562                 }
563         } end_for_each();
564
565         return true;
566 }
567
568 /* Whether or not the I/O range for f includes one or more sequential zones */
569 static bool zbd_is_seq_job(const struct fio_file *f)
570 {
571         uint32_t zone_idx, zone_idx_b, zone_idx_e;
572
573         assert(f->zbd_info);
574
575         if (f->io_size == 0)
576                 return false;
577
578         zone_idx_b = zbd_offset_to_zone_idx(f, f->file_offset);
579         zone_idx_e =
580                 zbd_offset_to_zone_idx(f, f->file_offset + f->io_size - 1);
581         for (zone_idx = zone_idx_b; zone_idx <= zone_idx_e; zone_idx++)
582                 if (zbd_get_zone(f, zone_idx)->has_wp)
583                         return true;
584
585         return false;
586 }
587
588 /*
589  * Verify whether the file offset and size parameters are aligned with zone
590  * boundaries. If the file offset is not aligned, align it down to the start of
591  * the zone containing the start offset and align up the file io_size parameter.
592  */
593 static bool zbd_zone_align_file_sizes(struct thread_data *td,
594                                       struct fio_file *f)
595 {
596         const struct fio_zone_info *z;
597         uint64_t new_offset, new_end;
598
599         if (!f->zbd_info)
600                 return true;
601         if (f->file_offset >= f->real_file_size)
602                 return true;
603         if (!zbd_is_seq_job(f))
604                 return true;
605
606         if (!td->o.zone_size) {
607                 td->o.zone_size = f->zbd_info->zone_size;
608                 if (!td->o.zone_size) {
609                         log_err("%s: invalid 0 zone size\n",
610                                 f->file_name);
611                         return false;
612                 }
613         } else if (td->o.zone_size != f->zbd_info->zone_size) {
614                 log_err("%s: zonesize %llu does not match the device zone size %"PRIu64".\n",
615                         f->file_name, td->o.zone_size,
616                         f->zbd_info->zone_size);
617                 return false;
618         }
619
620         if (td->o.zone_skip % td->o.zone_size) {
621                 log_err("%s: zoneskip %llu is not a multiple of the device zone size %llu.\n",
622                         f->file_name, td->o.zone_skip,
623                         td->o.zone_size);
624                 return false;
625         }
626
627         z = zbd_offset_to_zone(f, f->file_offset);
628         if ((f->file_offset != z->start) &&
629             (td->o.td_ddir != TD_DDIR_READ)) {
630                 new_offset = zbd_zone_end(z);
631                 if (new_offset >= f->file_offset + f->io_size) {
632                         log_info("%s: io_size must be at least one zone\n",
633                                  f->file_name);
634                         return false;
635                 }
636                 log_info("%s: rounded up offset from %"PRIu64" to %"PRIu64"\n",
637                          f->file_name, f->file_offset,
638                          new_offset);
639                 f->io_size -= (new_offset - f->file_offset);
640                 f->file_offset = new_offset;
641         }
642
643         z = zbd_offset_to_zone(f, f->file_offset + f->io_size);
644         new_end = z->start;
645         if ((td->o.td_ddir != TD_DDIR_READ) &&
646             (f->file_offset + f->io_size != new_end)) {
647                 if (new_end <= f->file_offset) {
648                         log_info("%s: io_size must be at least one zone\n",
649                                  f->file_name);
650                         return false;
651                 }
652                 log_info("%s: rounded down io_size from %"PRIu64" to %"PRIu64"\n",
653                          f->file_name, f->io_size,
654                          new_end - f->file_offset);
655                 f->io_size = new_end - f->file_offset;
656         }
657
658         return true;
659 }
660
661 /*
662  * Verify whether offset and size parameters are aligned with zone boundaries.
663  */
664 static bool zbd_verify_sizes(void)
665 {
666         struct fio_file *f;
667         int j;
668
669         for_each_td(td) {
670                 for_each_file(td, f, j) {
671                         if (!zbd_zone_align_file_sizes(td, f))
672                                 return false;
673                 }
674         } end_for_each();
675
676         return true;
677 }
678
679 static bool zbd_verify_bs(void)
680 {
681         struct fio_file *f;
682         int j;
683
684         for_each_td(td) {
685                 if (td_trim(td) &&
686                     (td->o.min_bs[DDIR_TRIM] != td->o.max_bs[DDIR_TRIM] ||
687                      td->o.bssplit_nr[DDIR_TRIM])) {
688                         log_info("bsrange and bssplit are not allowed for trim with zonemode=zbd\n");
689                         return false;
690                 }
691                 for_each_file(td, f, j) {
692                         uint64_t zone_size;
693
694                         if (!f->zbd_info)
695                                 continue;
696
697                         zone_size = f->zbd_info->zone_size;
698                         if (td_trim(td) && td->o.bs[DDIR_TRIM] != zone_size) {
699                                 log_info("%s: trim block size %llu is not the zone size %"PRIu64"\n",
700                                          f->file_name, td->o.bs[DDIR_TRIM],
701                                          zone_size);
702                                 return false;
703                         }
704                 }
705         } end_for_each();
706         return true;
707 }
708
709 static int ilog2(uint64_t i)
710 {
711         int log = -1;
712
713         while (i) {
714                 i >>= 1;
715                 log++;
716         }
717         return log;
718 }
719
720 /*
721  * Initialize f->zbd_info for devices that are not zoned block devices. This
722  * allows to execute a ZBD workload against a non-ZBD device.
723  */
724 static int init_zone_info(struct thread_data *td, struct fio_file *f)
725 {
726         uint32_t nr_zones;
727         struct fio_zone_info *p;
728         uint64_t zone_size = td->o.zone_size;
729         uint64_t zone_capacity = td->o.zone_capacity;
730         struct zoned_block_device_info *zbd_info = NULL;
731         int i;
732
733         if (zone_size == 0) {
734                 log_err("%s: Specifying the zone size is mandatory for regular file/block device with --zonemode=zbd\n\n",
735                         f->file_name);
736                 return 1;
737         }
738
739         if (zone_size < 512) {
740                 log_err("%s: zone size must be at least 512 bytes for --zonemode=zbd\n\n",
741                         f->file_name);
742                 return 1;
743         }
744
745         if (zone_capacity == 0)
746                 zone_capacity = zone_size;
747
748         if (zone_capacity > zone_size) {
749                 log_err("%s: job parameter zonecapacity %llu is larger than zone size %llu\n",
750                         f->file_name, td->o.zone_capacity, td->o.zone_size);
751                 return 1;
752         }
753
754         if (f->real_file_size < zone_size) {
755                 log_err("%s: file/device size %"PRIu64" is smaller than zone size %"PRIu64"\n",
756                         f->file_name, f->real_file_size, zone_size);
757                 return -EINVAL;
758         }
759
760         nr_zones = (f->real_file_size + zone_size - 1) / zone_size;
761         zbd_info = scalloc(1, sizeof(*zbd_info) +
762                            (nr_zones + 1) * sizeof(zbd_info->zone_info[0]));
763         if (!zbd_info)
764                 return -ENOMEM;
765
766         mutex_init_pshared(&zbd_info->mutex);
767         zbd_info->refcount = 1;
768         p = &zbd_info->zone_info[0];
769         for (i = 0; i < nr_zones; i++, p++) {
770                 mutex_init_pshared_with_type(&p->mutex,
771                                              PTHREAD_MUTEX_RECURSIVE);
772                 p->start = i * zone_size;
773                 p->wp = p->start;
774                 p->type = ZBD_ZONE_TYPE_SWR;
775                 p->cond = ZBD_ZONE_COND_EMPTY;
776                 p->capacity = zone_capacity;
777                 p->has_wp = 1;
778         }
779         /* a sentinel */
780         p->start = nr_zones * zone_size;
781
782         f->zbd_info = zbd_info;
783         f->zbd_info->zone_size = zone_size;
784         f->zbd_info->zone_size_log2 = is_power_of_2(zone_size) ?
785                 ilog2(zone_size) : 0;
786         f->zbd_info->nr_zones = nr_zones;
787         return 0;
788 }
789
790 /*
791  * Maximum number of zones to report in one operation.
792  */
793 #define ZBD_REPORT_MAX_ZONES    8192U
794
795 /*
796  * Parse the device zone report and store it in f->zbd_info. Must be called
797  * only for devices that are zoned, namely those with a model != ZBD_NONE.
798  */
799 static int parse_zone_info(struct thread_data *td, struct fio_file *f)
800 {
801         int nr_zones, nrz;
802         struct zbd_zone *zones, *z;
803         struct fio_zone_info *p;
804         uint64_t zone_size, offset, capacity;
805         bool same_zone_cap = true;
806         struct zoned_block_device_info *zbd_info = NULL;
807         int i, j, ret = -ENOMEM;
808
809         zones = calloc(ZBD_REPORT_MAX_ZONES, sizeof(struct zbd_zone));
810         if (!zones)
811                 goto out;
812
813         nrz = zbd_report_zones(td, f, 0, zones, ZBD_REPORT_MAX_ZONES);
814         if (nrz < 0) {
815                 ret = nrz;
816                 log_info("fio: report zones (offset 0) failed for %s (%d).\n",
817                          f->file_name, -ret);
818                 goto out;
819         }
820
821         zone_size = zones[0].len;
822         capacity = zones[0].capacity;
823         nr_zones = (f->real_file_size + zone_size - 1) / zone_size;
824
825         if (td->o.zone_size == 0) {
826                 td->o.zone_size = zone_size;
827         } else if (td->o.zone_size != zone_size) {
828                 log_err("fio: %s job parameter zonesize %llu does not match disk zone size %"PRIu64".\n",
829                         f->file_name, td->o.zone_size, zone_size);
830                 ret = -EINVAL;
831                 goto out;
832         }
833
834         dprint(FD_ZBD, "Device %s has %d zones of size %"PRIu64" KB\n",
835                f->file_name, nr_zones, zone_size / 1024);
836
837         zbd_info = scalloc(1, sizeof(*zbd_info) +
838                            (nr_zones + 1) * sizeof(zbd_info->zone_info[0]));
839         if (!zbd_info)
840                 goto out;
841         mutex_init_pshared(&zbd_info->mutex);
842         zbd_info->refcount = 1;
843         p = &zbd_info->zone_info[0];
844         for (offset = 0, j = 0; j < nr_zones;) {
845                 z = &zones[0];
846                 for (i = 0; i < nrz; i++, j++, z++, p++) {
847                         mutex_init_pshared_with_type(&p->mutex,
848                                                      PTHREAD_MUTEX_RECURSIVE);
849                         p->start = z->start;
850                         p->capacity = z->capacity;
851                         if (capacity != z->capacity)
852                                 same_zone_cap = false;
853
854                         switch (z->cond) {
855                         case ZBD_ZONE_COND_NOT_WP:
856                         case ZBD_ZONE_COND_FULL:
857                                 p->wp = p->start + p->capacity;
858                                 break;
859                         default:
860                                 assert(z->start <= z->wp);
861                                 assert(z->wp <= z->start + zone_size);
862                                 p->wp = z->wp;
863                                 break;
864                         }
865
866                         switch (z->type) {
867                         case ZBD_ZONE_TYPE_SWR:
868                                 p->has_wp = 1;
869                                 break;
870                         default:
871                                 p->has_wp = 0;
872                         }
873                         p->type = z->type;
874                         p->cond = z->cond;
875
876                         if (j > 0 && p->start != p[-1].start + zone_size) {
877                                 log_info("%s: invalid zone data [%d:%d]: %"PRIu64" + %"PRIu64" != %"PRIu64"\n",
878                                          f->file_name, j, i,
879                                          p[-1].start, zone_size, p->start);
880                                 ret = -EINVAL;
881                                 goto out;
882                         }
883                 }
884                 z--;
885                 offset = z->start + z->len;
886                 if (j >= nr_zones)
887                         break;
888
889                 nrz = zbd_report_zones(td, f, offset, zones,
890                                        min((uint32_t)(nr_zones - j),
891                                            ZBD_REPORT_MAX_ZONES));
892                 if (nrz < 0) {
893                         ret = nrz;
894                         log_info("fio: report zones (offset %"PRIu64") failed for %s (%d).\n",
895                                  offset, f->file_name, -ret);
896                         goto out;
897                 }
898         }
899
900         /* a sentinel */
901         zbd_info->zone_info[nr_zones].start = offset;
902
903         f->zbd_info = zbd_info;
904         f->zbd_info->zone_size = zone_size;
905         f->zbd_info->zone_size_log2 = is_power_of_2(zone_size) ?
906                 ilog2(zone_size) : 0;
907         f->zbd_info->nr_zones = nr_zones;
908
909         if (same_zone_cap)
910                 dprint(FD_ZBD, "Zone capacity = %"PRIu64" KB\n",
911                        capacity / 1024);
912
913         zbd_info = NULL;
914         ret = 0;
915
916 out:
917         sfree(zbd_info);
918         free(zones);
919         return ret;
920 }
921
922 static int zbd_set_max_write_zones(struct thread_data *td, struct fio_file *f)
923 {
924         struct zoned_block_device_info *zbd = f->zbd_info;
925         unsigned int max_open_zones;
926         int ret;
927
928         if (zbd->model != ZBD_HOST_MANAGED || td->o.ignore_zone_limits) {
929                 /* Only host-managed devices have a max open limit */
930                 zbd->max_write_zones = td->o.max_open_zones;
931                 goto out;
932         }
933
934         /* If host-managed, get the max open limit */
935         ret = zbd_get_max_open_zones(td, f, &max_open_zones);
936         if (ret)
937                 return ret;
938
939         if (!max_open_zones) {
940                 /* No device limit */
941                 zbd->max_write_zones = td->o.max_open_zones;
942         } else if (!td->o.max_open_zones) {
943                 /* No user limit. Set limit to device limit */
944                 zbd->max_write_zones = max_open_zones;
945         } else if (td->o.max_open_zones <= max_open_zones) {
946                 /* Both user limit and dev limit. User limit not too large */
947                 zbd->max_write_zones = td->o.max_open_zones;
948         } else {
949                 /* Both user limit and dev limit. User limit too large */
950                 td_verror(td, EINVAL,
951                           "Specified --max_open_zones is too large");
952                 log_err("Specified --max_open_zones (%d) is larger than max (%u)\n",
953                         td->o.max_open_zones, max_open_zones);
954                 return -EINVAL;
955         }
956
957 out:
958         /* Ensure that the limit is not larger than FIO's internal limit */
959         if (zbd->max_write_zones > ZBD_MAX_WRITE_ZONES) {
960                 td_verror(td, EINVAL, "'max_open_zones' value is too large");
961                 log_err("'max_open_zones' value is larger than %u\n",
962                         ZBD_MAX_WRITE_ZONES);
963                 return -EINVAL;
964         }
965
966         dprint(FD_ZBD, "%s: using max write zones limit: %"PRIu32"\n",
967                f->file_name, zbd->max_write_zones);
968
969         return 0;
970 }
971
972 /*
973  * Allocate zone information and store it into f->zbd_info if zonemode=zbd.
974  *
975  * Returns 0 upon success and a negative error code upon failure.
976  */
977 static int zbd_create_zone_info(struct thread_data *td, struct fio_file *f)
978 {
979         enum zbd_zoned_model zbd_model;
980         int ret;
981
982         assert(td->o.zone_mode == ZONE_MODE_ZBD);
983
984         ret = zbd_get_zoned_model(td, f, &zbd_model);
985         if (ret)
986                 return ret;
987
988         switch (zbd_model) {
989         case ZBD_HOST_AWARE:
990         case ZBD_HOST_MANAGED:
991                 ret = parse_zone_info(td, f);
992                 if (ret)
993                         return ret;
994                 break;
995         case ZBD_NONE:
996                 ret = init_zone_info(td, f);
997                 if (ret)
998                         return ret;
999                 break;
1000         default:
1001                 td_verror(td, EINVAL, "Unsupported zoned model");
1002                 log_err("Unsupported zoned model\n");
1003                 return -EINVAL;
1004         }
1005
1006         assert(f->zbd_info);
1007         f->zbd_info->model = zbd_model;
1008
1009         ret = zbd_set_max_write_zones(td, f);
1010         if (ret) {
1011                 zbd_free_zone_info(f);
1012                 return ret;
1013         }
1014
1015         return 0;
1016 }
1017
1018 void zbd_free_zone_info(struct fio_file *f)
1019 {
1020         uint32_t refcount;
1021
1022         assert(f->zbd_info);
1023
1024         pthread_mutex_lock(&f->zbd_info->mutex);
1025         refcount = --f->zbd_info->refcount;
1026         pthread_mutex_unlock(&f->zbd_info->mutex);
1027
1028         assert((int32_t)refcount >= 0);
1029         if (refcount == 0)
1030                 sfree(f->zbd_info);
1031         f->zbd_info = NULL;
1032 }
1033
1034 /*
1035  * Initialize f->zbd_info.
1036  *
1037  * Returns 0 upon success and a negative error code upon failure.
1038  *
1039  * Note: this function can only work correctly if it is called before the first
1040  * fio fork() call.
1041  */
1042 static int zbd_init_zone_info(struct thread_data *td, struct fio_file *file)
1043 {
1044         struct fio_file *f2;
1045         int j, ret;
1046
1047         for_each_td(td2) {
1048                 for_each_file(td2, f2, j) {
1049                         if (td2 == td && f2 == file)
1050                                 continue;
1051                         if (!f2->zbd_info ||
1052                             strcmp(f2->file_name, file->file_name) != 0)
1053                                 continue;
1054                         file->zbd_info = f2->zbd_info;
1055                         file->zbd_info->refcount++;
1056                         return 0;
1057                 }
1058         } end_for_each();
1059
1060         ret = zbd_create_zone_info(td, file);
1061         if (ret < 0)
1062                 td_verror(td, -ret, "zbd_create_zone_info() failed");
1063
1064         return ret;
1065 }
1066
1067 int zbd_init_files(struct thread_data *td)
1068 {
1069         struct fio_file *f;
1070         int i;
1071
1072         for_each_file(td, f, i) {
1073                 if (zbd_init_zone_info(td, f))
1074                         return 1;
1075         }
1076
1077         return 0;
1078 }
1079
1080 void zbd_recalc_options_with_zone_granularity(struct thread_data *td)
1081 {
1082         struct fio_file *f;
1083         int i;
1084
1085         for_each_file(td, f, i) {
1086                 struct zoned_block_device_info *zbd = f->zbd_info;
1087                 uint64_t zone_size;
1088
1089                 /* zonemode=strided doesn't get per-file zone size. */
1090                 zone_size = zbd ? zbd->zone_size : td->o.zone_size;
1091                 if (zone_size == 0)
1092                         continue;
1093
1094                 if (td->o.size_nz > 0)
1095                         td->o.size = td->o.size_nz * zone_size;
1096                 if (td->o.io_size_nz > 0)
1097                         td->o.io_size = td->o.io_size_nz * zone_size;
1098                 if (td->o.start_offset_nz > 0)
1099                         td->o.start_offset = td->o.start_offset_nz * zone_size;
1100                 if (td->o.offset_increment_nz > 0)
1101                         td->o.offset_increment =
1102                                 td->o.offset_increment_nz * zone_size;
1103                 if (td->o.zone_skip_nz > 0)
1104                         td->o.zone_skip = td->o.zone_skip_nz * zone_size;
1105         }
1106 }
1107
1108 static uint64_t zbd_verify_and_set_vdb(struct thread_data *td,
1109                                        const struct fio_file *f)
1110 {
1111         struct fio_zone_info *zb, *ze, *z;
1112         uint64_t wp_vdb = 0;
1113         struct zoned_block_device_info *zbdi = f->zbd_info;
1114
1115         assert(td->runstate < TD_RUNNING);
1116         assert(zbdi);
1117
1118         if (!accounting_vdb(td, f))
1119                 return 0;
1120
1121         /*
1122          * Ensure that the I/O range includes one or more sequential zones so
1123          * that f->min_zone and f->max_zone have different values.
1124          */
1125         if (!zbd_is_seq_job(f))
1126                 return 0;
1127
1128         if (zbdi->write_min_zone != zbdi->write_max_zone) {
1129                 if (zbdi->write_min_zone != f->min_zone ||
1130                     zbdi->write_max_zone != f->max_zone) {
1131                         td_verror(td, EINVAL,
1132                                   "multi-jobs with different write ranges are "
1133                                   "not supported with zone_reset_threshold");
1134                         log_err("multi-jobs with different write ranges are "
1135                                 "not supported with zone_reset_threshold\n");
1136                 }
1137                 return 0;
1138         }
1139
1140         zbdi->write_min_zone = f->min_zone;
1141         zbdi->write_max_zone = f->max_zone;
1142
1143         zb = zbd_get_zone(f, f->min_zone);
1144         ze = zbd_get_zone(f, f->max_zone);
1145         for (z = zb; z < ze; z++)
1146                 if (z->has_wp)
1147                         wp_vdb += z->wp - z->start;
1148
1149         zbdi->wp_valid_data_bytes = wp_vdb;
1150
1151         return wp_vdb;
1152 }
1153
1154 int zbd_setup_files(struct thread_data *td)
1155 {
1156         struct fio_file *f;
1157         int i;
1158
1159         if (!zbd_using_direct_io()) {
1160                 log_err("Using direct I/O is mandatory for writing to ZBD drives\n\n");
1161                 return 1;
1162         }
1163
1164         if (!zbd_verify_sizes())
1165                 return 1;
1166
1167         if (!zbd_verify_bs())
1168                 return 1;
1169
1170         if (td->o.experimental_verify) {
1171                 log_err("zonemode=zbd does not support experimental verify\n");
1172                 return 1;
1173         }
1174
1175         for_each_file(td, f, i) {
1176                 struct zoned_block_device_info *zbd = f->zbd_info;
1177                 struct fio_zone_info *z;
1178                 int zi;
1179                 uint64_t vdb;
1180
1181                 assert(zbd);
1182
1183                 f->min_zone = zbd_offset_to_zone_idx(f, f->file_offset);
1184                 f->max_zone =
1185                         zbd_offset_to_zone_idx(f, f->file_offset + f->io_size);
1186
1187                 vdb = zbd_verify_and_set_vdb(td, f);
1188
1189                 dprint(FD_ZBD, "%s(%s): valid data bytes = %" PRIu64 "\n",
1190                        __func__, f->file_name, vdb);
1191
1192                 /*
1193                  * When all zones in the I/O range are conventional, io_size
1194                  * can be smaller than zone size, making min_zone the same
1195                  * as max_zone. This is why the assert below needs to be made
1196                  * conditional.
1197                  */
1198                 if (zbd_is_seq_job(f))
1199                         assert(f->min_zone < f->max_zone);
1200
1201                 if (td->o.max_open_zones > 0 &&
1202                     zbd->max_write_zones != td->o.max_open_zones) {
1203                         log_err("Different 'max_open_zones' values\n");
1204                         return 1;
1205                 }
1206
1207                 /*
1208                  * The per job max open zones limit cannot be used without a
1209                  * global max open zones limit. (As the tracking of open zones
1210                  * is disabled when there is no global max open zones limit.)
1211                  */
1212                 if (td->o.job_max_open_zones && !zbd->max_write_zones) {
1213                         log_err("'job_max_open_zones' cannot be used without a global open zones limit\n");
1214                         return 1;
1215                 }
1216
1217                 /*
1218                  * zbd->max_write_zones is the global limit shared for all jobs
1219                  * that target the same zoned block device. Force sync the per
1220                  * thread global limit with the actual global limit. (The real
1221                  * per thread/job limit is stored in td->o.job_max_open_zones).
1222                  */
1223                 td->o.max_open_zones = zbd->max_write_zones;
1224
1225                 for (zi = f->min_zone; zi < f->max_zone; zi++) {
1226                         z = &zbd->zone_info[zi];
1227                         if (z->cond != ZBD_ZONE_COND_IMP_OPEN &&
1228                             z->cond != ZBD_ZONE_COND_EXP_OPEN)
1229                                 continue;
1230                         if (__zbd_write_zone_get(td, f, z))
1231                                 continue;
1232                         /*
1233                          * If the number of open zones exceeds specified limits,
1234                          * error out.
1235                          */
1236                         log_err("Number of open zones exceeds max_open_zones limit\n");
1237                         return 1;
1238                 }
1239         }
1240
1241         return 0;
1242 }
1243
1244 /*
1245  * Reset zbd_info.write_cnt, the counter that counts down towards the next
1246  * zone reset.
1247  */
1248 static void _zbd_reset_write_cnt(const struct thread_data *td,
1249                                  const struct fio_file *f)
1250 {
1251         assert(0 <= td->o.zrf.u.f && td->o.zrf.u.f <= 1);
1252
1253         f->zbd_info->write_cnt = td->o.zrf.u.f ?
1254                 min(1.0 / td->o.zrf.u.f, 0.0 + UINT_MAX) : UINT_MAX;
1255 }
1256
1257 static void zbd_reset_write_cnt(const struct thread_data *td,
1258                                 const struct fio_file *f)
1259 {
1260         pthread_mutex_lock(&f->zbd_info->mutex);
1261         _zbd_reset_write_cnt(td, f);
1262         pthread_mutex_unlock(&f->zbd_info->mutex);
1263 }
1264
1265 static bool zbd_dec_and_reset_write_cnt(const struct thread_data *td,
1266                                         const struct fio_file *f)
1267 {
1268         uint32_t write_cnt = 0;
1269
1270         pthread_mutex_lock(&f->zbd_info->mutex);
1271         assert(f->zbd_info->write_cnt);
1272         if (f->zbd_info->write_cnt)
1273                 write_cnt = --f->zbd_info->write_cnt;
1274         if (write_cnt == 0)
1275                 _zbd_reset_write_cnt(td, f);
1276         pthread_mutex_unlock(&f->zbd_info->mutex);
1277
1278         return write_cnt == 0;
1279 }
1280
1281 void zbd_file_reset(struct thread_data *td, struct fio_file *f)
1282 {
1283         struct fio_zone_info *zb, *ze;
1284         bool verify_data_left = false;
1285
1286         if (!f->zbd_info || !td_write(td))
1287                 return;
1288
1289         zb = zbd_get_zone(f, f->min_zone);
1290         ze = zbd_get_zone(f, f->max_zone);
1291
1292         /*
1293          * If data verification is enabled reset the affected zones before
1294          * writing any data to avoid that a zone reset has to be issued while
1295          * writing data, which causes data loss.
1296          */
1297         if (td->o.verify != VERIFY_NONE) {
1298                 verify_data_left = td->runstate == TD_VERIFYING ||
1299                         td->io_hist_len || td->verify_batch;
1300                 if (td->io_hist_len && td->o.verify_backlog)
1301                         verify_data_left =
1302                                 td->io_hist_len % td->o.verify_backlog;
1303                 if (!verify_data_left)
1304                         zbd_reset_zones(td, f, zb, ze);
1305         }
1306
1307         zbd_reset_write_cnt(td, f);
1308 }
1309
1310 /* Return random zone index for one of the write target zones. */
1311 static uint32_t pick_random_zone_idx(const struct fio_file *f,
1312                                      const struct io_u *io_u)
1313 {
1314         return (io_u->offset - f->file_offset) *
1315                 f->zbd_info->num_write_zones / f->io_size;
1316 }
1317
1318 static bool any_io_in_flight(void)
1319 {
1320         for_each_td(td) {
1321                 if (td->io_u_in_flight)
1322                         return true;
1323         } end_for_each();
1324
1325         return false;
1326 }
1327
1328 /*
1329  * Modify the offset of an I/O unit that does not refer to a zone such that
1330  * in write target zones array. Add a zone to or remove a zone from the lsit if
1331  * necessary. The write target zone is searched across sequential zones.
1332  * This algorithm can only work correctly if all write pointers are
1333  * a multiple of the fio block size. The caller must neither hold z->mutex
1334  * nor f->zbd_info->mutex. Returns with z->mutex held upon success.
1335  */
1336 static struct fio_zone_info *zbd_convert_to_write_zone(struct thread_data *td,
1337                                                        struct io_u *io_u)
1338 {
1339         const uint64_t min_bs = td->o.min_bs[io_u->ddir];
1340         struct fio_file *f = io_u->file;
1341         struct zoned_block_device_info *zbdi = f->zbd_info;
1342         struct fio_zone_info *z;
1343         unsigned int write_zone_idx = -1;
1344         uint32_t zone_idx, new_zone_idx;
1345         int i;
1346         bool wait_zone_write;
1347         bool in_flight;
1348         bool should_retry = true;
1349
1350         assert(is_valid_offset(f, io_u->offset));
1351
1352         if (zbdi->max_write_zones || td->o.job_max_open_zones) {
1353                 /*
1354                  * This statement accesses zbdi->write_zones[] on purpose
1355                  * without locking.
1356                  */
1357                 zone_idx = zbdi->write_zones[pick_random_zone_idx(f, io_u)];
1358         } else {
1359                 zone_idx = zbd_offset_to_zone_idx(f, io_u->offset);
1360         }
1361         if (zone_idx < f->min_zone)
1362                 zone_idx = f->min_zone;
1363         else if (zone_idx >= f->max_zone)
1364                 zone_idx = f->max_zone - 1;
1365
1366         dprint(FD_ZBD,
1367                "%s(%s): starting from zone %d (offset %lld, buflen %lld)\n",
1368                __func__, f->file_name, zone_idx, io_u->offset, io_u->buflen);
1369
1370         /*
1371          * Since z->mutex is the outer lock and zbdi->mutex the inner
1372          * lock it can happen that the state of the zone with index zone_idx
1373          * has changed after 'z' has been assigned and before zbdi->mutex
1374          * has been obtained. Hence the loop.
1375          */
1376         for (;;) {
1377                 uint32_t tmp_idx;
1378
1379                 z = zbd_get_zone(f, zone_idx);
1380                 if (z->has_wp)
1381                         zone_lock(td, f, z);
1382
1383                 pthread_mutex_lock(&zbdi->mutex);
1384
1385                 if (z->has_wp) {
1386                         if (z->cond != ZBD_ZONE_COND_OFFLINE &&
1387                             zbdi->max_write_zones == 0 &&
1388                             td->o.job_max_open_zones == 0)
1389                                 goto examine_zone;
1390                         if (zbdi->num_write_zones == 0) {
1391                                 dprint(FD_ZBD, "%s(%s): no zone is write target\n",
1392                                        __func__, f->file_name);
1393                                 goto choose_other_zone;
1394                         }
1395                 }
1396
1397                 /*
1398                  * Array of write target zones is per-device, shared across all
1399                  * threads. Start with quasi-random candidate zone. Ignore
1400                  * zones which don't belong to thread's offset/size area.
1401                  */
1402                 write_zone_idx = pick_random_zone_idx(f, io_u);
1403                 assert(!write_zone_idx ||
1404                        write_zone_idx < zbdi->num_write_zones);
1405                 tmp_idx = write_zone_idx;
1406
1407                 for (i = 0; i < zbdi->num_write_zones; i++) {
1408                         uint32_t tmpz;
1409
1410                         if (tmp_idx >= zbdi->num_write_zones)
1411                                 tmp_idx = 0;
1412                         tmpz = zbdi->write_zones[tmp_idx];
1413                         if (f->min_zone <= tmpz && tmpz < f->max_zone) {
1414                                 write_zone_idx = tmp_idx;
1415                                 goto found_candidate_zone;
1416                         }
1417
1418                         tmp_idx++;
1419                 }
1420
1421                 dprint(FD_ZBD, "%s(%s): no candidate zone\n",
1422                         __func__, f->file_name);
1423
1424                 pthread_mutex_unlock(&zbdi->mutex);
1425
1426                 if (z->has_wp)
1427                         zone_unlock(z);
1428
1429                 return NULL;
1430
1431 found_candidate_zone:
1432                 new_zone_idx = zbdi->write_zones[write_zone_idx];
1433                 if (new_zone_idx == zone_idx)
1434                         break;
1435                 zone_idx = new_zone_idx;
1436
1437                 pthread_mutex_unlock(&zbdi->mutex);
1438
1439                 if (z->has_wp)
1440                         zone_unlock(z);
1441         }
1442
1443         /* Both z->mutex and zbdi->mutex are held. */
1444
1445 examine_zone:
1446         if (zbd_zone_remainder(z) >= min_bs) {
1447                 pthread_mutex_unlock(&zbdi->mutex);
1448                 goto out;
1449         }
1450
1451 choose_other_zone:
1452         /* Check if number of write target zones reaches one of limits. */
1453         wait_zone_write =
1454                 zbdi->num_write_zones == f->max_zone - f->min_zone ||
1455                 (zbdi->max_write_zones &&
1456                  zbdi->num_write_zones == zbdi->max_write_zones) ||
1457                 (td->o.job_max_open_zones &&
1458                  td->num_write_zones == td->o.job_max_open_zones);
1459
1460         pthread_mutex_unlock(&zbdi->mutex);
1461
1462         /* Only z->mutex is held. */
1463
1464         /*
1465          * When number of write target zones reaches to one of limits, wait for
1466          * zone write completion to one of them before trying a new zone.
1467          */
1468         if (wait_zone_write) {
1469                 dprint(FD_ZBD,
1470                        "%s(%s): quiesce to remove a zone from write target zones array\n",
1471                        __func__, f->file_name);
1472                 io_u_quiesce(td);
1473         }
1474
1475 retry:
1476         /* Zone 'z' is full, so try to choose a new zone. */
1477         for (i = f->io_size / zbdi->zone_size; i > 0; i--) {
1478                 zone_idx++;
1479                 if (z->has_wp)
1480                         zone_unlock(z);
1481                 z++;
1482                 if (!is_valid_offset(f, z->start)) {
1483                         /* Wrap-around. */
1484                         zone_idx = f->min_zone;
1485                         z = zbd_get_zone(f, zone_idx);
1486                 }
1487                 assert(is_valid_offset(f, z->start));
1488                 if (!z->has_wp)
1489                         continue;
1490                 zone_lock(td, f, z);
1491                 if (z->write)
1492                         continue;
1493                 if (zbd_write_zone_get(td, f, z))
1494                         goto out;
1495         }
1496
1497         /* Only z->mutex is held. */
1498
1499         /* Check whether the write fits in any of the write target zones. */
1500         pthread_mutex_lock(&zbdi->mutex);
1501         for (i = 0; i < zbdi->num_write_zones; i++) {
1502                 zone_idx = zbdi->write_zones[i];
1503                 if (zone_idx < f->min_zone || zone_idx >= f->max_zone)
1504                         continue;
1505                 pthread_mutex_unlock(&zbdi->mutex);
1506                 zone_unlock(z);
1507
1508                 z = zbd_get_zone(f, zone_idx);
1509
1510                 zone_lock(td, f, z);
1511                 if (zbd_zone_remainder(z) >= min_bs)
1512                         goto out;
1513                 pthread_mutex_lock(&zbdi->mutex);
1514         }
1515
1516         /*
1517          * When any I/O is in-flight or when all I/Os in-flight get completed,
1518          * the I/Os might have removed zones from the write target array then
1519          * retry the steps to choose a zone. Before retry, call io_u_quiesce()
1520          * to complete in-flight writes.
1521          */
1522         in_flight = any_io_in_flight();
1523         if (in_flight || should_retry) {
1524                 dprint(FD_ZBD,
1525                        "%s(%s): wait zone write and retry write target zone selection\n",
1526                        __func__, f->file_name);
1527                 pthread_mutex_unlock(&zbdi->mutex);
1528                 zone_unlock(z);
1529                 io_u_quiesce(td);
1530                 zone_lock(td, f, z);
1531                 should_retry = in_flight;
1532                 goto retry;
1533         }
1534
1535         pthread_mutex_unlock(&zbdi->mutex);
1536
1537         zone_unlock(z);
1538
1539         dprint(FD_ZBD, "%s(%s): did not choose another write zone\n",
1540                __func__, f->file_name);
1541
1542         return NULL;
1543
1544 out:
1545         dprint(FD_ZBD, "%s(%s): returning zone %d\n",
1546                __func__, f->file_name, zone_idx);
1547
1548         io_u->offset = z->start;
1549         assert(z->has_wp);
1550         assert(z->cond != ZBD_ZONE_COND_OFFLINE);
1551
1552         return z;
1553 }
1554
1555 /*
1556  * Find another zone which has @min_bytes of readable data. Search in zones
1557  * @zb + 1 .. @zl. For random workload, also search in zones @zb - 1 .. @zf.
1558  *
1559  * Either returns NULL or returns a zone pointer. When the zone has write
1560  * pointer, hold the mutex for the zone.
1561  */
1562 static struct fio_zone_info *
1563 zbd_find_zone(struct thread_data *td, struct io_u *io_u, uint64_t min_bytes,
1564               struct fio_zone_info *zb, struct fio_zone_info *zl)
1565 {
1566         struct fio_file *f = io_u->file;
1567         struct fio_zone_info *z1, *z2;
1568         const struct fio_zone_info *const zf = zbd_get_zone(f, f->min_zone);
1569
1570         /*
1571          * Skip to the next non-empty zone in case of sequential I/O and to
1572          * the nearest non-empty zone in case of random I/O.
1573          */
1574         for (z1 = zb + 1, z2 = zb - 1; z1 < zl || z2 >= zf; z1++, z2--) {
1575                 if (z1 < zl && z1->cond != ZBD_ZONE_COND_OFFLINE) {
1576                         if (z1->has_wp)
1577                                 zone_lock(td, f, z1);
1578                         if (z1->start + min_bytes <= z1->wp)
1579                                 return z1;
1580                         if (z1->has_wp)
1581                                 zone_unlock(z1);
1582                 } else if (!td_random(td)) {
1583                         break;
1584                 }
1585
1586                 if (td_random(td) && z2 >= zf &&
1587                     z2->cond != ZBD_ZONE_COND_OFFLINE) {
1588                         if (z2->has_wp)
1589                                 zone_lock(td, f, z2);
1590                         if (z2->start + min_bytes <= z2->wp)
1591                                 return z2;
1592                         if (z2->has_wp)
1593                                 zone_unlock(z2);
1594                 }
1595         }
1596
1597         dprint(FD_ZBD,
1598                "%s: no zone has %"PRIu64" bytes of readable data\n",
1599                f->file_name, min_bytes);
1600
1601         return NULL;
1602 }
1603
1604 /**
1605  * zbd_end_zone_io - update zone status at command completion
1606  * @io_u: I/O unit
1607  * @z: zone info pointer
1608  *
1609  * If the write command made the zone full, remove it from the write target
1610  * zones array.
1611  *
1612  * The caller must hold z->mutex.
1613  */
1614 static void zbd_end_zone_io(struct thread_data *td, const struct io_u *io_u,
1615                             struct fio_zone_info *z)
1616 {
1617         const struct fio_file *f = io_u->file;
1618
1619         if (io_u->ddir == DDIR_WRITE &&
1620             io_u->offset + io_u->buflen >= zbd_zone_capacity_end(z)) {
1621                 pthread_mutex_lock(&f->zbd_info->mutex);
1622                 zbd_write_zone_put(td, f, z);
1623                 pthread_mutex_unlock(&f->zbd_info->mutex);
1624         }
1625 }
1626
1627 /**
1628  * zbd_queue_io - update the write pointer of a sequential zone
1629  * @io_u: I/O unit
1630  * @success: Whether or not the I/O unit has been queued successfully
1631  * @q: queueing status (busy, completed or queued).
1632  *
1633  * For write and trim operations, update the write pointer of the I/O unit
1634  * target zone.
1635  */
1636 static void zbd_queue_io(struct thread_data *td, struct io_u *io_u, int q,
1637                          bool success)
1638 {
1639         const struct fio_file *f = io_u->file;
1640         struct zoned_block_device_info *zbd_info = f->zbd_info;
1641         struct fio_zone_info *z;
1642         uint64_t zone_end;
1643
1644         assert(zbd_info);
1645
1646         z = zbd_offset_to_zone(f, io_u->offset);
1647         assert(z->has_wp);
1648
1649         if (!success)
1650                 goto unlock;
1651
1652         dprint(FD_ZBD,
1653                "%s: queued I/O (%lld, %llu) for zone %u\n",
1654                f->file_name, io_u->offset, io_u->buflen, zbd_zone_idx(f, z));
1655
1656         switch (io_u->ddir) {
1657         case DDIR_WRITE:
1658                 zone_end = min((uint64_t)(io_u->offset + io_u->buflen),
1659                                zbd_zone_capacity_end(z));
1660
1661                 /*
1662                  * z->wp > zone_end means that one or more I/O errors
1663                  * have occurred.
1664                  */
1665                 if (accounting_vdb(td, f) && z->wp <= zone_end) {
1666                         pthread_mutex_lock(&zbd_info->mutex);
1667                         zbd_info->wp_valid_data_bytes += zone_end - z->wp;
1668                         pthread_mutex_unlock(&zbd_info->mutex);
1669                 }
1670                 z->wp = zone_end;
1671                 break;
1672         default:
1673                 break;
1674         }
1675
1676         if (q == FIO_Q_COMPLETED && !io_u->error)
1677                 zbd_end_zone_io(td, io_u, z);
1678
1679 unlock:
1680         if (!success || q != FIO_Q_QUEUED) {
1681                 /* BUSY or COMPLETED: unlock the zone */
1682                 zone_unlock(z);
1683                 io_u->zbd_put_io = NULL;
1684         }
1685 }
1686
1687 /**
1688  * zbd_put_io - Unlock an I/O unit target zone lock
1689  * @io_u: I/O unit
1690  */
1691 static void zbd_put_io(struct thread_data *td, const struct io_u *io_u)
1692 {
1693         const struct fio_file *f = io_u->file;
1694         struct zoned_block_device_info *zbd_info = f->zbd_info;
1695         struct fio_zone_info *z;
1696
1697         assert(zbd_info);
1698
1699         z = zbd_offset_to_zone(f, io_u->offset);
1700         assert(z->has_wp);
1701
1702         dprint(FD_ZBD,
1703                "%s: terminate I/O (%lld, %llu) for zone %u\n",
1704                f->file_name, io_u->offset, io_u->buflen, zbd_zone_idx(f, z));
1705
1706         zbd_end_zone_io(td, io_u, z);
1707
1708         zone_unlock(z);
1709 }
1710
1711 /*
1712  * Windows and MacOS do not define this.
1713  */
1714 #ifndef EREMOTEIO
1715 #define EREMOTEIO       121     /* POSIX value */
1716 #endif
1717
1718 bool zbd_unaligned_write(int error_code)
1719 {
1720         switch (error_code) {
1721         case EIO:
1722         case EREMOTEIO:
1723                 return true;
1724         }
1725         return false;
1726 }
1727
1728 /**
1729  * setup_zbd_zone_mode - handle zoneskip as necessary for ZBD drives
1730  * @td: FIO thread data.
1731  * @io_u: FIO I/O unit.
1732  *
1733  * For sequential workloads, change the file offset to skip zoneskip bytes when
1734  * no more IO can be performed in the current zone.
1735  * - For read workloads, zoneskip is applied when the io has reached the end of
1736  *   the zone or the zone write position (when td->o.read_beyond_wp is false).
1737  * - For write workloads, zoneskip is applied when the zone is full.
1738  * This applies only to read and write operations.
1739  */
1740 void setup_zbd_zone_mode(struct thread_data *td, struct io_u *io_u)
1741 {
1742         struct fio_file *f = io_u->file;
1743         enum fio_ddir ddir = io_u->ddir;
1744         struct fio_zone_info *z;
1745
1746         assert(td->o.zone_mode == ZONE_MODE_ZBD);
1747         assert(td->o.zone_size);
1748         assert(f->zbd_info);
1749
1750         z = zbd_offset_to_zone(f, f->last_pos[ddir]);
1751
1752         /*
1753          * When the zone capacity is smaller than the zone size and the I/O is
1754          * sequential write, skip to zone end if the latest position is at the
1755          * zone capacity limit.
1756          */
1757         if (z->capacity < f->zbd_info->zone_size &&
1758             !td_random(td) && ddir == DDIR_WRITE &&
1759             f->last_pos[ddir] >= zbd_zone_capacity_end(z)) {
1760                 dprint(FD_ZBD,
1761                        "%s: Jump from zone capacity limit to zone end:"
1762                        " (%"PRIu64" -> %"PRIu64") for zone %u (%"PRIu64")\n",
1763                        f->file_name, f->last_pos[ddir],
1764                        zbd_zone_end(z), zbd_zone_idx(f, z), z->capacity);
1765                 td->io_skip_bytes += zbd_zone_end(z) - f->last_pos[ddir];
1766                 f->last_pos[ddir] = zbd_zone_end(z);
1767         }
1768
1769         /*
1770          * zone_skip is valid only for sequential workloads.
1771          */
1772         if (td_random(td) || !td->o.zone_skip)
1773                 return;
1774
1775         /*
1776          * It is time to switch to a new zone if:
1777          * - zone_bytes == zone_size bytes have already been accessed
1778          * - The last position reached the end of the current zone.
1779          * - For reads with td->o.read_beyond_wp == false, the last position
1780          *   reached the zone write pointer.
1781          */
1782         if (td->zone_bytes >= td->o.zone_size ||
1783             f->last_pos[ddir] >= zbd_zone_end(z) ||
1784             (ddir == DDIR_READ &&
1785              (!td->o.read_beyond_wp) && f->last_pos[ddir] >= z->wp)) {
1786                 /*
1787                  * Skip zones.
1788                  */
1789                 td->zone_bytes = 0;
1790                 f->file_offset += td->o.zone_size + td->o.zone_skip;
1791
1792                 /*
1793                  * Wrap from the beginning, if we exceed the file size
1794                  */
1795                 if (f->file_offset >= f->real_file_size)
1796                         f->file_offset = get_start_offset(td, f);
1797
1798                 f->last_pos[ddir] = f->file_offset;
1799                 td->io_skip_bytes += td->o.zone_skip;
1800         }
1801 }
1802
1803 /**
1804  * zbd_adjust_ddir - Adjust an I/O direction for zonemode=zbd.
1805  *
1806  * @td: FIO thread data.
1807  * @io_u: FIO I/O unit.
1808  * @ddir: I/O direction before adjustment.
1809  *
1810  * Return adjusted I/O direction.
1811  */
1812 enum fio_ddir zbd_adjust_ddir(struct thread_data *td, struct io_u *io_u,
1813                               enum fio_ddir ddir)
1814 {
1815         /*
1816          * In case read direction is chosen for the first random I/O, fio with
1817          * zonemode=zbd stops because no data can be read from zoned block
1818          * devices with all empty zones. Overwrite the first I/O direction as
1819          * write to make sure data to read exists.
1820          */
1821         assert(io_u->file->zbd_info);
1822         if (ddir != DDIR_READ || !td_rw(td))
1823                 return ddir;
1824
1825         if (io_u->file->last_start[DDIR_WRITE] != -1ULL || td->o.read_beyond_wp)
1826                 return DDIR_READ;
1827
1828         return DDIR_WRITE;
1829 }
1830
1831 /**
1832  * zbd_adjust_block - adjust the offset and length as necessary for ZBD drives
1833  * @td: FIO thread data.
1834  * @io_u: FIO I/O unit.
1835  *
1836  * Locking strategy: returns with z->mutex locked if and only if z refers
1837  * to a sequential zone and if io_u_accept is returned. z is the zone that
1838  * corresponds to io_u->offset at the end of this function.
1839  */
1840 enum io_u_action zbd_adjust_block(struct thread_data *td, struct io_u *io_u)
1841 {
1842         struct fio_file *f = io_u->file;
1843         struct zoned_block_device_info *zbdi = f->zbd_info;
1844         struct fio_zone_info *zb, *zl, *orig_zb;
1845         uint32_t orig_len = io_u->buflen;
1846         uint64_t min_bs = td->o.min_bs[io_u->ddir];
1847         uint64_t new_len;
1848         int64_t range;
1849
1850         assert(zbdi);
1851         assert(min_bs);
1852         assert(is_valid_offset(f, io_u->offset));
1853         assert(io_u->buflen);
1854
1855         zb = zbd_offset_to_zone(f, io_u->offset);
1856         orig_zb = zb;
1857
1858         if (!zb->has_wp) {
1859                 /* Accept non-write I/Os for conventional zones. */
1860                 if (io_u->ddir != DDIR_WRITE)
1861                         return io_u_accept;
1862
1863                 /*
1864                  * Make sure that writes to conventional zones
1865                  * don't cross over to any sequential zones.
1866                  */
1867                 if (!(zb + 1)->has_wp ||
1868                     io_u->offset + io_u->buflen <= (zb + 1)->start)
1869                         return io_u_accept;
1870
1871                 if (io_u->offset + min_bs > (zb + 1)->start) {
1872                         dprint(FD_IO,
1873                                "%s: off=%llu + min_bs=%"PRIu64" > next zone %"PRIu64"\n",
1874                                f->file_name, io_u->offset,
1875                                min_bs, (zb + 1)->start);
1876                         io_u->offset =
1877                                 zb->start + (zb + 1)->start - io_u->offset;
1878                         new_len = min(io_u->buflen,
1879                                       (zb + 1)->start - io_u->offset);
1880                 } else {
1881                         new_len = (zb + 1)->start - io_u->offset;
1882                 }
1883
1884                 io_u->buflen = new_len / min_bs * min_bs;
1885
1886                 return io_u_accept;
1887         }
1888
1889         /*
1890          * Accept the I/O offset for reads if reading beyond the write pointer
1891          * is enabled.
1892          */
1893         if (zb->cond != ZBD_ZONE_COND_OFFLINE &&
1894             io_u->ddir == DDIR_READ && td->o.read_beyond_wp)
1895                 return io_u_accept;
1896
1897         zone_lock(td, f, zb);
1898
1899         switch (io_u->ddir) {
1900         case DDIR_READ:
1901                 if (td->runstate == TD_VERIFYING && td_write(td))
1902                         goto accept;
1903
1904                 /*
1905                  * Check that there is enough written data in the zone to do an
1906                  * I/O of at least min_bs B. If there isn't, find a new zone for
1907                  * the I/O.
1908                  */
1909                 range = zb->cond != ZBD_ZONE_COND_OFFLINE ?
1910                         zb->wp - zb->start : 0;
1911                 if (range < min_bs ||
1912                     ((!td_random(td)) && (io_u->offset + min_bs > zb->wp))) {
1913                         zone_unlock(zb);
1914                         zl = zbd_get_zone(f, f->max_zone);
1915                         zb = zbd_find_zone(td, io_u, min_bs, zb, zl);
1916                         if (!zb) {
1917                                 dprint(FD_ZBD,
1918                                        "%s: zbd_find_zone(%lld, %llu) failed\n",
1919                                        f->file_name, io_u->offset,
1920                                        io_u->buflen);
1921                                 goto eof;
1922                         }
1923                         /*
1924                          * zbd_find_zone() returned a zone with a range of at
1925                          * least min_bs.
1926                          */
1927                         range = zb->wp - zb->start;
1928                         assert(range >= min_bs);
1929
1930                         if (!td_random(td))
1931                                 io_u->offset = zb->start;
1932                 }
1933
1934                 /*
1935                  * Make sure the I/O is within the zone valid data range while
1936                  * maximizing the I/O size and preserving randomness.
1937                  */
1938                 if (range <= io_u->buflen)
1939                         io_u->offset = zb->start;
1940                 else if (td_random(td))
1941                         io_u->offset = zb->start +
1942                                 ((io_u->offset - orig_zb->start) %
1943                                  (range - io_u->buflen)) / min_bs * min_bs;
1944
1945                 /*
1946                  * When zbd_find_zone() returns a conventional zone,
1947                  * we can simply accept the new i/o offset here.
1948                  */
1949                 if (!zb->has_wp)
1950                         return io_u_accept;
1951
1952                 /*
1953                  * Make sure the I/O does not cross over the zone wp position.
1954                  */
1955                 new_len = min((unsigned long long)io_u->buflen,
1956                               (unsigned long long)(zb->wp - io_u->offset));
1957                 new_len = new_len / min_bs * min_bs;
1958                 if (new_len < io_u->buflen) {
1959                         io_u->buflen = new_len;
1960                         dprint(FD_IO, "Changed length from %u into %llu\n",
1961                                orig_len, io_u->buflen);
1962                 }
1963
1964                 assert(zb->start <= io_u->offset);
1965                 assert(io_u->offset + io_u->buflen <= zb->wp);
1966
1967                 goto accept;
1968
1969         case DDIR_WRITE:
1970                 if (io_u->buflen > zbdi->zone_size) {
1971                         td_verror(td, EINVAL, "I/O buflen exceeds zone size");
1972                         dprint(FD_IO,
1973                                "%s: I/O buflen %llu exceeds zone size %"PRIu64"\n",
1974                                f->file_name, io_u->buflen, zbdi->zone_size);
1975                         goto eof;
1976                 }
1977
1978 retry:
1979                 if (zbd_zone_remainder(zb) > 0 &&
1980                     zbd_zone_remainder(zb) < min_bs) {
1981                         pthread_mutex_lock(&f->zbd_info->mutex);
1982                         zbd_write_zone_put(td, f, zb);
1983                         pthread_mutex_unlock(&f->zbd_info->mutex);
1984                         dprint(FD_ZBD,
1985                                "%s: finish zone %d\n",
1986                                f->file_name, zbd_zone_idx(f, zb));
1987                         io_u_quiesce(td);
1988                         zbd_finish_zone(td, f, zb);
1989                         if (zbd_zone_idx(f, zb) + 1 >= f->max_zone) {
1990                                 if (!td_random(td))
1991                                         goto eof;
1992                         }
1993                         zone_unlock(zb);
1994
1995                         /* Find the next write pointer zone */
1996                         do {
1997                                 zb++;
1998                                 if (zbd_zone_idx(f, zb) >= f->max_zone)
1999                                         zb = zbd_get_zone(f, f->min_zone);
2000                         } while (!zb->has_wp);
2001
2002                         zone_lock(td, f, zb);
2003                 }
2004
2005                 if (!zbd_write_zone_get(td, f, zb)) {
2006                         zone_unlock(zb);
2007                         zb = zbd_convert_to_write_zone(td, io_u);
2008                         if (!zb) {
2009                                 dprint(FD_IO, "%s: can't convert to write target zone",
2010                                        f->file_name);
2011                                 goto eof;
2012                         }
2013                 }
2014
2015                 if (zbd_zone_remainder(zb) > 0 &&
2016                     zbd_zone_remainder(zb) < min_bs)
2017                         goto retry;
2018
2019                 /* Check whether the zone reset threshold has been exceeded */
2020                 if (td->o.zrf.u.f) {
2021                         if (zbdi->wp_valid_data_bytes >=
2022                             f->io_size * td->o.zrt.u.f &&
2023                             zbd_dec_and_reset_write_cnt(td, f))
2024                                 zb->reset_zone = 1;
2025                 }
2026
2027                 /* Reset the zone pointer if necessary */
2028                 if (zb->reset_zone || zbd_zone_full(f, zb, min_bs)) {
2029                         if (td->o.verify != VERIFY_NONE) {
2030                                 /*
2031                                  * Unset io-u->file to tell get_next_verify()
2032                                  * that this IO is not requeue.
2033                                  */
2034                                 io_u->file = NULL;
2035                                 if (!get_next_verify(td, io_u)) {
2036                                         zone_unlock(zb);
2037                                         return io_u_accept;
2038                                 }
2039                                 io_u->file = f;
2040                         }
2041
2042                         /*
2043                          * Since previous write requests may have been submitted
2044                          * asynchronously and since we will submit the zone
2045                          * reset synchronously, wait until previously submitted
2046                          * write requests have completed before issuing a
2047                          * zone reset.
2048                          */
2049                         io_u_quiesce(td);
2050                         zb->reset_zone = 0;
2051                         if (zbd_reset_zone(td, f, zb) < 0)
2052                                 goto eof;
2053
2054                         if (zb->capacity < min_bs) {
2055                                 td_verror(td, EINVAL, "ZCAP is less min_bs");
2056                                 log_err("zone capacity %"PRIu64" smaller than minimum block size %"PRIu64"\n",
2057                                         zb->capacity, min_bs);
2058                                 goto eof;
2059                         }
2060                 }
2061
2062                 /* Make writes occur at the write pointer */
2063                 assert(!zbd_zone_full(f, zb, min_bs));
2064                 io_u->offset = zb->wp;
2065                 if (!is_valid_offset(f, io_u->offset)) {
2066                         td_verror(td, EINVAL, "invalid WP value");
2067                         dprint(FD_ZBD, "%s: dropped request with offset %llu\n",
2068                                f->file_name, io_u->offset);
2069                         goto eof;
2070                 }
2071
2072                 /*
2073                  * Make sure that the buflen is a multiple of the minimal
2074                  * block size. Give up if shrinking would make the request too
2075                  * small.
2076                  */
2077                 new_len = min((unsigned long long)io_u->buflen,
2078                               zbd_zone_capacity_end(zb) - io_u->offset);
2079                 new_len = new_len / min_bs * min_bs;
2080                 if (new_len == io_u->buflen)
2081                         goto accept;
2082                 if (new_len >= min_bs) {
2083                         io_u->buflen = new_len;
2084                         dprint(FD_IO, "Changed length from %u into %llu\n",
2085                                orig_len, io_u->buflen);
2086                         goto accept;
2087                 }
2088
2089                 td_verror(td, EIO, "zone remainder too small");
2090                 log_err("zone remainder %lld smaller than min block size %"PRIu64"\n",
2091                         (zbd_zone_capacity_end(zb) - io_u->offset), min_bs);
2092
2093                 goto eof;
2094
2095         case DDIR_TRIM:
2096                 /* Check random trim targets a non-empty zone */
2097                 if (!td_random(td) || zb->wp > zb->start)
2098                         goto accept;
2099
2100                 /* Find out a non-empty zone to trim */
2101                 zone_unlock(zb);
2102                 zl = zbd_get_zone(f, f->max_zone);
2103                 zb = zbd_find_zone(td, io_u, 1, zb, zl);
2104                 if (zb) {
2105                         io_u->offset = zb->start;
2106                         dprint(FD_ZBD, "%s: found new zone(%lld) for trim\n",
2107                                f->file_name, io_u->offset);
2108                         goto accept;
2109                 }
2110
2111                 goto eof;
2112
2113         case DDIR_SYNC:
2114                 /* fall-through */
2115         case DDIR_DATASYNC:
2116         case DDIR_SYNC_FILE_RANGE:
2117         case DDIR_WAIT:
2118         case DDIR_LAST:
2119         case DDIR_INVAL:
2120                 goto accept;
2121         }
2122
2123         assert(false);
2124
2125 accept:
2126         assert(zb->has_wp);
2127         assert(zb->cond != ZBD_ZONE_COND_OFFLINE);
2128         assert(!io_u->zbd_queue_io);
2129         assert(!io_u->zbd_put_io);
2130
2131         io_u->zbd_queue_io = zbd_queue_io;
2132         io_u->zbd_put_io = zbd_put_io;
2133
2134         /*
2135          * Since we return with the zone lock still held,
2136          * add an annotation to let Coverity know that it
2137          * is intentional.
2138          */
2139         /* coverity[missing_unlock] */
2140
2141         return io_u_accept;
2142
2143 eof:
2144         if (zb && zb->has_wp)
2145                 zone_unlock(zb);
2146
2147         return io_u_eof;
2148 }
2149
2150 /* Return a string with ZBD statistics */
2151 char *zbd_write_status(const struct thread_stat *ts)
2152 {
2153         char *res;
2154
2155         if (asprintf(&res, "; %"PRIu64" zone resets", ts->nr_zone_resets) < 0)
2156                 return NULL;
2157         return res;
2158 }
2159
2160 /**
2161  * zbd_do_io_u_trim - If reset zone is applicable, do reset zone instead of trim
2162  *
2163  * @td: FIO thread data.
2164  * @io_u: FIO I/O unit.
2165  *
2166  * It is assumed that z->mutex is already locked.
2167  * Return io_u_completed when reset zone succeeds. Return 0 when the target zone
2168  * does not have write pointer. On error, return negative errno.
2169  */
2170 int zbd_do_io_u_trim(const struct thread_data *td, struct io_u *io_u)
2171 {
2172         struct fio_file *f = io_u->file;
2173         struct fio_zone_info *z;
2174         int ret;
2175
2176         z = zbd_offset_to_zone(f, io_u->offset);
2177         if (!z->has_wp)
2178                 return 0;
2179
2180         if (io_u->offset != z->start) {
2181                 log_err("Trim offset not at zone start (%lld)\n",
2182                         io_u->offset);
2183                 return -EINVAL;
2184         }
2185
2186         ret = zbd_reset_zone((struct thread_data *)td, f, z);
2187         if (ret < 0)
2188                 return ret;
2189
2190         return io_u_completed;
2191 }