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