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