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