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