zbd: Fix build errors on Windows and MacOS
[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 "file.h"
15 #include "fio.h"
16 #include "lib/pow2.h"
17 #include "log.h"
18 #include "oslib/asprintf.h"
19 #include "smalloc.h"
20 #include "verify.h"
21 #include "zbd.h"
22
23 /**
24  * zbd_get_zoned_model - Get a device zoned model
25  * @td: FIO thread data
26  * @f: FIO file for which to get model information
27  */
28 int zbd_get_zoned_model(struct thread_data *td, struct fio_file *f,
29                         enum zbd_zoned_model *model)
30 {
31         int ret;
32
33         if (td->io_ops && td->io_ops->get_zoned_model)
34                 ret = td->io_ops->get_zoned_model(td, f, model);
35         else
36                 ret = blkzoned_get_zoned_model(td, f, model);
37         if (ret < 0) {
38                 td_verror(td, errno, "get zoned model failed");
39                 log_err("%s: get zoned model failed (%d).\n",
40                         f->file_name, errno);
41         }
42
43         return ret;
44 }
45
46 /**
47  * zbd_report_zones - Get zone information
48  * @td: FIO thread data.
49  * @f: FIO file for which to get zone information
50  * @offset: offset from which to report zones
51  * @zones: Array of struct zbd_zone
52  * @nr_zones: Size of @zones array
53  *
54  * Get zone information into @zones starting from the zone at offset @offset
55  * for the device specified by @f.
56  *
57  * Returns the number of zones reported upon success and a negative error code
58  * upon failure. If the zone report is empty, always assume an error (device
59  * problem) and return -EIO.
60  */
61 int zbd_report_zones(struct thread_data *td, struct fio_file *f,
62                      uint64_t offset, struct zbd_zone *zones,
63                      unsigned int nr_zones)
64 {
65         int ret;
66
67         if (td->io_ops && td->io_ops->report_zones)
68                 ret = td->io_ops->report_zones(td, f, offset, zones, nr_zones);
69         else
70                 ret = blkzoned_report_zones(td, f, offset, zones, nr_zones);
71         if (ret < 0) {
72                 td_verror(td, errno, "report zones failed");
73                 log_err("%s: report zones from sector %llu failed (%d).\n",
74                         f->file_name, (unsigned long long)offset >> 9, errno);
75         } else if (ret == 0) {
76                 td_verror(td, errno, "Empty zone report");
77                 log_err("%s: report zones from sector %llu is empty.\n",
78                         f->file_name, (unsigned long long)offset >> 9);
79                 ret = -EIO;
80         }
81
82         return ret;
83 }
84
85 /**
86  * zbd_reset_wp - reset the write pointer of a range of zones
87  * @td: FIO thread data.
88  * @f: FIO file for which to reset zones
89  * @offset: Starting offset of the first zone to reset
90  * @length: Length of the range of zones to reset
91  *
92  * Reset the write pointer of all zones in the range @offset...@offset+@length.
93  * Returns 0 upon success and a negative error code upon failure.
94  */
95 int zbd_reset_wp(struct thread_data *td, struct fio_file *f,
96                  uint64_t offset, uint64_t length)
97 {
98         int ret;
99
100         if (td->io_ops && td->io_ops->reset_wp)
101                 ret = td->io_ops->reset_wp(td, f, offset, length);
102         else
103                 ret = blkzoned_reset_wp(td, f, offset, length);
104         if (ret < 0) {
105                 td_verror(td, errno, "resetting wp failed");
106                 log_err("%s: resetting wp for %llu sectors at sector %llu failed (%d).\n",
107                         f->file_name, (unsigned long long)length >> 9,
108                         (unsigned long long)offset >> 9, errno);
109         }
110
111         return ret;
112 }
113
114 /**
115  * zbd_zone_idx - convert an offset into a zone number
116  * @f: file pointer.
117  * @offset: offset in bytes. If this offset is in the first zone_size bytes
118  *          past the disk size then the index of the sentinel is returned.
119  */
120 static uint32_t zbd_zone_idx(const struct fio_file *f, uint64_t offset)
121 {
122         uint32_t zone_idx;
123
124         if (f->zbd_info->zone_size_log2 > 0)
125                 zone_idx = offset >> f->zbd_info->zone_size_log2;
126         else
127                 zone_idx = offset / f->zbd_info->zone_size;
128
129         return min(zone_idx, f->zbd_info->nr_zones);
130 }
131
132 /**
133  * zbd_zone_swr - Test whether a zone requires sequential writes
134  * @z: zone info pointer.
135  */
136 static inline bool zbd_zone_swr(struct fio_zone_info *z)
137 {
138         return z->type == ZBD_ZONE_TYPE_SWR;
139 }
140
141 /**
142  * zbd_zone_full - verify whether a minimum number of bytes remain in a zone
143  * @f: file pointer.
144  * @z: zone info pointer.
145  * @required: minimum number of bytes that must remain in a zone.
146  *
147  * The caller must hold z->mutex.
148  */
149 static bool zbd_zone_full(const struct fio_file *f, struct fio_zone_info *z,
150                           uint64_t required)
151 {
152         assert((required & 511) == 0);
153
154         return zbd_zone_swr(z) &&
155                 z->wp + required > z->start + f->zbd_info->zone_size;
156 }
157
158 static void zone_lock(struct thread_data *td, struct fio_zone_info *z)
159 {
160         /*
161          * Lock the io_u target zone. The zone will be unlocked if io_u offset
162          * is changed or when io_u completes and zbd_put_io() executed.
163          * To avoid multiple jobs doing asynchronous I/Os from deadlocking each
164          * other waiting for zone locks when building an io_u batch, first
165          * only trylock the zone. If the zone is already locked by another job,
166          * process the currently queued I/Os so that I/O progress is made and
167          * zones unlocked.
168          */
169         if (pthread_mutex_trylock(&z->mutex) != 0) {
170                 if (!td_ioengine_flagged(td, FIO_SYNCIO))
171                         io_u_quiesce(td);
172                 pthread_mutex_lock(&z->mutex);
173         }
174 }
175
176 static bool is_valid_offset(const struct fio_file *f, uint64_t offset)
177 {
178         return (uint64_t)(offset - f->file_offset) < f->io_size;
179 }
180
181 /* Verify whether direct I/O is used for all host-managed zoned drives. */
182 static bool zbd_using_direct_io(void)
183 {
184         struct thread_data *td;
185         struct fio_file *f;
186         int i, j;
187
188         for_each_td(td, i) {
189                 if (td->o.odirect || !(td->o.td_ddir & TD_DDIR_WRITE))
190                         continue;
191                 for_each_file(td, f, j) {
192                         if (f->zbd_info &&
193                             f->zbd_info->model == ZBD_HOST_MANAGED)
194                                 return false;
195                 }
196         }
197
198         return true;
199 }
200
201 /* Whether or not the I/O range for f includes one or more sequential zones */
202 static bool zbd_is_seq_job(struct fio_file *f)
203 {
204         uint32_t zone_idx, zone_idx_b, zone_idx_e;
205
206         assert(f->zbd_info);
207         if (f->io_size == 0)
208                 return false;
209         zone_idx_b = zbd_zone_idx(f, f->file_offset);
210         zone_idx_e = zbd_zone_idx(f, f->file_offset + f->io_size - 1);
211         for (zone_idx = zone_idx_b; zone_idx <= zone_idx_e; zone_idx++)
212                 if (zbd_zone_swr(&f->zbd_info->zone_info[zone_idx]))
213                         return true;
214
215         return false;
216 }
217
218 /*
219  * Verify whether offset and size parameters are aligned with zone boundaries.
220  */
221 static bool zbd_verify_sizes(void)
222 {
223         const struct fio_zone_info *z;
224         struct thread_data *td;
225         struct fio_file *f;
226         uint64_t new_offset, new_end;
227         uint32_t zone_idx;
228         int i, j;
229
230         for_each_td(td, i) {
231                 for_each_file(td, f, j) {
232                         if (!f->zbd_info)
233                                 continue;
234                         if (f->file_offset >= f->real_file_size)
235                                 continue;
236                         if (!zbd_is_seq_job(f))
237                                 continue;
238
239                         if (!td->o.zone_size) {
240                                 td->o.zone_size = f->zbd_info->zone_size;
241                                 if (!td->o.zone_size) {
242                                         log_err("%s: invalid 0 zone size\n",
243                                                 f->file_name);
244                                         return false;
245                                 }
246                         } else if (td->o.zone_size != f->zbd_info->zone_size) {
247                                 log_err("%s: job parameter zonesize %llu does not match disk zone size %llu.\n",
248                                         f->file_name, (unsigned long long) td->o.zone_size,
249                                         (unsigned long long) f->zbd_info->zone_size);
250                                 return false;
251                         }
252
253                         if (td->o.zone_skip &&
254                             (td->o.zone_skip < td->o.zone_size ||
255                              td->o.zone_skip % td->o.zone_size)) {
256                                 log_err("%s: zoneskip %llu is not a multiple of the device zone size %llu.\n",
257                                         f->file_name, (unsigned long long) td->o.zone_skip,
258                                         (unsigned long long) td->o.zone_size);
259                                 return false;
260                         }
261
262                         zone_idx = zbd_zone_idx(f, f->file_offset);
263                         z = &f->zbd_info->zone_info[zone_idx];
264                         if (f->file_offset != z->start) {
265                                 new_offset = (z+1)->start;
266                                 if (new_offset >= f->file_offset + f->io_size) {
267                                         log_info("%s: io_size must be at least one zone\n",
268                                                  f->file_name);
269                                         return false;
270                                 }
271                                 log_info("%s: rounded up offset from %llu to %llu\n",
272                                          f->file_name, (unsigned long long) f->file_offset,
273                                          (unsigned long long) new_offset);
274                                 f->io_size -= (new_offset - f->file_offset);
275                                 f->file_offset = new_offset;
276                         }
277                         zone_idx = zbd_zone_idx(f, f->file_offset + f->io_size);
278                         z = &f->zbd_info->zone_info[zone_idx];
279                         new_end = z->start;
280                         if (f->file_offset + f->io_size != new_end) {
281                                 if (new_end <= f->file_offset) {
282                                         log_info("%s: io_size must be at least one zone\n",
283                                                  f->file_name);
284                                         return false;
285                                 }
286                                 log_info("%s: rounded down io_size from %llu to %llu\n",
287                                          f->file_name, (unsigned long long) f->io_size,
288                                          (unsigned long long) new_end - f->file_offset);
289                                 f->io_size = new_end - f->file_offset;
290                         }
291                 }
292         }
293
294         return true;
295 }
296
297 static bool zbd_verify_bs(void)
298 {
299         struct thread_data *td;
300         struct fio_file *f;
301         uint32_t zone_size;
302         int i, j, k;
303
304         for_each_td(td, i) {
305                 for_each_file(td, f, j) {
306                         if (!f->zbd_info)
307                                 continue;
308                         zone_size = f->zbd_info->zone_size;
309                         for (k = 0; k < ARRAY_SIZE(td->o.bs); k++) {
310                                 if (td->o.verify != VERIFY_NONE &&
311                                     zone_size % td->o.bs[k] != 0) {
312                                         log_info("%s: block size %llu is not a divisor of the zone size %d\n",
313                                                  f->file_name, td->o.bs[k],
314                                                  zone_size);
315                                         return false;
316                                 }
317                         }
318                 }
319         }
320         return true;
321 }
322
323 static int ilog2(uint64_t i)
324 {
325         int log = -1;
326
327         while (i) {
328                 i >>= 1;
329                 log++;
330         }
331         return log;
332 }
333
334 /*
335  * Initialize f->zbd_info for devices that are not zoned block devices. This
336  * allows to execute a ZBD workload against a non-ZBD device.
337  */
338 static int init_zone_info(struct thread_data *td, struct fio_file *f)
339 {
340         uint32_t nr_zones;
341         struct fio_zone_info *p;
342         uint64_t zone_size = td->o.zone_size;
343         struct zoned_block_device_info *zbd_info = NULL;
344         pthread_mutexattr_t attr;
345         int i;
346
347         if (zone_size == 0) {
348                 log_err("%s: Specifying the zone size is mandatory for regular block devices with --zonemode=zbd\n\n",
349                         f->file_name);
350                 return 1;
351         }
352
353         if (zone_size < 512) {
354                 log_err("%s: zone size must be at least 512 bytes for --zonemode=zbd\n\n",
355                         f->file_name);
356                 return 1;
357         }
358
359         nr_zones = (f->real_file_size + zone_size - 1) / zone_size;
360         zbd_info = scalloc(1, sizeof(*zbd_info) +
361                            (nr_zones + 1) * sizeof(zbd_info->zone_info[0]));
362         if (!zbd_info)
363                 return -ENOMEM;
364
365         pthread_mutexattr_init(&attr);
366         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
367         pthread_mutexattr_setpshared(&attr, true);
368         pthread_mutex_init(&zbd_info->mutex, &attr);
369         zbd_info->refcount = 1;
370         p = &zbd_info->zone_info[0];
371         for (i = 0; i < nr_zones; i++, p++) {
372                 pthread_mutex_init(&p->mutex, &attr);
373                 p->start = i * zone_size;
374                 p->wp = p->start + zone_size;
375                 p->type = ZBD_ZONE_TYPE_SWR;
376                 p->cond = ZBD_ZONE_COND_EMPTY;
377         }
378         /* a sentinel */
379         p->start = nr_zones * zone_size;
380
381         f->zbd_info = zbd_info;
382         f->zbd_info->zone_size = zone_size;
383         f->zbd_info->zone_size_log2 = is_power_of_2(zone_size) ?
384                 ilog2(zone_size) : 0;
385         f->zbd_info->nr_zones = nr_zones;
386         pthread_mutexattr_destroy(&attr);
387         return 0;
388 }
389
390 /*
391  * Maximum number of zones to report in one operation.
392  */
393 #define ZBD_REPORT_MAX_ZONES    8192U
394
395 /*
396  * Parse the device zone report and store it in f->zbd_info. Must be called
397  * only for devices that are zoned, namely those with a model != ZBD_NONE.
398  */
399 static int parse_zone_info(struct thread_data *td, struct fio_file *f)
400 {
401         int nr_zones, nrz;
402         struct zbd_zone *zones, *z;
403         struct fio_zone_info *p;
404         uint64_t zone_size, offset;
405         struct zoned_block_device_info *zbd_info = NULL;
406         pthread_mutexattr_t attr;
407         int i, j, ret = 0;
408
409         pthread_mutexattr_init(&attr);
410         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
411         pthread_mutexattr_setpshared(&attr, true);
412
413         zones = calloc(ZBD_REPORT_MAX_ZONES, sizeof(struct zbd_zone));
414         if (!zones)
415                 goto out;
416
417         nrz = zbd_report_zones(td, f, 0, zones, ZBD_REPORT_MAX_ZONES);
418         if (nrz < 0) {
419                 ret = nrz;
420                 log_info("fio: report zones (offset 0) failed for %s (%d).\n",
421                          f->file_name, -ret);
422                 goto out;
423         }
424
425         zone_size = zones[0].len;
426         nr_zones = (f->real_file_size + zone_size - 1) / zone_size;
427
428         if (td->o.zone_size == 0) {
429                 td->o.zone_size = zone_size;
430         } else if (td->o.zone_size != zone_size) {
431                 log_err("fio: %s job parameter zonesize %llu does not match disk zone size %llu.\n",
432                         f->file_name, (unsigned long long) td->o.zone_size,
433                         (unsigned long long) zone_size);
434                 ret = -EINVAL;
435                 goto out;
436         }
437
438         dprint(FD_ZBD, "Device %s has %d zones of size %llu KB\n", f->file_name,
439                nr_zones, (unsigned long long) zone_size / 1024);
440
441         zbd_info = scalloc(1, sizeof(*zbd_info) +
442                            (nr_zones + 1) * sizeof(zbd_info->zone_info[0]));
443         ret = -ENOMEM;
444         if (!zbd_info)
445                 goto out;
446         pthread_mutex_init(&zbd_info->mutex, &attr);
447         zbd_info->refcount = 1;
448         p = &zbd_info->zone_info[0];
449         for (offset = 0, j = 0; j < nr_zones;) {
450                 z = &zones[0];
451                 for (i = 0; i < nrz; i++, j++, z++, p++) {
452                         pthread_mutex_init(&p->mutex, &attr);
453                         p->start = z->start;
454                         switch (z->cond) {
455                         case ZBD_ZONE_COND_NOT_WP:
456                         case ZBD_ZONE_COND_FULL:
457                                 p->wp = p->start + zone_size;
458                                 break;
459                         default:
460                                 assert(z->start <= z->wp);
461                                 assert(z->wp <= z->start + zone_size);
462                                 p->wp = z->wp;
463                                 break;
464                         }
465                         p->type = z->type;
466                         p->cond = z->cond;
467                         if (j > 0 && p->start != p[-1].start + zone_size) {
468                                 log_info("%s: invalid zone data\n",
469                                          f->file_name);
470                                 ret = -EINVAL;
471                                 goto out;
472                         }
473                 }
474                 z--;
475                 offset = z->start + z->len;
476                 if (j >= nr_zones)
477                         break;
478                 nrz = zbd_report_zones(td, f, offset,
479                                             zones, ZBD_REPORT_MAX_ZONES);
480                 if (nrz < 0) {
481                         ret = nrz;
482                         log_info("fio: report zones (offset %llu) failed for %s (%d).\n",
483                                  (unsigned long long)offset,
484                                  f->file_name, -ret);
485                         goto out;
486                 }
487         }
488
489         /* a sentinel */
490         zbd_info->zone_info[nr_zones].start = offset;
491
492         f->zbd_info = zbd_info;
493         f->zbd_info->zone_size = zone_size;
494         f->zbd_info->zone_size_log2 = is_power_of_2(zone_size) ?
495                 ilog2(zone_size) : 0;
496         f->zbd_info->nr_zones = nr_zones;
497         zbd_info = NULL;
498         ret = 0;
499
500 out:
501         sfree(zbd_info);
502         free(zones);
503         pthread_mutexattr_destroy(&attr);
504         return ret;
505 }
506
507 /*
508  * Allocate zone information and store it into f->zbd_info if zonemode=zbd.
509  *
510  * Returns 0 upon success and a negative error code upon failure.
511  */
512 static int zbd_create_zone_info(struct thread_data *td, struct fio_file *f)
513 {
514         enum zbd_zoned_model zbd_model;
515         int ret;
516
517         assert(td->o.zone_mode == ZONE_MODE_ZBD);
518
519         ret = zbd_get_zoned_model(td, f, &zbd_model);
520         if (ret)
521                 return ret;
522
523         switch (zbd_model) {
524         case ZBD_IGNORE:
525                 return 0;
526         case ZBD_HOST_AWARE:
527         case ZBD_HOST_MANAGED:
528                 ret = parse_zone_info(td, f);
529                 break;
530         case ZBD_NONE:
531                 ret = init_zone_info(td, f);
532                 break;
533         default:
534                 td_verror(td, EINVAL, "Unsupported zoned model");
535                 log_err("Unsupported zoned model\n");
536                 return -EINVAL;
537         }
538
539         if (ret == 0)
540                 f->zbd_info->model = zbd_model;
541         return ret;
542 }
543
544 void zbd_free_zone_info(struct fio_file *f)
545 {
546         uint32_t refcount;
547
548         if (!f->zbd_info)
549                 return;
550
551         pthread_mutex_lock(&f->zbd_info->mutex);
552         refcount = --f->zbd_info->refcount;
553         pthread_mutex_unlock(&f->zbd_info->mutex);
554
555         assert((int32_t)refcount >= 0);
556         if (refcount == 0)
557                 sfree(f->zbd_info);
558         f->zbd_info = NULL;
559 }
560
561 /*
562  * Initialize f->zbd_info.
563  *
564  * Returns 0 upon success and a negative error code upon failure.
565  *
566  * Note: this function can only work correctly if it is called before the first
567  * fio fork() call.
568  */
569 static int zbd_init_zone_info(struct thread_data *td, struct fio_file *file)
570 {
571         struct thread_data *td2;
572         struct fio_file *f2;
573         int i, j, ret;
574
575         for_each_td(td2, i) {
576                 for_each_file(td2, f2, j) {
577                         if (td2 == td && f2 == file)
578                                 continue;
579                         if (!f2->zbd_info ||
580                             strcmp(f2->file_name, file->file_name) != 0)
581                                 continue;
582                         file->zbd_info = f2->zbd_info;
583                         file->zbd_info->refcount++;
584                         return 0;
585                 }
586         }
587
588         ret = zbd_create_zone_info(td, file);
589         if (ret < 0)
590                 td_verror(td, -ret, "zbd_create_zone_info() failed");
591         return ret;
592 }
593
594 int zbd_init(struct thread_data *td)
595 {
596         struct fio_file *f;
597         int i;
598
599         for_each_file(td, f, i) {
600                 if (zbd_init_zone_info(td, f))
601                         return 1;
602         }
603
604         if (!zbd_using_direct_io()) {
605                 log_err("Using direct I/O is mandatory for writing to ZBD drives\n\n");
606                 return 1;
607         }
608
609         if (!zbd_verify_sizes())
610                 return 1;
611
612         if (!zbd_verify_bs())
613                 return 1;
614
615         return 0;
616 }
617
618 /**
619  * zbd_reset_range - reset zones for a range of sectors
620  * @td: FIO thread data.
621  * @f: Fio file for which to reset zones
622  * @sector: Starting sector in units of 512 bytes
623  * @nr_sectors: Number of sectors in units of 512 bytes
624  *
625  * Returns 0 upon success and a negative error code upon failure.
626  */
627 static int zbd_reset_range(struct thread_data *td, struct fio_file *f,
628                            uint64_t offset, uint64_t length)
629 {
630         uint32_t zone_idx_b, zone_idx_e;
631         struct fio_zone_info *zb, *ze, *z;
632         int ret = 0;
633
634         assert(is_valid_offset(f, offset + length - 1));
635
636         switch (f->zbd_info->model) {
637         case ZBD_HOST_AWARE:
638         case ZBD_HOST_MANAGED:
639                 ret = zbd_reset_wp(td, f, offset, length);
640                 if (ret < 0)
641                         return ret;
642                 break;
643         default:
644                 break;
645         }
646
647         zone_idx_b = zbd_zone_idx(f, offset);
648         zb = &f->zbd_info->zone_info[zone_idx_b];
649         zone_idx_e = zbd_zone_idx(f, offset + length);
650         ze = &f->zbd_info->zone_info[zone_idx_e];
651         for (z = zb; z < ze; z++) {
652                 pthread_mutex_lock(&z->mutex);
653                 pthread_mutex_lock(&f->zbd_info->mutex);
654                 f->zbd_info->sectors_with_data -= z->wp - z->start;
655                 pthread_mutex_unlock(&f->zbd_info->mutex);
656                 z->wp = z->start;
657                 z->verify_block = 0;
658                 pthread_mutex_unlock(&z->mutex);
659         }
660
661         td->ts.nr_zone_resets += ze - zb;
662
663         return ret;
664 }
665
666 static unsigned int zbd_zone_nr(struct zoned_block_device_info *zbd_info,
667                                 struct fio_zone_info *zone)
668 {
669         return zone - zbd_info->zone_info;
670 }
671
672 /**
673  * zbd_reset_zone - reset the write pointer of a single zone
674  * @td: FIO thread data.
675  * @f: FIO file associated with the disk for which to reset a write pointer.
676  * @z: Zone to reset.
677  *
678  * Returns 0 upon success and a negative error code upon failure.
679  */
680 static int zbd_reset_zone(struct thread_data *td, struct fio_file *f,
681                           struct fio_zone_info *z)
682 {
683         dprint(FD_ZBD, "%s: resetting wp of zone %u.\n", f->file_name,
684                 zbd_zone_nr(f->zbd_info, z));
685
686         return zbd_reset_range(td, f, z->start, (z+1)->start - z->start);
687 }
688
689 /*
690  * Reset a range of zones. Returns 0 upon success and 1 upon failure.
691  * @td: fio thread data.
692  * @f: fio file for which to reset zones
693  * @zb: first zone to reset.
694  * @ze: first zone not to reset.
695  * @all_zones: whether to reset all zones or only those zones for which the
696  *      write pointer is not a multiple of td->o.min_bs[DDIR_WRITE].
697  */
698 static int zbd_reset_zones(struct thread_data *td, struct fio_file *f,
699                            struct fio_zone_info *const zb,
700                            struct fio_zone_info *const ze, bool all_zones)
701 {
702         struct fio_zone_info *z;
703         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
704         bool reset_wp;
705         int res = 0;
706
707         dprint(FD_ZBD, "%s: examining zones %u .. %u\n", f->file_name,
708                 zbd_zone_nr(f->zbd_info, zb), zbd_zone_nr(f->zbd_info, ze));
709         for (z = zb; z < ze; z++) {
710                 if (!zbd_zone_swr(z))
711                         continue;
712                 zone_lock(td, z);
713                 reset_wp = all_zones ? z->wp != z->start :
714                                 (td->o.td_ddir & TD_DDIR_WRITE) &&
715                                 z->wp % min_bs != 0;
716                 if (reset_wp) {
717                         dprint(FD_ZBD, "%s: resetting zone %u\n",
718                                f->file_name,
719                                zbd_zone_nr(f->zbd_info, z));
720                         if (zbd_reset_zone(td, f, z) < 0)
721                                 res = 1;
722                 }
723                 pthread_mutex_unlock(&z->mutex);
724         }
725
726         return res;
727 }
728
729 /*
730  * Reset zbd_info.write_cnt, the counter that counts down towards the next
731  * zone reset.
732  */
733 static void zbd_reset_write_cnt(const struct thread_data *td,
734                                 const struct fio_file *f)
735 {
736         assert(0 <= td->o.zrf.u.f && td->o.zrf.u.f <= 1);
737
738         pthread_mutex_lock(&f->zbd_info->mutex);
739         f->zbd_info->write_cnt = td->o.zrf.u.f ?
740                 min(1.0 / td->o.zrf.u.f, 0.0 + UINT_MAX) : UINT_MAX;
741         pthread_mutex_unlock(&f->zbd_info->mutex);
742 }
743
744 static bool zbd_dec_and_reset_write_cnt(const struct thread_data *td,
745                                         const struct fio_file *f)
746 {
747         uint32_t write_cnt = 0;
748
749         pthread_mutex_lock(&f->zbd_info->mutex);
750         assert(f->zbd_info->write_cnt);
751         if (f->zbd_info->write_cnt)
752                 write_cnt = --f->zbd_info->write_cnt;
753         if (write_cnt == 0)
754                 zbd_reset_write_cnt(td, f);
755         pthread_mutex_unlock(&f->zbd_info->mutex);
756
757         return write_cnt == 0;
758 }
759
760 enum swd_action {
761         CHECK_SWD,
762         SET_SWD,
763 };
764
765 /* Calculate the number of sectors with data (swd) and perform action 'a' */
766 static uint64_t zbd_process_swd(const struct fio_file *f, enum swd_action a)
767 {
768         struct fio_zone_info *zb, *ze, *z;
769         uint64_t swd = 0;
770
771         zb = &f->zbd_info->zone_info[zbd_zone_idx(f, f->file_offset)];
772         ze = &f->zbd_info->zone_info[zbd_zone_idx(f, f->file_offset +
773                                                   f->io_size)];
774         for (z = zb; z < ze; z++) {
775                 pthread_mutex_lock(&z->mutex);
776                 swd += z->wp - z->start;
777         }
778         pthread_mutex_lock(&f->zbd_info->mutex);
779         switch (a) {
780         case CHECK_SWD:
781                 assert(f->zbd_info->sectors_with_data == swd);
782                 break;
783         case SET_SWD:
784                 f->zbd_info->sectors_with_data = swd;
785                 break;
786         }
787         pthread_mutex_unlock(&f->zbd_info->mutex);
788         for (z = zb; z < ze; z++)
789                 pthread_mutex_unlock(&z->mutex);
790
791         return swd;
792 }
793
794 /*
795  * The swd check is useful for debugging but takes too much time to leave
796  * it enabled all the time. Hence it is disabled by default.
797  */
798 static const bool enable_check_swd = false;
799
800 /* Check whether the value of zbd_info.sectors_with_data is correct. */
801 static void zbd_check_swd(const struct fio_file *f)
802 {
803         if (!enable_check_swd)
804                 return;
805
806         zbd_process_swd(f, CHECK_SWD);
807 }
808
809 static void zbd_init_swd(struct fio_file *f)
810 {
811         uint64_t swd;
812
813         if (!enable_check_swd)
814                 return;
815
816         swd = zbd_process_swd(f, SET_SWD);
817         dprint(FD_ZBD, "%s(%s): swd = %" PRIu64 "\n", __func__, f->file_name,
818                swd);
819 }
820
821 void zbd_file_reset(struct thread_data *td, struct fio_file *f)
822 {
823         struct fio_zone_info *zb, *ze;
824         uint32_t zone_idx_e;
825
826         if (!f->zbd_info)
827                 return;
828
829         zb = &f->zbd_info->zone_info[zbd_zone_idx(f, f->file_offset)];
830         zone_idx_e = zbd_zone_idx(f, f->file_offset + f->io_size);
831         ze = &f->zbd_info->zone_info[zone_idx_e];
832         zbd_init_swd(f);
833         /*
834          * If data verification is enabled reset the affected zones before
835          * writing any data to avoid that a zone reset has to be issued while
836          * writing data, which causes data loss.
837          */
838         zbd_reset_zones(td, f, zb, ze, td->o.verify != VERIFY_NONE &&
839                         (td->o.td_ddir & TD_DDIR_WRITE) &&
840                         td->runstate != TD_VERIFYING);
841         zbd_reset_write_cnt(td, f);
842 }
843
844 /* The caller must hold f->zbd_info->mutex. */
845 static bool is_zone_open(const struct thread_data *td, const struct fio_file *f,
846                          unsigned int zone_idx)
847 {
848         struct zoned_block_device_info *zbdi = f->zbd_info;
849         int i;
850
851         assert(td->o.max_open_zones <= ARRAY_SIZE(zbdi->open_zones));
852         assert(zbdi->num_open_zones <= td->o.max_open_zones);
853
854         for (i = 0; i < zbdi->num_open_zones; i++)
855                 if (zbdi->open_zones[i] == zone_idx)
856                         return true;
857
858         return false;
859 }
860
861 /*
862  * Open a ZBD zone if it was not yet open. Returns true if either the zone was
863  * already open or if opening a new zone is allowed. Returns false if the zone
864  * was not yet open and opening a new zone would cause the zone limit to be
865  * exceeded.
866  */
867 static bool zbd_open_zone(struct thread_data *td, const struct io_u *io_u,
868                           uint32_t zone_idx)
869 {
870         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
871         const struct fio_file *f = io_u->file;
872         struct fio_zone_info *z = &f->zbd_info->zone_info[zone_idx];
873         bool res = true;
874
875         if (z->cond == ZBD_ZONE_COND_OFFLINE)
876                 return false;
877
878         /*
879          * Skip full zones with data verification enabled because resetting a
880          * zone causes data loss and hence causes verification to fail.
881          */
882         if (td->o.verify != VERIFY_NONE && zbd_zone_full(f, z, min_bs))
883                 return false;
884
885         /* Zero means no limit */
886         if (!td->o.max_open_zones)
887                 return true;
888
889         pthread_mutex_lock(&f->zbd_info->mutex);
890         if (is_zone_open(td, f, zone_idx))
891                 goto out;
892         res = false;
893         if (f->zbd_info->num_open_zones >= td->o.max_open_zones)
894                 goto out;
895         dprint(FD_ZBD, "%s: opening zone %d\n", f->file_name, zone_idx);
896         f->zbd_info->open_zones[f->zbd_info->num_open_zones++] = zone_idx;
897         z->open = 1;
898         res = true;
899
900 out:
901         pthread_mutex_unlock(&f->zbd_info->mutex);
902         return res;
903 }
904
905 /* The caller must hold f->zbd_info->mutex */
906 static void zbd_close_zone(struct thread_data *td, const struct fio_file *f,
907                            unsigned int open_zone_idx)
908 {
909         uint32_t zone_idx;
910
911         assert(open_zone_idx < f->zbd_info->num_open_zones);
912         zone_idx = f->zbd_info->open_zones[open_zone_idx];
913         memmove(f->zbd_info->open_zones + open_zone_idx,
914                 f->zbd_info->open_zones + open_zone_idx + 1,
915                 (ZBD_MAX_OPEN_ZONES - (open_zone_idx + 1)) *
916                 sizeof(f->zbd_info->open_zones[0]));
917         f->zbd_info->num_open_zones--;
918         f->zbd_info->zone_info[zone_idx].open = 0;
919 }
920
921 /* Anything goes as long as it is not a constant. */
922 static uint32_t pick_random_zone_idx(const struct fio_file *f,
923                                      const struct io_u *io_u)
924 {
925         return io_u->offset * f->zbd_info->num_open_zones / f->real_file_size;
926 }
927
928 /*
929  * Modify the offset of an I/O unit that does not refer to an open zone such
930  * that it refers to an open zone. Close an open zone and open a new zone if
931  * necessary. This algorithm can only work correctly if all write pointers are
932  * a multiple of the fio block size. The caller must neither hold z->mutex
933  * nor f->zbd_info->mutex. Returns with z->mutex held upon success.
934  */
935 static struct fio_zone_info *zbd_convert_to_open_zone(struct thread_data *td,
936                                                       struct io_u *io_u)
937 {
938         const uint32_t min_bs = td->o.min_bs[io_u->ddir];
939         const struct fio_file *f = io_u->file;
940         struct fio_zone_info *z;
941         unsigned int open_zone_idx = -1;
942         uint32_t zone_idx, new_zone_idx;
943         int i;
944
945         assert(is_valid_offset(f, io_u->offset));
946
947         if (td->o.max_open_zones) {
948                 /*
949                  * This statement accesses f->zbd_info->open_zones[] on purpose
950                  * without locking.
951                  */
952                 zone_idx = f->zbd_info->open_zones[pick_random_zone_idx(f, io_u)];
953         } else {
954                 zone_idx = zbd_zone_idx(f, io_u->offset);
955         }
956         dprint(FD_ZBD, "%s(%s): starting from zone %d (offset %lld, buflen %lld)\n",
957                __func__, f->file_name, zone_idx, io_u->offset, io_u->buflen);
958
959         /*
960          * Since z->mutex is the outer lock and f->zbd_info->mutex the inner
961          * lock it can happen that the state of the zone with index zone_idx
962          * has changed after 'z' has been assigned and before f->zbd_info->mutex
963          * has been obtained. Hence the loop.
964          */
965         for (;;) {
966                 uint32_t tmp_idx;
967
968                 z = &f->zbd_info->zone_info[zone_idx];
969
970                 zone_lock(td, z);
971                 pthread_mutex_lock(&f->zbd_info->mutex);
972                 if (td->o.max_open_zones == 0)
973                         goto examine_zone;
974                 if (f->zbd_info->num_open_zones == 0) {
975                         pthread_mutex_unlock(&f->zbd_info->mutex);
976                         pthread_mutex_unlock(&z->mutex);
977                         dprint(FD_ZBD, "%s(%s): no zones are open\n",
978                                __func__, f->file_name);
979                         return NULL;
980                 }
981
982                 /*
983                  * List of opened zones is per-device, shared across all threads.
984                  * Start with quasi-random candidate zone.
985                  * Ignore zones which don't belong to thread's offset/size area.
986                  */
987                 open_zone_idx = pick_random_zone_idx(f, io_u);
988                 assert(open_zone_idx < f->zbd_info->num_open_zones);
989                 tmp_idx = open_zone_idx;
990                 for (i = 0; i < f->zbd_info->num_open_zones; i++) {
991                         uint32_t tmpz;
992
993                         if (tmp_idx >= f->zbd_info->num_open_zones)
994                                 tmp_idx = 0;
995                         tmpz = f->zbd_info->open_zones[tmp_idx];
996
997                         if (is_valid_offset(f, f->zbd_info->zone_info[tmpz].start)) {
998                                 open_zone_idx = tmp_idx;
999                                 goto found_candidate_zone;
1000                         }
1001
1002                         tmp_idx++;
1003                 }
1004
1005                 dprint(FD_ZBD, "%s(%s): no candidate zone\n",
1006                         __func__, f->file_name);
1007                 return NULL;
1008
1009 found_candidate_zone:
1010                 new_zone_idx = f->zbd_info->open_zones[open_zone_idx];
1011                 if (new_zone_idx == zone_idx)
1012                         break;
1013                 zone_idx = new_zone_idx;
1014                 pthread_mutex_unlock(&f->zbd_info->mutex);
1015                 pthread_mutex_unlock(&z->mutex);
1016         }
1017
1018         /* Both z->mutex and f->zbd_info->mutex are held. */
1019
1020 examine_zone:
1021         if (z->wp + min_bs <= (z+1)->start) {
1022                 pthread_mutex_unlock(&f->zbd_info->mutex);
1023                 goto out;
1024         }
1025         dprint(FD_ZBD, "%s(%s): closing zone %d\n", __func__, f->file_name,
1026                zone_idx);
1027         if (td->o.max_open_zones)
1028                 zbd_close_zone(td, f, open_zone_idx);
1029         pthread_mutex_unlock(&f->zbd_info->mutex);
1030
1031         /* Only z->mutex is held. */
1032
1033         /* Zone 'z' is full, so try to open a new zone. */
1034         for (i = f->io_size / f->zbd_info->zone_size; i > 0; i--) {
1035                 zone_idx++;
1036                 pthread_mutex_unlock(&z->mutex);
1037                 z++;
1038                 if (!is_valid_offset(f, z->start)) {
1039                         /* Wrap-around. */
1040                         zone_idx = zbd_zone_idx(f, f->file_offset);
1041                         z = &f->zbd_info->zone_info[zone_idx];
1042                 }
1043                 assert(is_valid_offset(f, z->start));
1044                 zone_lock(td, z);
1045                 if (z->open)
1046                         continue;
1047                 if (zbd_open_zone(td, io_u, zone_idx))
1048                         goto out;
1049         }
1050
1051         /* Only z->mutex is held. */
1052
1053         /* Check whether the write fits in any of the already opened zones. */
1054         pthread_mutex_lock(&f->zbd_info->mutex);
1055         for (i = 0; i < f->zbd_info->num_open_zones; i++) {
1056                 zone_idx = f->zbd_info->open_zones[i];
1057                 pthread_mutex_unlock(&f->zbd_info->mutex);
1058                 pthread_mutex_unlock(&z->mutex);
1059
1060                 z = &f->zbd_info->zone_info[zone_idx];
1061
1062                 zone_lock(td, z);
1063                 if (z->wp + min_bs <= (z+1)->start)
1064                         goto out;
1065                 pthread_mutex_lock(&f->zbd_info->mutex);
1066         }
1067         pthread_mutex_unlock(&f->zbd_info->mutex);
1068         pthread_mutex_unlock(&z->mutex);
1069         dprint(FD_ZBD, "%s(%s): did not open another zone\n", __func__,
1070                f->file_name);
1071         return NULL;
1072
1073 out:
1074         dprint(FD_ZBD, "%s(%s): returning zone %d\n", __func__, f->file_name,
1075                zone_idx);
1076         io_u->offset = z->start;
1077         return z;
1078 }
1079
1080 /* The caller must hold z->mutex. */
1081 static struct fio_zone_info *zbd_replay_write_order(struct thread_data *td,
1082                                                     struct io_u *io_u,
1083                                                     struct fio_zone_info *z)
1084 {
1085         const struct fio_file *f = io_u->file;
1086         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
1087
1088         if (!zbd_open_zone(td, io_u, z - f->zbd_info->zone_info)) {
1089                 pthread_mutex_unlock(&z->mutex);
1090                 z = zbd_convert_to_open_zone(td, io_u);
1091                 assert(z);
1092         }
1093
1094         if (z->verify_block * min_bs >= f->zbd_info->zone_size)
1095                 log_err("%s: %d * %d >= %llu\n", f->file_name, z->verify_block,
1096                         min_bs, (unsigned long long) f->zbd_info->zone_size);
1097         io_u->offset = z->start + z->verify_block++ * min_bs;
1098         return z;
1099 }
1100
1101 /*
1102  * Find another zone for which @io_u fits below the write pointer. Start
1103  * searching in zones @zb + 1 .. @zl and continue searching in zones
1104  * @zf .. @zb - 1.
1105  *
1106  * Either returns NULL or returns a zone pointer and holds the mutex for that
1107  * zone.
1108  */
1109 static struct fio_zone_info *
1110 zbd_find_zone(struct thread_data *td, struct io_u *io_u,
1111               struct fio_zone_info *zb, struct fio_zone_info *zl)
1112 {
1113         const uint32_t min_bs = td->o.min_bs[io_u->ddir];
1114         const struct fio_file *f = io_u->file;
1115         struct fio_zone_info *z1, *z2;
1116         const struct fio_zone_info *const zf =
1117                 &f->zbd_info->zone_info[zbd_zone_idx(f, f->file_offset)];
1118
1119         /*
1120          * Skip to the next non-empty zone in case of sequential I/O and to
1121          * the nearest non-empty zone in case of random I/O.
1122          */
1123         for (z1 = zb + 1, z2 = zb - 1; z1 < zl || z2 >= zf; z1++, z2--) {
1124                 if (z1 < zl && z1->cond != ZBD_ZONE_COND_OFFLINE) {
1125                         pthread_mutex_lock(&z1->mutex);
1126                         if (z1->start + min_bs <= z1->wp)
1127                                 return z1;
1128                         pthread_mutex_unlock(&z1->mutex);
1129                 } else if (!td_random(td)) {
1130                         break;
1131                 }
1132                 if (td_random(td) && z2 >= zf &&
1133                     z2->cond != ZBD_ZONE_COND_OFFLINE) {
1134                         pthread_mutex_lock(&z2->mutex);
1135                         if (z2->start + min_bs <= z2->wp)
1136                                 return z2;
1137                         pthread_mutex_unlock(&z2->mutex);
1138                 }
1139         }
1140         dprint(FD_ZBD, "%s: adjusting random read offset failed\n",
1141                f->file_name);
1142         return NULL;
1143 }
1144
1145 /**
1146  * zbd_queue_io - update the write pointer of a sequential zone
1147  * @io_u: I/O unit
1148  * @success: Whether or not the I/O unit has been queued successfully
1149  * @q: queueing status (busy, completed or queued).
1150  *
1151  * For write and trim operations, update the write pointer of the I/O unit
1152  * target zone.
1153  */
1154 static void zbd_queue_io(struct io_u *io_u, int q, bool success)
1155 {
1156         const struct fio_file *f = io_u->file;
1157         struct zoned_block_device_info *zbd_info = f->zbd_info;
1158         struct fio_zone_info *z;
1159         uint32_t zone_idx;
1160         uint64_t zone_end;
1161
1162         if (!zbd_info)
1163                 return;
1164
1165         zone_idx = zbd_zone_idx(f, io_u->offset);
1166         assert(zone_idx < zbd_info->nr_zones);
1167         z = &zbd_info->zone_info[zone_idx];
1168
1169         if (!zbd_zone_swr(z))
1170                 return;
1171
1172         if (!success)
1173                 goto unlock;
1174
1175         dprint(FD_ZBD,
1176                "%s: queued I/O (%lld, %llu) for zone %u\n",
1177                f->file_name, io_u->offset, io_u->buflen, zone_idx);
1178
1179         switch (io_u->ddir) {
1180         case DDIR_WRITE:
1181                 zone_end = min((uint64_t)(io_u->offset + io_u->buflen),
1182                                (z + 1)->start);
1183                 pthread_mutex_lock(&zbd_info->mutex);
1184                 /*
1185                  * z->wp > zone_end means that one or more I/O errors
1186                  * have occurred.
1187                  */
1188                 if (z->wp <= zone_end)
1189                         zbd_info->sectors_with_data += zone_end - z->wp;
1190                 pthread_mutex_unlock(&zbd_info->mutex);
1191                 z->wp = zone_end;
1192                 break;
1193         case DDIR_TRIM:
1194                 assert(z->wp == z->start);
1195                 break;
1196         default:
1197                 break;
1198         }
1199
1200 unlock:
1201         if (!success || q != FIO_Q_QUEUED) {
1202                 /* BUSY or COMPLETED: unlock the zone */
1203                 pthread_mutex_unlock(&z->mutex);
1204                 io_u->zbd_put_io = NULL;
1205         }
1206 }
1207
1208 /**
1209  * zbd_put_io - Unlock an I/O unit target zone lock
1210  * @io_u: I/O unit
1211  */
1212 static void zbd_put_io(const struct io_u *io_u)
1213 {
1214         const struct fio_file *f = io_u->file;
1215         struct zoned_block_device_info *zbd_info = f->zbd_info;
1216         struct fio_zone_info *z;
1217         uint32_t zone_idx;
1218
1219         if (!zbd_info)
1220                 return;
1221
1222         zone_idx = zbd_zone_idx(f, io_u->offset);
1223         assert(zone_idx < zbd_info->nr_zones);
1224         z = &zbd_info->zone_info[zone_idx];
1225
1226         if (!zbd_zone_swr(z))
1227                 return;
1228
1229         dprint(FD_ZBD,
1230                "%s: terminate I/O (%lld, %llu) for zone %u\n",
1231                f->file_name, io_u->offset, io_u->buflen, zone_idx);
1232
1233         assert(pthread_mutex_unlock(&z->mutex) == 0);
1234         zbd_check_swd(f);
1235 }
1236
1237 /*
1238  * Windows and MacOS do not define this.
1239  */
1240 #ifndef EREMOTEIO
1241 #define EREMOTEIO       121     /* POSIX value */
1242 #endif
1243
1244 bool zbd_unaligned_write(int error_code)
1245 {
1246         switch (error_code) {
1247         case EIO:
1248         case EREMOTEIO:
1249                 return true;
1250         }
1251         return false;
1252 }
1253
1254 /**
1255  * setup_zbd_zone_mode - handle zoneskip as necessary for ZBD drives
1256  * @td: FIO thread data.
1257  * @io_u: FIO I/O unit.
1258  *
1259  * For sequential workloads, change the file offset to skip zoneskip bytes when
1260  * no more IO can be performed in the current zone.
1261  * - For read workloads, zoneskip is applied when the io has reached the end of
1262  *   the zone or the zone write position (when td->o.read_beyond_wp is false).
1263  * - For write workloads, zoneskip is applied when the zone is full.
1264  * This applies only to read and write operations.
1265  */
1266 void setup_zbd_zone_mode(struct thread_data *td, struct io_u *io_u)
1267 {
1268         struct fio_file *f = io_u->file;
1269         enum fio_ddir ddir = io_u->ddir;
1270         struct fio_zone_info *z;
1271         uint32_t zone_idx;
1272
1273         assert(td->o.zone_mode == ZONE_MODE_ZBD);
1274         assert(td->o.zone_size);
1275
1276         /*
1277          * zone_skip is valid only for sequential workloads.
1278          */
1279         if (td_random(td) || !td->o.zone_skip)
1280                 return;
1281
1282         /*
1283          * It is time to switch to a new zone if:
1284          * - zone_bytes == zone_size bytes have already been accessed
1285          * - The last position reached the end of the current zone.
1286          * - For reads with td->o.read_beyond_wp == false, the last position
1287          *   reached the zone write pointer.
1288          */
1289         zone_idx = zbd_zone_idx(f, f->last_pos[ddir]);
1290         z = &f->zbd_info->zone_info[zone_idx];
1291
1292         if (td->zone_bytes >= td->o.zone_size ||
1293             f->last_pos[ddir] >= (z+1)->start ||
1294             (ddir == DDIR_READ &&
1295              (!td->o.read_beyond_wp) && f->last_pos[ddir] >= z->wp)) {
1296                 /*
1297                  * Skip zones.
1298                  */
1299                 td->zone_bytes = 0;
1300                 f->file_offset += td->o.zone_size + td->o.zone_skip;
1301
1302                 /*
1303                  * Wrap from the beginning, if we exceed the file size
1304                  */
1305                 if (f->file_offset >= f->real_file_size)
1306                         f->file_offset = get_start_offset(td, f);
1307
1308                 f->last_pos[ddir] = f->file_offset;
1309                 td->io_skip_bytes += td->o.zone_skip;
1310         }
1311 }
1312
1313 /**
1314  * zbd_adjust_block - adjust the offset and length as necessary for ZBD drives
1315  * @td: FIO thread data.
1316  * @io_u: FIO I/O unit.
1317  *
1318  * Locking strategy: returns with z->mutex locked if and only if z refers
1319  * to a sequential zone and if io_u_accept is returned. z is the zone that
1320  * corresponds to io_u->offset at the end of this function.
1321  */
1322 enum io_u_action zbd_adjust_block(struct thread_data *td, struct io_u *io_u)
1323 {
1324         struct fio_file *f = io_u->file;
1325         uint32_t zone_idx_b;
1326         struct fio_zone_info *zb, *zl, *orig_zb;
1327         uint32_t orig_len = io_u->buflen;
1328         uint32_t min_bs = td->o.min_bs[io_u->ddir];
1329         uint64_t new_len;
1330         int64_t range;
1331
1332         if (!f->zbd_info)
1333                 return io_u_accept;
1334
1335         assert(is_valid_offset(f, io_u->offset));
1336         assert(io_u->buflen);
1337         zone_idx_b = zbd_zone_idx(f, io_u->offset);
1338         zb = &f->zbd_info->zone_info[zone_idx_b];
1339         orig_zb = zb;
1340
1341         /* Accept the I/O offset for conventional zones. */
1342         if (!zbd_zone_swr(zb))
1343                 return io_u_accept;
1344
1345         /*
1346          * Accept the I/O offset for reads if reading beyond the write pointer
1347          * is enabled.
1348          */
1349         if (zb->cond != ZBD_ZONE_COND_OFFLINE &&
1350             io_u->ddir == DDIR_READ && td->o.read_beyond_wp)
1351                 return io_u_accept;
1352
1353         zbd_check_swd(f);
1354
1355         zone_lock(td, zb);
1356
1357         switch (io_u->ddir) {
1358         case DDIR_READ:
1359                 if (td->runstate == TD_VERIFYING) {
1360                         zb = zbd_replay_write_order(td, io_u, zb);
1361                         goto accept;
1362                 }
1363                 /*
1364                  * Check that there is enough written data in the zone to do an
1365                  * I/O of at least min_bs B. If there isn't, find a new zone for
1366                  * the I/O.
1367                  */
1368                 range = zb->cond != ZBD_ZONE_COND_OFFLINE ?
1369                         zb->wp - zb->start : 0;
1370                 if (range < min_bs ||
1371                     ((!td_random(td)) && (io_u->offset + min_bs > zb->wp))) {
1372                         pthread_mutex_unlock(&zb->mutex);
1373                         zl = &f->zbd_info->zone_info[zbd_zone_idx(f,
1374                                                 f->file_offset + f->io_size)];
1375                         zb = zbd_find_zone(td, io_u, zb, zl);
1376                         if (!zb) {
1377                                 dprint(FD_ZBD,
1378                                        "%s: zbd_find_zone(%lld, %llu) failed\n",
1379                                        f->file_name, io_u->offset,
1380                                        io_u->buflen);
1381                                 goto eof;
1382                         }
1383                         /*
1384                          * zbd_find_zone() returned a zone with a range of at
1385                          * least min_bs.
1386                          */
1387                         range = zb->wp - zb->start;
1388                         assert(range >= min_bs);
1389
1390                         if (!td_random(td))
1391                                 io_u->offset = zb->start;
1392                 }
1393                 /*
1394                  * Make sure the I/O is within the zone valid data range while
1395                  * maximizing the I/O size and preserving randomness.
1396                  */
1397                 if (range <= io_u->buflen)
1398                         io_u->offset = zb->start;
1399                 else if (td_random(td))
1400                         io_u->offset = zb->start +
1401                                 ((io_u->offset - orig_zb->start) %
1402                                  (range - io_u->buflen)) / min_bs * min_bs;
1403                 /*
1404                  * Make sure the I/O does not cross over the zone wp position.
1405                  */
1406                 new_len = min((unsigned long long)io_u->buflen,
1407                               (unsigned long long)(zb->wp - io_u->offset));
1408                 new_len = new_len / min_bs * min_bs;
1409                 if (new_len < io_u->buflen) {
1410                         io_u->buflen = new_len;
1411                         dprint(FD_IO, "Changed length from %u into %llu\n",
1412                                orig_len, io_u->buflen);
1413                 }
1414                 assert(zb->start <= io_u->offset);
1415                 assert(io_u->offset + io_u->buflen <= zb->wp);
1416                 goto accept;
1417         case DDIR_WRITE:
1418                 if (io_u->buflen > f->zbd_info->zone_size)
1419                         goto eof;
1420                 if (!zbd_open_zone(td, io_u, zone_idx_b)) {
1421                         pthread_mutex_unlock(&zb->mutex);
1422                         zb = zbd_convert_to_open_zone(td, io_u);
1423                         if (!zb)
1424                                 goto eof;
1425                         zone_idx_b = zb - f->zbd_info->zone_info;
1426                 }
1427                 /* Check whether the zone reset threshold has been exceeded */
1428                 if (td->o.zrf.u.f) {
1429                         if (f->zbd_info->sectors_with_data >=
1430                             f->io_size * td->o.zrt.u.f &&
1431                             zbd_dec_and_reset_write_cnt(td, f)) {
1432                                 zb->reset_zone = 1;
1433                         }
1434                 }
1435                 /* Reset the zone pointer if necessary */
1436                 if (zb->reset_zone || zbd_zone_full(f, zb, min_bs)) {
1437                         assert(td->o.verify == VERIFY_NONE);
1438                         /*
1439                          * Since previous write requests may have been submitted
1440                          * asynchronously and since we will submit the zone
1441                          * reset synchronously, wait until previously submitted
1442                          * write requests have completed before issuing a
1443                          * zone reset.
1444                          */
1445                         io_u_quiesce(td);
1446                         zb->reset_zone = 0;
1447                         if (zbd_reset_zone(td, f, zb) < 0)
1448                                 goto eof;
1449                 }
1450                 /* Make writes occur at the write pointer */
1451                 assert(!zbd_zone_full(f, zb, min_bs));
1452                 io_u->offset = zb->wp;
1453                 if (!is_valid_offset(f, io_u->offset)) {
1454                         dprint(FD_ZBD, "Dropped request with offset %llu\n",
1455                                io_u->offset);
1456                         goto eof;
1457                 }
1458                 /*
1459                  * Make sure that the buflen is a multiple of the minimal
1460                  * block size. Give up if shrinking would make the request too
1461                  * small.
1462                  */
1463                 new_len = min((unsigned long long)io_u->buflen,
1464                               (zb + 1)->start - io_u->offset);
1465                 new_len = new_len / min_bs * min_bs;
1466                 if (new_len == io_u->buflen)
1467                         goto accept;
1468                 if (new_len >= min_bs) {
1469                         io_u->buflen = new_len;
1470                         dprint(FD_IO, "Changed length from %u into %llu\n",
1471                                orig_len, io_u->buflen);
1472                         goto accept;
1473                 }
1474                 log_err("Zone remainder %lld smaller than minimum block size %d\n",
1475                         ((zb + 1)->start - io_u->offset),
1476                         min_bs);
1477                 goto eof;
1478         case DDIR_TRIM:
1479                 /* fall-through */
1480         case DDIR_SYNC:
1481         case DDIR_DATASYNC:
1482         case DDIR_SYNC_FILE_RANGE:
1483         case DDIR_WAIT:
1484         case DDIR_LAST:
1485         case DDIR_INVAL:
1486                 goto accept;
1487         }
1488
1489         assert(false);
1490
1491 accept:
1492         assert(zb);
1493         assert(zb->cond != ZBD_ZONE_COND_OFFLINE);
1494         assert(!io_u->zbd_queue_io);
1495         assert(!io_u->zbd_put_io);
1496         io_u->zbd_queue_io = zbd_queue_io;
1497         io_u->zbd_put_io = zbd_put_io;
1498         return io_u_accept;
1499
1500 eof:
1501         if (zb)
1502                 pthread_mutex_unlock(&zb->mutex);
1503         return io_u_eof;
1504 }
1505
1506 /* Return a string with ZBD statistics */
1507 char *zbd_write_status(const struct thread_stat *ts)
1508 {
1509         char *res;
1510
1511         if (asprintf(&res, "; %llu zone resets", (unsigned long long) ts->nr_zone_resets) < 0)
1512                 return NULL;
1513         return res;
1514 }