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