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