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