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