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