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