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