oslib/linux-blkzoned: Allow reset zone before file set up
[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 < 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 int zbd_setup_files(struct thread_data *td)
632 {
633         struct fio_file *f;
634         int i;
635
636         for_each_file(td, f, i) {
637                 if (zbd_init_zone_info(td, f))
638                         return 1;
639         }
640
641         if (!zbd_using_direct_io()) {
642                 log_err("Using direct I/O is mandatory for writing to ZBD drives\n\n");
643                 return 1;
644         }
645
646         if (!zbd_verify_sizes())
647                 return 1;
648
649         if (!zbd_verify_bs())
650                 return 1;
651
652         for_each_file(td, f, i) {
653                 struct zoned_block_device_info *zbd = f->zbd_info;
654
655                 if (!zbd)
656                         continue;
657
658                 zbd->max_open_zones = zbd->max_open_zones ?: ZBD_MAX_OPEN_ZONES;
659
660                 if (td->o.max_open_zones > 0 &&
661                     zbd->max_open_zones != td->o.max_open_zones) {
662                         log_err("Different 'max_open_zones' values\n");
663                         return 1;
664                 }
665                 if (zbd->max_open_zones > ZBD_MAX_OPEN_ZONES) {
666                         log_err("'max_open_zones' value is limited by %u\n", ZBD_MAX_OPEN_ZONES);
667                         return 1;
668                 }
669         }
670
671         return 0;
672 }
673
674 static unsigned int zbd_zone_nr(struct zoned_block_device_info *zbd_info,
675                                 struct fio_zone_info *zone)
676 {
677         return zone - zbd_info->zone_info;
678 }
679
680 /**
681  * zbd_reset_zone - reset the write pointer of a single zone
682  * @td: FIO thread data.
683  * @f: FIO file associated with the disk for which to reset a write pointer.
684  * @z: Zone to reset.
685  *
686  * Returns 0 upon success and a negative error code upon failure.
687  *
688  * The caller must hold z->mutex.
689  */
690 static int zbd_reset_zone(struct thread_data *td, struct fio_file *f,
691                           struct fio_zone_info *z)
692 {
693         uint64_t offset = z->start;
694         uint64_t length = (z+1)->start - offset;
695         int ret = 0;
696
697         assert(is_valid_offset(f, offset + length - 1));
698
699         dprint(FD_ZBD, "%s: resetting wp of zone %u.\n", f->file_name,
700                 zbd_zone_nr(f->zbd_info, z));
701         switch (f->zbd_info->model) {
702         case ZBD_HOST_AWARE:
703         case ZBD_HOST_MANAGED:
704                 ret = zbd_reset_wp(td, f, offset, length);
705                 if (ret < 0)
706                         return ret;
707                 break;
708         default:
709                 break;
710         }
711
712         pthread_mutex_lock(&f->zbd_info->mutex);
713         f->zbd_info->sectors_with_data -= z->wp - z->start;
714         pthread_mutex_unlock(&f->zbd_info->mutex);
715         z->wp = z->start;
716         z->verify_block = 0;
717
718         td->ts.nr_zone_resets++;
719
720         return ret;
721 }
722
723 /* The caller must hold f->zbd_info->mutex */
724 static void zbd_close_zone(struct thread_data *td, const struct fio_file *f,
725                            unsigned int zone_idx)
726 {
727         uint32_t open_zone_idx = 0;
728
729         for (; open_zone_idx < f->zbd_info->num_open_zones; open_zone_idx++) {
730                 if (f->zbd_info->open_zones[open_zone_idx] == zone_idx)
731                         break;
732         }
733         if (open_zone_idx == f->zbd_info->num_open_zones) {
734                 dprint(FD_ZBD, "%s: zone %d is not open\n",
735                        f->file_name, zone_idx);
736                 return;
737         }
738
739         dprint(FD_ZBD, "%s: closing zone %d\n", f->file_name, zone_idx);
740         memmove(f->zbd_info->open_zones + open_zone_idx,
741                 f->zbd_info->open_zones + open_zone_idx + 1,
742                 (ZBD_MAX_OPEN_ZONES - (open_zone_idx + 1)) *
743                 sizeof(f->zbd_info->open_zones[0]));
744         f->zbd_info->num_open_zones--;
745         td->num_open_zones--;
746         f->zbd_info->zone_info[zone_idx].open = 0;
747 }
748
749 /*
750  * Reset a range of zones. Returns 0 upon success and 1 upon failure.
751  * @td: fio thread data.
752  * @f: fio file for which to reset zones
753  * @zb: first zone to reset.
754  * @ze: first zone not to reset.
755  * @all_zones: whether to reset all zones or only those zones for which the
756  *      write pointer is not a multiple of td->o.min_bs[DDIR_WRITE].
757  */
758 static int zbd_reset_zones(struct thread_data *td, struct fio_file *f,
759                            struct fio_zone_info *const zb,
760                            struct fio_zone_info *const ze, bool all_zones)
761 {
762         struct fio_zone_info *z;
763         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
764         bool reset_wp;
765         int res = 0;
766
767         assert(min_bs);
768
769         dprint(FD_ZBD, "%s: examining zones %u .. %u\n", f->file_name,
770                 zbd_zone_nr(f->zbd_info, zb), zbd_zone_nr(f->zbd_info, ze));
771         for (z = zb; z < ze; z++) {
772                 uint32_t nz = z - f->zbd_info->zone_info;
773
774                 if (!zbd_zone_swr(z))
775                         continue;
776                 zone_lock(td, f, z);
777                 if (all_zones) {
778                         pthread_mutex_lock(&f->zbd_info->mutex);
779                         zbd_close_zone(td, f, nz);
780                         pthread_mutex_unlock(&f->zbd_info->mutex);
781
782                         reset_wp = z->wp != z->start;
783                 } else {
784                         reset_wp = z->wp % min_bs != 0;
785                 }
786                 if (reset_wp) {
787                         dprint(FD_ZBD, "%s: resetting zone %u\n",
788                                f->file_name,
789                                zbd_zone_nr(f->zbd_info, z));
790                         if (zbd_reset_zone(td, f, z) < 0)
791                                 res = 1;
792                 }
793                 pthread_mutex_unlock(&z->mutex);
794         }
795
796         return res;
797 }
798
799 /*
800  * Reset zbd_info.write_cnt, the counter that counts down towards the next
801  * zone reset.
802  */
803 static void _zbd_reset_write_cnt(const struct thread_data *td,
804                                  const struct fio_file *f)
805 {
806         assert(0 <= td->o.zrf.u.f && td->o.zrf.u.f <= 1);
807
808         f->zbd_info->write_cnt = td->o.zrf.u.f ?
809                 min(1.0 / td->o.zrf.u.f, 0.0 + UINT_MAX) : UINT_MAX;
810 }
811
812 static void zbd_reset_write_cnt(const struct thread_data *td,
813                                 const struct fio_file *f)
814 {
815         pthread_mutex_lock(&f->zbd_info->mutex);
816         _zbd_reset_write_cnt(td, f);
817         pthread_mutex_unlock(&f->zbd_info->mutex);
818 }
819
820 static bool zbd_dec_and_reset_write_cnt(const struct thread_data *td,
821                                         const struct fio_file *f)
822 {
823         uint32_t write_cnt = 0;
824
825         pthread_mutex_lock(&f->zbd_info->mutex);
826         assert(f->zbd_info->write_cnt);
827         if (f->zbd_info->write_cnt)
828                 write_cnt = --f->zbd_info->write_cnt;
829         if (write_cnt == 0)
830                 _zbd_reset_write_cnt(td, f);
831         pthread_mutex_unlock(&f->zbd_info->mutex);
832
833         return write_cnt == 0;
834 }
835
836 enum swd_action {
837         CHECK_SWD,
838         SET_SWD,
839 };
840
841 /* Calculate the number of sectors with data (swd) and perform action 'a' */
842 static uint64_t zbd_process_swd(const struct fio_file *f, enum swd_action a)
843 {
844         struct fio_zone_info *zb, *ze, *z;
845         uint64_t swd = 0;
846
847         zb = &f->zbd_info->zone_info[f->min_zone];
848         ze = &f->zbd_info->zone_info[f->max_zone];
849         for (z = zb; z < ze; z++) {
850                 pthread_mutex_lock(&z->mutex);
851                 swd += z->wp - z->start;
852         }
853         pthread_mutex_lock(&f->zbd_info->mutex);
854         switch (a) {
855         case CHECK_SWD:
856                 assert(f->zbd_info->sectors_with_data == swd);
857                 break;
858         case SET_SWD:
859                 f->zbd_info->sectors_with_data = swd;
860                 break;
861         }
862         pthread_mutex_unlock(&f->zbd_info->mutex);
863         for (z = zb; z < ze; z++)
864                 pthread_mutex_unlock(&z->mutex);
865
866         return swd;
867 }
868
869 /*
870  * The swd check is useful for debugging but takes too much time to leave
871  * it enabled all the time. Hence it is disabled by default.
872  */
873 static const bool enable_check_swd = false;
874
875 /* Check whether the value of zbd_info.sectors_with_data is correct. */
876 static void zbd_check_swd(const struct fio_file *f)
877 {
878         if (!enable_check_swd)
879                 return;
880
881         zbd_process_swd(f, CHECK_SWD);
882 }
883
884 static void zbd_init_swd(struct fio_file *f)
885 {
886         uint64_t swd;
887
888         if (!enable_check_swd)
889                 return;
890
891         swd = zbd_process_swd(f, SET_SWD);
892         dprint(FD_ZBD, "%s(%s): swd = %" PRIu64 "\n", __func__, f->file_name,
893                swd);
894 }
895
896 void zbd_file_reset(struct thread_data *td, struct fio_file *f)
897 {
898         struct fio_zone_info *zb, *ze;
899
900         if (!f->zbd_info || !td_write(td))
901                 return;
902
903         zb = &f->zbd_info->zone_info[f->min_zone];
904         ze = &f->zbd_info->zone_info[f->max_zone];
905         zbd_init_swd(f);
906         /*
907          * If data verification is enabled reset the affected zones before
908          * writing any data to avoid that a zone reset has to be issued while
909          * writing data, which causes data loss.
910          */
911         zbd_reset_zones(td, f, zb, ze, td->o.verify != VERIFY_NONE &&
912                         td->runstate != TD_VERIFYING);
913         zbd_reset_write_cnt(td, f);
914 }
915
916 /* The caller must hold f->zbd_info->mutex. */
917 static bool is_zone_open(const struct thread_data *td, const struct fio_file *f,
918                          unsigned int zone_idx)
919 {
920         struct zoned_block_device_info *zbdi = f->zbd_info;
921         int i;
922
923         assert(td->o.job_max_open_zones == 0 || td->num_open_zones <= td->o.job_max_open_zones);
924         assert(td->o.job_max_open_zones <= zbdi->max_open_zones);
925         assert(zbdi->num_open_zones <= zbdi->max_open_zones);
926
927         for (i = 0; i < zbdi->num_open_zones; i++)
928                 if (zbdi->open_zones[i] == zone_idx)
929                         return true;
930
931         return false;
932 }
933
934 /*
935  * Open a ZBD zone if it was not yet open. Returns true if either the zone was
936  * already open or if opening a new zone is allowed. Returns false if the zone
937  * was not yet open and opening a new zone would cause the zone limit to be
938  * exceeded.
939  */
940 static bool zbd_open_zone(struct thread_data *td, const struct io_u *io_u,
941                           uint32_t zone_idx)
942 {
943         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
944         const struct fio_file *f = io_u->file;
945         struct fio_zone_info *z = &f->zbd_info->zone_info[zone_idx];
946         bool res = true;
947
948         if (z->cond == ZBD_ZONE_COND_OFFLINE)
949                 return false;
950
951         /*
952          * Skip full zones with data verification enabled because resetting a
953          * zone causes data loss and hence causes verification to fail.
954          */
955         if (td->o.verify != VERIFY_NONE && zbd_zone_full(f, z, min_bs))
956                 return false;
957
958         pthread_mutex_lock(&f->zbd_info->mutex);
959         if (is_zone_open(td, f, zone_idx)) {
960                 /*
961                  * If the zone is already open and going to be full by writes
962                  * in-flight, handle it as a full zone instead of an open zone.
963                  */
964                 if (z->wp >= zbd_zone_capacity_end(z))
965                         res = false;
966                 goto out;
967         }
968         res = false;
969         /* Zero means no limit */
970         if (td->o.job_max_open_zones > 0 &&
971             td->num_open_zones >= td->o.job_max_open_zones)
972                 goto out;
973         if (f->zbd_info->num_open_zones >= f->zbd_info->max_open_zones)
974                 goto out;
975         dprint(FD_ZBD, "%s: opening zone %d\n", f->file_name, zone_idx);
976         f->zbd_info->open_zones[f->zbd_info->num_open_zones++] = zone_idx;
977         td->num_open_zones++;
978         z->open = 1;
979         res = true;
980
981 out:
982         pthread_mutex_unlock(&f->zbd_info->mutex);
983         return res;
984 }
985
986 /* Anything goes as long as it is not a constant. */
987 static uint32_t pick_random_zone_idx(const struct fio_file *f,
988                                      const struct io_u *io_u)
989 {
990         return io_u->offset * f->zbd_info->num_open_zones / f->real_file_size;
991 }
992
993 /*
994  * Modify the offset of an I/O unit that does not refer to an open zone such
995  * that it refers to an open zone. Close an open zone and open a new zone if
996  * necessary. This algorithm can only work correctly if all write pointers are
997  * a multiple of the fio block size. The caller must neither hold z->mutex
998  * nor f->zbd_info->mutex. Returns with z->mutex held upon success.
999  */
1000 static struct fio_zone_info *zbd_convert_to_open_zone(struct thread_data *td,
1001                                                       struct io_u *io_u)
1002 {
1003         const uint32_t min_bs = td->o.min_bs[io_u->ddir];
1004         struct fio_file *f = io_u->file;
1005         struct fio_zone_info *z;
1006         unsigned int open_zone_idx = -1;
1007         uint32_t zone_idx, new_zone_idx;
1008         int i;
1009         bool wait_zone_close;
1010
1011         assert(is_valid_offset(f, io_u->offset));
1012
1013         if (td->o.max_open_zones || td->o.job_max_open_zones) {
1014                 /*
1015                  * This statement accesses f->zbd_info->open_zones[] on purpose
1016                  * without locking.
1017                  */
1018                 zone_idx = f->zbd_info->open_zones[pick_random_zone_idx(f, io_u)];
1019         } else {
1020                 zone_idx = zbd_zone_idx(f, io_u->offset);
1021         }
1022         if (zone_idx < f->min_zone)
1023                 zone_idx = f->min_zone;
1024         else if (zone_idx >= f->max_zone)
1025                 zone_idx = f->max_zone - 1;
1026         dprint(FD_ZBD, "%s(%s): starting from zone %d (offset %lld, buflen %lld)\n",
1027                __func__, f->file_name, zone_idx, io_u->offset, io_u->buflen);
1028
1029         /*
1030          * Since z->mutex is the outer lock and f->zbd_info->mutex the inner
1031          * lock it can happen that the state of the zone with index zone_idx
1032          * has changed after 'z' has been assigned and before f->zbd_info->mutex
1033          * has been obtained. Hence the loop.
1034          */
1035         for (;;) {
1036                 uint32_t tmp_idx;
1037
1038                 z = &f->zbd_info->zone_info[zone_idx];
1039
1040                 zone_lock(td, f, z);
1041                 pthread_mutex_lock(&f->zbd_info->mutex);
1042                 if (td->o.max_open_zones == 0 && td->o.job_max_open_zones == 0)
1043                         goto examine_zone;
1044                 if (f->zbd_info->num_open_zones == 0) {
1045                         dprint(FD_ZBD, "%s(%s): no zones are open\n",
1046                                __func__, f->file_name);
1047                         goto open_other_zone;
1048                 }
1049
1050                 /*
1051                  * List of opened zones is per-device, shared across all threads.
1052                  * Start with quasi-random candidate zone.
1053                  * Ignore zones which don't belong to thread's offset/size area.
1054                  */
1055                 open_zone_idx = pick_random_zone_idx(f, io_u);
1056                 assert(open_zone_idx < f->zbd_info->num_open_zones);
1057                 tmp_idx = open_zone_idx;
1058                 for (i = 0; i < f->zbd_info->num_open_zones; i++) {
1059                         uint32_t tmpz;
1060
1061                         if (tmp_idx >= f->zbd_info->num_open_zones)
1062                                 tmp_idx = 0;
1063                         tmpz = f->zbd_info->open_zones[tmp_idx];
1064                         if (f->min_zone <= tmpz && tmpz < f->max_zone) {
1065                                 open_zone_idx = tmp_idx;
1066                                 goto found_candidate_zone;
1067                         }
1068
1069                         tmp_idx++;
1070                 }
1071
1072                 dprint(FD_ZBD, "%s(%s): no candidate zone\n",
1073                         __func__, f->file_name);
1074                 pthread_mutex_unlock(&f->zbd_info->mutex);
1075                 pthread_mutex_unlock(&z->mutex);
1076                 return NULL;
1077
1078 found_candidate_zone:
1079                 new_zone_idx = f->zbd_info->open_zones[open_zone_idx];
1080                 if (new_zone_idx == zone_idx)
1081                         break;
1082                 zone_idx = new_zone_idx;
1083                 pthread_mutex_unlock(&f->zbd_info->mutex);
1084                 pthread_mutex_unlock(&z->mutex);
1085         }
1086
1087         /* Both z->mutex and f->zbd_info->mutex are held. */
1088
1089 examine_zone:
1090         if (z->wp + min_bs <= zbd_zone_capacity_end(z)) {
1091                 pthread_mutex_unlock(&f->zbd_info->mutex);
1092                 goto out;
1093         }
1094
1095 open_other_zone:
1096         /* Check if number of open zones reaches one of limits. */
1097         wait_zone_close =
1098                 f->zbd_info->num_open_zones == f->max_zone - f->min_zone ||
1099                 (td->o.max_open_zones &&
1100                  f->zbd_info->num_open_zones == td->o.max_open_zones) ||
1101                 (td->o.job_max_open_zones &&
1102                  td->num_open_zones == td->o.job_max_open_zones);
1103
1104         pthread_mutex_unlock(&f->zbd_info->mutex);
1105
1106         /* Only z->mutex is held. */
1107
1108         /*
1109          * When number of open zones reaches to one of limits, wait for
1110          * zone close before opening a new zone.
1111          */
1112         if (wait_zone_close) {
1113                 dprint(FD_ZBD, "%s(%s): quiesce to allow open zones to close\n",
1114                        __func__, f->file_name);
1115                 io_u_quiesce(td);
1116         }
1117
1118         /* Zone 'z' is full, so try to open a new zone. */
1119         for (i = f->io_size / f->zbd_info->zone_size; i > 0; i--) {
1120                 zone_idx++;
1121                 pthread_mutex_unlock(&z->mutex);
1122                 z++;
1123                 if (!is_valid_offset(f, z->start)) {
1124                         /* Wrap-around. */
1125                         zone_idx = f->min_zone;
1126                         z = &f->zbd_info->zone_info[zone_idx];
1127                 }
1128                 assert(is_valid_offset(f, z->start));
1129                 zone_lock(td, f, z);
1130                 if (z->open)
1131                         continue;
1132                 if (zbd_open_zone(td, io_u, zone_idx))
1133                         goto out;
1134         }
1135
1136         /* Only z->mutex is held. */
1137
1138         /* Check whether the write fits in any of the already opened zones. */
1139         pthread_mutex_lock(&f->zbd_info->mutex);
1140         for (i = 0; i < f->zbd_info->num_open_zones; i++) {
1141                 zone_idx = f->zbd_info->open_zones[i];
1142                 if (zone_idx < f->min_zone || zone_idx >= f->max_zone)
1143                         continue;
1144                 pthread_mutex_unlock(&f->zbd_info->mutex);
1145                 pthread_mutex_unlock(&z->mutex);
1146
1147                 z = &f->zbd_info->zone_info[zone_idx];
1148
1149                 zone_lock(td, f, z);
1150                 if (z->wp + min_bs <= zbd_zone_capacity_end(z))
1151                         goto out;
1152                 pthread_mutex_lock(&f->zbd_info->mutex);
1153         }
1154         pthread_mutex_unlock(&f->zbd_info->mutex);
1155         pthread_mutex_unlock(&z->mutex);
1156         dprint(FD_ZBD, "%s(%s): did not open another zone\n", __func__,
1157                f->file_name);
1158         return NULL;
1159
1160 out:
1161         dprint(FD_ZBD, "%s(%s): returning zone %d\n", __func__, f->file_name,
1162                zone_idx);
1163         io_u->offset = z->start;
1164         return z;
1165 }
1166
1167 /* The caller must hold z->mutex. */
1168 static struct fio_zone_info *zbd_replay_write_order(struct thread_data *td,
1169                                                     struct io_u *io_u,
1170                                                     struct fio_zone_info *z)
1171 {
1172         const struct fio_file *f = io_u->file;
1173         const uint32_t min_bs = td->o.min_bs[DDIR_WRITE];
1174
1175         if (!zbd_open_zone(td, io_u, z - f->zbd_info->zone_info)) {
1176                 pthread_mutex_unlock(&z->mutex);
1177                 z = zbd_convert_to_open_zone(td, io_u);
1178                 assert(z);
1179         }
1180
1181         if (z->verify_block * min_bs >= z->capacity)
1182                 log_err("%s: %d * %d >= %llu\n", f->file_name, z->verify_block,
1183                         min_bs, (unsigned long long)z->capacity);
1184         io_u->offset = z->start + z->verify_block++ * min_bs;
1185         return z;
1186 }
1187
1188 /*
1189  * Find another zone for which @io_u fits below the write pointer. Start
1190  * searching in zones @zb + 1 .. @zl and continue searching in zones
1191  * @zf .. @zb - 1.
1192  *
1193  * Either returns NULL or returns a zone pointer and holds the mutex for that
1194  * zone.
1195  */
1196 static struct fio_zone_info *
1197 zbd_find_zone(struct thread_data *td, struct io_u *io_u,
1198               struct fio_zone_info *zb, struct fio_zone_info *zl)
1199 {
1200         const uint32_t min_bs = td->o.min_bs[io_u->ddir];
1201         struct fio_file *f = io_u->file;
1202         struct fio_zone_info *z1, *z2;
1203         const struct fio_zone_info *const zf =
1204                 &f->zbd_info->zone_info[f->min_zone];
1205
1206         /*
1207          * Skip to the next non-empty zone in case of sequential I/O and to
1208          * the nearest non-empty zone in case of random I/O.
1209          */
1210         for (z1 = zb + 1, z2 = zb - 1; z1 < zl || z2 >= zf; z1++, z2--) {
1211                 if (z1 < zl && z1->cond != ZBD_ZONE_COND_OFFLINE) {
1212                         zone_lock(td, f, z1);
1213                         if (z1->start + min_bs <= z1->wp)
1214                                 return z1;
1215                         pthread_mutex_unlock(&z1->mutex);
1216                 } else if (!td_random(td)) {
1217                         break;
1218                 }
1219                 if (td_random(td) && z2 >= zf &&
1220                     z2->cond != ZBD_ZONE_COND_OFFLINE) {
1221                         zone_lock(td, f, z2);
1222                         if (z2->start + min_bs <= z2->wp)
1223                                 return z2;
1224                         pthread_mutex_unlock(&z2->mutex);
1225                 }
1226         }
1227         dprint(FD_ZBD, "%s: adjusting random read offset failed\n",
1228                f->file_name);
1229         return NULL;
1230 }
1231
1232 /**
1233  * zbd_end_zone_io - update zone status at command completion
1234  * @io_u: I/O unit
1235  * @z: zone info pointer
1236  *
1237  * If the write command made the zone full, close it.
1238  *
1239  * The caller must hold z->mutex.
1240  */
1241 static void zbd_end_zone_io(struct thread_data *td, const struct io_u *io_u,
1242                             struct fio_zone_info *z)
1243 {
1244         const struct fio_file *f = io_u->file;
1245
1246         if (io_u->ddir == DDIR_WRITE &&
1247             io_u->offset + io_u->buflen >= zbd_zone_capacity_end(z)) {
1248                 pthread_mutex_lock(&f->zbd_info->mutex);
1249                 zbd_close_zone(td, f, z - f->zbd_info->zone_info);
1250                 pthread_mutex_unlock(&f->zbd_info->mutex);
1251         }
1252 }
1253
1254 /**
1255  * zbd_queue_io - update the write pointer of a sequential zone
1256  * @io_u: I/O unit
1257  * @success: Whether or not the I/O unit has been queued successfully
1258  * @q: queueing status (busy, completed or queued).
1259  *
1260  * For write and trim operations, update the write pointer of the I/O unit
1261  * target zone.
1262  */
1263 static void zbd_queue_io(struct thread_data *td, struct io_u *io_u, int q,
1264                          bool success)
1265 {
1266         const struct fio_file *f = io_u->file;
1267         struct zoned_block_device_info *zbd_info = f->zbd_info;
1268         struct fio_zone_info *z;
1269         uint32_t zone_idx;
1270         uint64_t zone_end;
1271
1272         if (!zbd_info)
1273                 return;
1274
1275         zone_idx = zbd_zone_idx(f, io_u->offset);
1276         assert(zone_idx < zbd_info->nr_zones);
1277         z = &zbd_info->zone_info[zone_idx];
1278
1279         if (!zbd_zone_swr(z))
1280                 return;
1281
1282         if (!success)
1283                 goto unlock;
1284
1285         dprint(FD_ZBD,
1286                "%s: queued I/O (%lld, %llu) for zone %u\n",
1287                f->file_name, io_u->offset, io_u->buflen, zone_idx);
1288
1289         switch (io_u->ddir) {
1290         case DDIR_WRITE:
1291                 zone_end = min((uint64_t)(io_u->offset + io_u->buflen),
1292                                zbd_zone_capacity_end(z));
1293                 pthread_mutex_lock(&zbd_info->mutex);
1294                 /*
1295                  * z->wp > zone_end means that one or more I/O errors
1296                  * have occurred.
1297                  */
1298                 if (z->wp <= zone_end)
1299                         zbd_info->sectors_with_data += zone_end - z->wp;
1300                 pthread_mutex_unlock(&zbd_info->mutex);
1301                 z->wp = zone_end;
1302                 break;
1303         case DDIR_TRIM:
1304                 assert(z->wp == z->start);
1305                 break;
1306         default:
1307                 break;
1308         }
1309
1310         if (q == FIO_Q_COMPLETED && !io_u->error)
1311                 zbd_end_zone_io(td, io_u, z);
1312
1313 unlock:
1314         if (!success || q != FIO_Q_QUEUED) {
1315                 /* BUSY or COMPLETED: unlock the zone */
1316                 pthread_mutex_unlock(&z->mutex);
1317                 io_u->zbd_put_io = NULL;
1318         }
1319 }
1320
1321 /**
1322  * zbd_put_io - Unlock an I/O unit target zone lock
1323  * @io_u: I/O unit
1324  */
1325 static void zbd_put_io(struct thread_data *td, const struct io_u *io_u)
1326 {
1327         const struct fio_file *f = io_u->file;
1328         struct zoned_block_device_info *zbd_info = f->zbd_info;
1329         struct fio_zone_info *z;
1330         uint32_t zone_idx;
1331         int ret;
1332
1333         if (!zbd_info)
1334                 return;
1335
1336         zone_idx = zbd_zone_idx(f, io_u->offset);
1337         assert(zone_idx < zbd_info->nr_zones);
1338         z = &zbd_info->zone_info[zone_idx];
1339
1340         if (!zbd_zone_swr(z))
1341                 return;
1342
1343         dprint(FD_ZBD,
1344                "%s: terminate I/O (%lld, %llu) for zone %u\n",
1345                f->file_name, io_u->offset, io_u->buflen, zone_idx);
1346
1347         zbd_end_zone_io(td, io_u, z);
1348
1349         ret = pthread_mutex_unlock(&z->mutex);
1350         assert(ret == 0);
1351         zbd_check_swd(f);
1352 }
1353
1354 /*
1355  * Windows and MacOS do not define this.
1356  */
1357 #ifndef EREMOTEIO
1358 #define EREMOTEIO       121     /* POSIX value */
1359 #endif
1360
1361 bool zbd_unaligned_write(int error_code)
1362 {
1363         switch (error_code) {
1364         case EIO:
1365         case EREMOTEIO:
1366                 return true;
1367         }
1368         return false;
1369 }
1370
1371 /**
1372  * setup_zbd_zone_mode - handle zoneskip as necessary for ZBD drives
1373  * @td: FIO thread data.
1374  * @io_u: FIO I/O unit.
1375  *
1376  * For sequential workloads, change the file offset to skip zoneskip bytes when
1377  * no more IO can be performed in the current zone.
1378  * - For read workloads, zoneskip is applied when the io has reached the end of
1379  *   the zone or the zone write position (when td->o.read_beyond_wp is false).
1380  * - For write workloads, zoneskip is applied when the zone is full.
1381  * This applies only to read and write operations.
1382  */
1383 void setup_zbd_zone_mode(struct thread_data *td, struct io_u *io_u)
1384 {
1385         struct fio_file *f = io_u->file;
1386         enum fio_ddir ddir = io_u->ddir;
1387         struct fio_zone_info *z;
1388         uint32_t zone_idx;
1389
1390         assert(td->o.zone_mode == ZONE_MODE_ZBD);
1391         assert(td->o.zone_size);
1392
1393         zone_idx = zbd_zone_idx(f, f->last_pos[ddir]);
1394         z = &f->zbd_info->zone_info[zone_idx];
1395
1396         /*
1397          * When the zone capacity is smaller than the zone size and the I/O is
1398          * sequential write, skip to zone end if the latest position is at the
1399          * zone capacity limit.
1400          */
1401         if (z->capacity < f->zbd_info->zone_size && !td_random(td) &&
1402             ddir == DDIR_WRITE &&
1403             f->last_pos[ddir] >= zbd_zone_capacity_end(z)) {
1404                 dprint(FD_ZBD,
1405                        "%s: Jump from zone capacity limit to zone end:"
1406                        " (%llu -> %llu) for zone %u (%llu)\n",
1407                        f->file_name, (unsigned long long) f->last_pos[ddir],
1408                        (unsigned long long) zbd_zone_end(z),
1409                        zbd_zone_nr(f->zbd_info, z),
1410                        (unsigned long long) z->capacity);
1411                 td->io_skip_bytes += zbd_zone_end(z) - f->last_pos[ddir];
1412                 f->last_pos[ddir] = zbd_zone_end(z);
1413         }
1414
1415         /*
1416          * zone_skip is valid only for sequential workloads.
1417          */
1418         if (td_random(td) || !td->o.zone_skip)
1419                 return;
1420
1421         /*
1422          * It is time to switch to a new zone if:
1423          * - zone_bytes == zone_size bytes have already been accessed
1424          * - The last position reached the end of the current zone.
1425          * - For reads with td->o.read_beyond_wp == false, the last position
1426          *   reached the zone write pointer.
1427          */
1428         if (td->zone_bytes >= td->o.zone_size ||
1429             f->last_pos[ddir] >= zbd_zone_end(z) ||
1430             (ddir == DDIR_READ &&
1431              (!td->o.read_beyond_wp) && f->last_pos[ddir] >= z->wp)) {
1432                 /*
1433                  * Skip zones.
1434                  */
1435                 td->zone_bytes = 0;
1436                 f->file_offset += td->o.zone_size + td->o.zone_skip;
1437
1438                 /*
1439                  * Wrap from the beginning, if we exceed the file size
1440                  */
1441                 if (f->file_offset >= f->real_file_size)
1442                         f->file_offset = get_start_offset(td, f);
1443
1444                 f->last_pos[ddir] = f->file_offset;
1445                 td->io_skip_bytes += td->o.zone_skip;
1446         }
1447 }
1448
1449 /**
1450  * zbd_adjust_ddir - Adjust an I/O direction for zonemode=zbd.
1451  *
1452  * @td: FIO thread data.
1453  * @io_u: FIO I/O unit.
1454  * @ddir: I/O direction before adjustment.
1455  *
1456  * Return adjusted I/O direction.
1457  */
1458 enum fio_ddir zbd_adjust_ddir(struct thread_data *td, struct io_u *io_u,
1459                               enum fio_ddir ddir)
1460 {
1461         /*
1462          * In case read direction is chosen for the first random I/O, fio with
1463          * zonemode=zbd stops because no data can be read from zoned block
1464          * devices with all empty zones. Overwrite the first I/O direction as
1465          * write to make sure data to read exists.
1466          */
1467         if (ddir != DDIR_READ || !td_rw(td))
1468                 return ddir;
1469
1470         if (io_u->file->zbd_info->sectors_with_data ||
1471             td->o.read_beyond_wp)
1472                 return DDIR_READ;
1473
1474         return DDIR_WRITE;
1475 }
1476
1477 /**
1478  * zbd_adjust_block - adjust the offset and length as necessary for ZBD drives
1479  * @td: FIO thread data.
1480  * @io_u: FIO I/O unit.
1481  *
1482  * Locking strategy: returns with z->mutex locked if and only if z refers
1483  * to a sequential zone and if io_u_accept is returned. z is the zone that
1484  * corresponds to io_u->offset at the end of this function.
1485  */
1486 enum io_u_action zbd_adjust_block(struct thread_data *td, struct io_u *io_u)
1487 {
1488         struct fio_file *f = io_u->file;
1489         uint32_t zone_idx_b;
1490         struct fio_zone_info *zb, *zl, *orig_zb;
1491         uint32_t orig_len = io_u->buflen;
1492         uint32_t min_bs = td->o.min_bs[io_u->ddir];
1493         uint64_t new_len;
1494         int64_t range;
1495
1496         if (!f->zbd_info)
1497                 return io_u_accept;
1498
1499         assert(min_bs);
1500         assert(is_valid_offset(f, io_u->offset));
1501         assert(io_u->buflen);
1502         zone_idx_b = zbd_zone_idx(f, io_u->offset);
1503         zb = &f->zbd_info->zone_info[zone_idx_b];
1504         orig_zb = zb;
1505
1506         /* Accept the I/O offset for conventional zones. */
1507         if (!zbd_zone_swr(zb))
1508                 return io_u_accept;
1509
1510         /*
1511          * Accept the I/O offset for reads if reading beyond the write pointer
1512          * is enabled.
1513          */
1514         if (zb->cond != ZBD_ZONE_COND_OFFLINE &&
1515             io_u->ddir == DDIR_READ && td->o.read_beyond_wp)
1516                 return io_u_accept;
1517
1518         zbd_check_swd(f);
1519
1520         zone_lock(td, f, zb);
1521
1522         switch (io_u->ddir) {
1523         case DDIR_READ:
1524                 if (td->runstate == TD_VERIFYING && td_write(td)) {
1525                         zb = zbd_replay_write_order(td, io_u, zb);
1526                         goto accept;
1527                 }
1528                 /*
1529                  * Check that there is enough written data in the zone to do an
1530                  * I/O of at least min_bs B. If there isn't, find a new zone for
1531                  * the I/O.
1532                  */
1533                 range = zb->cond != ZBD_ZONE_COND_OFFLINE ?
1534                         zb->wp - zb->start : 0;
1535                 if (range < min_bs ||
1536                     ((!td_random(td)) && (io_u->offset + min_bs > zb->wp))) {
1537                         pthread_mutex_unlock(&zb->mutex);
1538                         zl = &f->zbd_info->zone_info[f->max_zone];
1539                         zb = zbd_find_zone(td, io_u, zb, zl);
1540                         if (!zb) {
1541                                 dprint(FD_ZBD,
1542                                        "%s: zbd_find_zone(%lld, %llu) failed\n",
1543                                        f->file_name, io_u->offset,
1544                                        io_u->buflen);
1545                                 goto eof;
1546                         }
1547                         /*
1548                          * zbd_find_zone() returned a zone with a range of at
1549                          * least min_bs.
1550                          */
1551                         range = zb->wp - zb->start;
1552                         assert(range >= min_bs);
1553
1554                         if (!td_random(td))
1555                                 io_u->offset = zb->start;
1556                 }
1557                 /*
1558                  * Make sure the I/O is within the zone valid data range while
1559                  * maximizing the I/O size and preserving randomness.
1560                  */
1561                 if (range <= io_u->buflen)
1562                         io_u->offset = zb->start;
1563                 else if (td_random(td))
1564                         io_u->offset = zb->start +
1565                                 ((io_u->offset - orig_zb->start) %
1566                                  (range - io_u->buflen)) / min_bs * min_bs;
1567                 /*
1568                  * Make sure the I/O does not cross over the zone wp position.
1569                  */
1570                 new_len = min((unsigned long long)io_u->buflen,
1571                               (unsigned long long)(zb->wp - io_u->offset));
1572                 new_len = new_len / min_bs * min_bs;
1573                 if (new_len < io_u->buflen) {
1574                         io_u->buflen = new_len;
1575                         dprint(FD_IO, "Changed length from %u into %llu\n",
1576                                orig_len, io_u->buflen);
1577                 }
1578                 assert(zb->start <= io_u->offset);
1579                 assert(io_u->offset + io_u->buflen <= zb->wp);
1580                 goto accept;
1581         case DDIR_WRITE:
1582                 if (io_u->buflen > f->zbd_info->zone_size)
1583                         goto eof;
1584                 if (!zbd_open_zone(td, io_u, zone_idx_b)) {
1585                         pthread_mutex_unlock(&zb->mutex);
1586                         zb = zbd_convert_to_open_zone(td, io_u);
1587                         if (!zb)
1588                                 goto eof;
1589                         zone_idx_b = zb - f->zbd_info->zone_info;
1590                 }
1591                 /* Check whether the zone reset threshold has been exceeded */
1592                 if (td->o.zrf.u.f) {
1593                         if (f->zbd_info->sectors_with_data >=
1594                             f->io_size * td->o.zrt.u.f &&
1595                             zbd_dec_and_reset_write_cnt(td, f)) {
1596                                 zb->reset_zone = 1;
1597                         }
1598                 }
1599                 /* Reset the zone pointer if necessary */
1600                 if (zb->reset_zone || zbd_zone_full(f, zb, min_bs)) {
1601                         assert(td->o.verify == VERIFY_NONE);
1602                         /*
1603                          * Since previous write requests may have been submitted
1604                          * asynchronously and since we will submit the zone
1605                          * reset synchronously, wait until previously submitted
1606                          * write requests have completed before issuing a
1607                          * zone reset.
1608                          */
1609                         io_u_quiesce(td);
1610                         zb->reset_zone = 0;
1611                         if (zbd_reset_zone(td, f, zb) < 0)
1612                                 goto eof;
1613
1614                         if (zb->capacity < min_bs) {
1615                                 log_err("zone capacity %llu smaller than minimum block size %d\n",
1616                                         (unsigned long long)zb->capacity,
1617                                         min_bs);
1618                                 goto eof;
1619                         }
1620                 }
1621                 /* Make writes occur at the write pointer */
1622                 assert(!zbd_zone_full(f, zb, min_bs));
1623                 io_u->offset = zb->wp;
1624                 if (!is_valid_offset(f, io_u->offset)) {
1625                         dprint(FD_ZBD, "Dropped request with offset %llu\n",
1626                                io_u->offset);
1627                         goto eof;
1628                 }
1629                 /*
1630                  * Make sure that the buflen is a multiple of the minimal
1631                  * block size. Give up if shrinking would make the request too
1632                  * small.
1633                  */
1634                 new_len = min((unsigned long long)io_u->buflen,
1635                               zbd_zone_capacity_end(zb) - io_u->offset);
1636                 new_len = new_len / min_bs * min_bs;
1637                 if (new_len == io_u->buflen)
1638                         goto accept;
1639                 if (new_len >= min_bs) {
1640                         io_u->buflen = new_len;
1641                         dprint(FD_IO, "Changed length from %u into %llu\n",
1642                                orig_len, io_u->buflen);
1643                         goto accept;
1644                 }
1645                 log_err("Zone remainder %lld smaller than minimum block size %d\n",
1646                         (zbd_zone_capacity_end(zb) - io_u->offset),
1647                         min_bs);
1648                 goto eof;
1649         case DDIR_TRIM:
1650                 /* fall-through */
1651         case DDIR_SYNC:
1652         case DDIR_DATASYNC:
1653         case DDIR_SYNC_FILE_RANGE:
1654         case DDIR_WAIT:
1655         case DDIR_LAST:
1656         case DDIR_INVAL:
1657                 goto accept;
1658         }
1659
1660         assert(false);
1661
1662 accept:
1663         assert(zb);
1664         assert(zb->cond != ZBD_ZONE_COND_OFFLINE);
1665         assert(!io_u->zbd_queue_io);
1666         assert(!io_u->zbd_put_io);
1667         io_u->zbd_queue_io = zbd_queue_io;
1668         io_u->zbd_put_io = zbd_put_io;
1669         return io_u_accept;
1670
1671 eof:
1672         if (zb)
1673                 pthread_mutex_unlock(&zb->mutex);
1674         return io_u_eof;
1675 }
1676
1677 /* Return a string with ZBD statistics */
1678 char *zbd_write_status(const struct thread_stat *ts)
1679 {
1680         char *res;
1681
1682         if (asprintf(&res, "; %llu zone resets", (unsigned long long) ts->nr_zone_resets) < 0)
1683                 return NULL;
1684         return res;
1685 }