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