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