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