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