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