xref: /spdk/app/fio/bdev/fio_plugin.c (revision 2186fc0389db7611703e15b2131e64846c1e65a0)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2017 Intel Corporation.
3  *   All rights reserved.
4  *   Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/bdev.h"
10 #include "spdk/bdev_zone.h"
11 #include "spdk/accel.h"
12 #include "spdk/env.h"
13 #include "spdk/file.h"
14 #include "spdk/init.h"
15 #include "spdk/thread.h"
16 #include "spdk/log.h"
17 #include "spdk/string.h"
18 #include "spdk/queue.h"
19 #include "spdk/util.h"
20 #include "spdk/rpc.h"
21 
22 #include "spdk_internal/event.h"
23 
24 #include "config-host.h"
25 #include "fio.h"
26 #include "optgroup.h"
27 
28 #ifdef for_each_rw_ddir
29 #define FIO_HAS_ZBD (FIO_IOOPS_VERSION >= 26)
30 #else
31 #define FIO_HAS_ZBD (0)
32 #endif
33 
34 /* FreeBSD is missing CLOCK_MONOTONIC_RAW,
35  * so alternative is provided. */
36 #ifndef CLOCK_MONOTONIC_RAW /* Defined in glibc bits/time.h */
37 #define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
38 #endif
39 
40 struct spdk_fio_options {
41 	void *pad;
42 	char *conf;
43 	char *json_conf;
44 	char *env_context;
45 	char *log_flags;
46 	unsigned mem_mb;
47 	int mem_single_seg;
48 	int initial_zone_reset;
49 	int zone_append;
50 	char *rpc_listen_addr;
51 };
52 
53 struct spdk_fio_request {
54 	struct io_u		*io;
55 	struct thread_data	*td;
56 };
57 
58 struct spdk_fio_target {
59 	struct spdk_bdev	*bdev;
60 	struct spdk_bdev_desc	*desc;
61 	struct spdk_io_channel	*ch;
62 	bool zone_append_enabled;
63 
64 	TAILQ_ENTRY(spdk_fio_target) link;
65 };
66 
67 struct spdk_fio_thread {
68 	struct thread_data		*td; /* fio thread context */
69 	struct spdk_thread		*thread; /* spdk thread context */
70 
71 	TAILQ_HEAD(, spdk_fio_target)	targets;
72 	bool				failed; /* true if the thread failed to initialize */
73 
74 	struct io_u		**iocq;		/* io completion queue */
75 	unsigned int		iocq_count;	/* number of iocq entries filled by last getevents */
76 	unsigned int		iocq_size;	/* number of iocq entries allocated */
77 
78 	TAILQ_ENTRY(spdk_fio_thread)	link;
79 };
80 
81 struct spdk_fio_zone_cb_arg {
82 	struct spdk_fio_target *target;
83 	struct spdk_bdev_zone_info *spdk_zones;
84 	int completed;
85 	uint64_t offset_blocks;
86 	struct zbd_zone *fio_zones;
87 	unsigned int nr_zones;
88 };
89 
90 /* On App Thread (oat) context used for making sync calls from async calls. */
91 struct spdk_fio_oat_ctx {
92 	union {
93 		struct spdk_fio_setup_args {
94 			struct thread_data *td;
95 		} sa;
96 		struct spdk_fio_bdev_get_zoned_model_args {
97 			struct fio_file *f;
98 			enum zbd_zoned_model *model;
99 		} zma;
100 		struct spdk_fio_bdev_get_max_open_zones_args {
101 			struct fio_file *f;
102 			unsigned int *max_open_zones;
103 		} moza;
104 	} u;
105 	pthread_mutex_t mutex;
106 	pthread_cond_t cond;
107 	int ret;
108 };
109 
110 static bool g_spdk_env_initialized = false;
111 static const char *g_json_config_file = NULL;
112 static void *g_json_data;
113 static size_t g_json_data_size;
114 static const char *g_rpc_listen_addr = NULL;
115 
116 static int spdk_fio_init(struct thread_data *td);
117 static void spdk_fio_cleanup(struct thread_data *td);
118 static size_t spdk_fio_poll_thread(struct spdk_fio_thread *fio_thread);
119 static int spdk_fio_handle_options(struct thread_data *td, struct fio_file *f,
120 				   struct spdk_bdev *bdev);
121 static int spdk_fio_handle_options_per_target(struct thread_data *td, struct fio_file *f);
122 static void spdk_fio_setup_oat(void *ctx);
123 
124 static pthread_t g_init_thread_id = 0;
125 static pthread_mutex_t g_init_mtx = PTHREAD_MUTEX_INITIALIZER;
126 static pthread_cond_t g_init_cond;
127 static bool g_poll_loop = true;
128 static TAILQ_HEAD(, spdk_fio_thread) g_threads = TAILQ_HEAD_INITIALIZER(g_threads);
129 
130 /* Default polling timeout (ns) */
131 #define SPDK_FIO_POLLING_TIMEOUT 1000000000ULL
132 
133 static __thread bool g_internal_thread = false;
134 
135 /* Run msg_fn on app thread ("oat") and wait for it to call spdk_fio_wake_oat_waiter() */
136 static void
137 spdk_fio_sync_run_oat(void (*msg_fn)(void *), struct spdk_fio_oat_ctx *ctx)
138 {
139 	assert(!spdk_thread_is_app_thread(NULL));
140 
141 	pthread_mutex_init(&ctx->mutex, NULL);
142 	pthread_cond_init(&ctx->cond, NULL);
143 	pthread_mutex_lock(&ctx->mutex);
144 
145 	spdk_thread_send_msg(spdk_thread_get_app_thread(), msg_fn, ctx);
146 
147 	/* Wake up the poll loop in spdk_init_thread_poll() */
148 	pthread_mutex_lock(&g_init_mtx);
149 	pthread_cond_signal(&g_init_cond);
150 	pthread_mutex_unlock(&g_init_mtx);
151 
152 	/* Wait for msg_fn() to call spdk_fio_wake_oat_waiter() */
153 	pthread_cond_wait(&ctx->cond, &ctx->mutex);
154 	pthread_mutex_unlock(&ctx->mutex);
155 
156 	pthread_mutex_destroy(&ctx->mutex);
157 	pthread_cond_destroy(&ctx->cond);
158 }
159 
160 static void
161 spdk_fio_wake_oat_waiter(struct spdk_fio_oat_ctx *ctx)
162 {
163 	pthread_mutex_lock(&ctx->mutex);
164 	pthread_cond_signal(&ctx->cond);
165 	pthread_mutex_unlock(&ctx->mutex);
166 }
167 
168 static int
169 spdk_fio_schedule_thread(struct spdk_thread *thread)
170 {
171 	struct spdk_fio_thread *fio_thread;
172 
173 	if (g_internal_thread) {
174 		/* Do nothing. */
175 		return 0;
176 	}
177 
178 	fio_thread = spdk_thread_get_ctx(thread);
179 
180 	pthread_mutex_lock(&g_init_mtx);
181 	TAILQ_INSERT_TAIL(&g_threads, fio_thread, link);
182 	pthread_mutex_unlock(&g_init_mtx);
183 
184 	return 0;
185 }
186 
187 static int
188 spdk_fio_init_thread(struct thread_data *td)
189 {
190 	struct spdk_fio_thread *fio_thread;
191 	struct spdk_thread *thread;
192 
193 	g_internal_thread = true;
194 	thread = spdk_thread_create("fio_thread", NULL);
195 	g_internal_thread = false;
196 	if (!thread) {
197 		SPDK_ERRLOG("failed to allocate thread\n");
198 		return -1;
199 	}
200 
201 	fio_thread = spdk_thread_get_ctx(thread);
202 	fio_thread->td = td;
203 	fio_thread->thread = thread;
204 	td->io_ops_data = fio_thread;
205 
206 	spdk_set_thread(thread);
207 
208 	fio_thread->iocq_size = td->o.iodepth;
209 	fio_thread->iocq = calloc(fio_thread->iocq_size, sizeof(struct io_u *));
210 	assert(fio_thread->iocq != NULL);
211 
212 	TAILQ_INIT(&fio_thread->targets);
213 
214 	return 0;
215 }
216 
217 static void
218 spdk_fio_bdev_close_targets(void *arg)
219 {
220 	struct spdk_fio_thread *fio_thread = arg;
221 	struct spdk_fio_target *target, *tmp;
222 
223 	TAILQ_FOREACH_SAFE(target, &fio_thread->targets, link, tmp) {
224 		TAILQ_REMOVE(&fio_thread->targets, target, link);
225 		spdk_put_io_channel(target->ch);
226 		spdk_bdev_close(target->desc);
227 		free(target);
228 	}
229 }
230 
231 static void
232 spdk_fio_cleanup_thread(struct spdk_fio_thread *fio_thread)
233 {
234 	spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_close_targets, fio_thread);
235 
236 	pthread_mutex_lock(&g_init_mtx);
237 	TAILQ_INSERT_TAIL(&g_threads, fio_thread, link);
238 	pthread_mutex_unlock(&g_init_mtx);
239 }
240 
241 static void
242 spdk_fio_calc_timeout(struct spdk_fio_thread *fio_thread, struct timespec *ts)
243 {
244 	uint64_t timeout, now;
245 
246 	if (spdk_thread_has_active_pollers(fio_thread->thread)) {
247 		return;
248 	}
249 
250 	timeout = spdk_thread_next_poller_expiration(fio_thread->thread);
251 	now = spdk_get_ticks();
252 
253 	if (timeout == 0) {
254 		timeout = now + (SPDK_FIO_POLLING_TIMEOUT * spdk_get_ticks_hz()) / SPDK_SEC_TO_NSEC;
255 	}
256 
257 	if (timeout > now) {
258 		timeout = ((timeout - now) * SPDK_SEC_TO_NSEC) / spdk_get_ticks_hz() +
259 			  ts->tv_sec * SPDK_SEC_TO_NSEC + ts->tv_nsec;
260 
261 		ts->tv_sec  = timeout / SPDK_SEC_TO_NSEC;
262 		ts->tv_nsec = timeout % SPDK_SEC_TO_NSEC;
263 	}
264 }
265 
266 static void
267 spdk_fio_bdev_init_done(int rc, void *cb_arg)
268 {
269 	*(bool *)cb_arg = true;
270 
271 	free(g_json_data);
272 	if (rc) {
273 		SPDK_ERRLOG("RUNTIME RPCs failed\n");
274 		exit(1);
275 	}
276 }
277 
278 static void
279 spdk_fio_bdev_subsystem_init_done(int rc, void *cb_arg)
280 {
281 	if (rc) {
282 		SPDK_ERRLOG("subsystem init failed\n");
283 		exit(1);
284 	}
285 
286 	spdk_rpc_set_state(SPDK_RPC_RUNTIME);
287 	spdk_subsystem_load_config(g_json_data, g_json_data_size,
288 				   spdk_fio_bdev_init_done, cb_arg, true);
289 }
290 
291 static void
292 spdk_fio_bdev_startup_done(int rc, void *cb_arg)
293 {
294 	if (rc) {
295 		SPDK_ERRLOG("STARTUP RPCs failed\n");
296 		exit(1);
297 	}
298 
299 	if (g_rpc_listen_addr != NULL) {
300 		if (spdk_rpc_initialize(g_rpc_listen_addr, NULL) != 0) {
301 			SPDK_ERRLOG("could not initialize RPC address %s\n", g_rpc_listen_addr);
302 			exit(1);
303 		}
304 	}
305 
306 	spdk_subsystem_init(spdk_fio_bdev_subsystem_init_done, cb_arg);
307 }
308 
309 static void
310 spdk_fio_bdev_init_start(void *arg)
311 {
312 	bool *done = arg;
313 
314 	g_json_data = spdk_posix_file_load_from_name(g_json_config_file, &g_json_data_size);
315 
316 	if (g_json_data == NULL) {
317 		SPDK_ERRLOG("could not allocate buffer for json config file\n");
318 		exit(1);
319 	}
320 
321 	/* Load SPDK_RPC_STARTUP RPCs from config file */
322 	assert(spdk_rpc_get_state() == SPDK_RPC_STARTUP);
323 	spdk_subsystem_load_config(g_json_data, g_json_data_size,
324 				   spdk_fio_bdev_startup_done, done, true);
325 }
326 
327 static void
328 spdk_fio_bdev_fini_done(void *cb_arg)
329 {
330 	*(bool *)cb_arg = true;
331 
332 	spdk_rpc_finish();
333 }
334 
335 static void
336 spdk_fio_bdev_fini_start(void *arg)
337 {
338 	bool *done = arg;
339 
340 	spdk_subsystem_fini(spdk_fio_bdev_fini_done, done);
341 }
342 
343 static void *
344 spdk_init_thread_poll(void *arg)
345 {
346 	struct spdk_fio_options		*eo = arg;
347 	struct spdk_fio_thread		*fio_thread;
348 	struct spdk_fio_thread		*thread, *tmp;
349 	struct spdk_env_opts		opts;
350 	bool				done;
351 	int				rc;
352 	struct timespec			ts;
353 	struct thread_data		td = {};
354 
355 	/* Create a dummy thread data for use on the initialization thread. */
356 	td.o.iodepth = 32;
357 	td.eo = eo;
358 
359 	/* Parse the SPDK configuration file */
360 	eo = arg;
361 
362 	if (eo->conf && eo->json_conf) {
363 		SPDK_ERRLOG("Cannot provide two types of configuration files\n");
364 		rc = EINVAL;
365 		goto err_exit;
366 	} else if (eo->conf && strlen(eo->conf)) {
367 		g_json_config_file = eo->conf;
368 	} else if (eo->json_conf && strlen(eo->json_conf)) {
369 		g_json_config_file = eo->json_conf;
370 	} else {
371 		SPDK_ERRLOG("No configuration file provided\n");
372 		rc = EINVAL;
373 		goto err_exit;
374 	}
375 
376 	/* Initialize the RPC listen address */
377 	if (eo->rpc_listen_addr) {
378 		g_rpc_listen_addr = eo->rpc_listen_addr;
379 	}
380 
381 	/* Initialize the environment library */
382 	opts.opts_size = sizeof(opts);
383 	spdk_env_opts_init(&opts);
384 	opts.name = "fio";
385 
386 	if (eo->mem_mb) {
387 		opts.mem_size = eo->mem_mb;
388 	}
389 	opts.hugepage_single_segments = eo->mem_single_seg;
390 	if (eo->env_context) {
391 		opts.env_context = eo->env_context;
392 	}
393 
394 	if (spdk_env_init(&opts) < 0) {
395 		SPDK_ERRLOG("Unable to initialize SPDK env\n");
396 		rc = EINVAL;
397 		goto err_exit;
398 	}
399 	spdk_unaffinitize_thread();
400 
401 	if (eo->log_flags) {
402 		char *tok = strtok(eo->log_flags, ",");
403 		do {
404 			rc = spdk_log_set_flag(tok);
405 			if (rc < 0) {
406 				SPDK_ERRLOG("unknown spdk log flag %s\n", tok);
407 				rc = EINVAL;
408 				goto err_exit;
409 			}
410 		} while ((tok = strtok(NULL, ",")) != NULL);
411 #ifdef DEBUG
412 		spdk_log_set_print_level(SPDK_LOG_DEBUG);
413 #endif
414 	}
415 
416 	spdk_thread_lib_init(spdk_fio_schedule_thread, sizeof(struct spdk_fio_thread));
417 
418 	/* Create an SPDK thread temporarily */
419 	rc = spdk_fio_init_thread(&td);
420 	if (rc < 0) {
421 		SPDK_ERRLOG("Failed to create initialization thread\n");
422 		goto err_exit;
423 	}
424 
425 	fio_thread = td.io_ops_data;
426 
427 	/* Initialize the bdev layer */
428 	done = false;
429 	spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_init_start, &done);
430 
431 	do {
432 		spdk_fio_poll_thread(fio_thread);
433 	} while (!done);
434 
435 	/*
436 	 * Continue polling until there are no more events.
437 	 * This handles any final events posted by pollers.
438 	 */
439 	while (spdk_fio_poll_thread(fio_thread) > 0) {};
440 
441 	/* Set condition variable */
442 	pthread_mutex_lock(&g_init_mtx);
443 	pthread_cond_signal(&g_init_cond);
444 
445 	pthread_mutex_unlock(&g_init_mtx);
446 
447 	while (g_poll_loop) {
448 		spdk_fio_poll_thread(fio_thread);
449 
450 		pthread_mutex_lock(&g_init_mtx);
451 		if (!TAILQ_EMPTY(&g_threads)) {
452 			TAILQ_FOREACH_SAFE(thread, &g_threads, link, tmp) {
453 				if (spdk_thread_is_exited(thread->thread)) {
454 					TAILQ_REMOVE(&g_threads, thread, link);
455 					free(thread->iocq);
456 					spdk_thread_destroy(thread->thread);
457 				} else {
458 					spdk_fio_poll_thread(thread);
459 				}
460 			}
461 
462 			/* If there are exiting threads to poll, don't sleep. */
463 			pthread_mutex_unlock(&g_init_mtx);
464 			continue;
465 		}
466 
467 		/* Figure out how long to sleep. */
468 		clock_gettime(CLOCK_MONOTONIC, &ts);
469 		spdk_fio_calc_timeout(fio_thread, &ts);
470 
471 		rc = pthread_cond_timedwait(&g_init_cond, &g_init_mtx, &ts);
472 		pthread_mutex_unlock(&g_init_mtx);
473 
474 		if (rc != 0 && rc != ETIMEDOUT) {
475 			break;
476 		}
477 	}
478 
479 	spdk_fio_cleanup_thread(fio_thread);
480 
481 	/* Finalize the bdev layer */
482 	done = false;
483 	spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_fini_start, &done);
484 
485 	do {
486 		spdk_fio_poll_thread(fio_thread);
487 
488 		TAILQ_FOREACH_SAFE(thread, &g_threads, link, tmp) {
489 			spdk_fio_poll_thread(thread);
490 		}
491 	} while (!done);
492 
493 	/* Now exit all the threads */
494 	TAILQ_FOREACH(thread, &g_threads, link) {
495 		spdk_set_thread(thread->thread);
496 		spdk_thread_exit(thread->thread);
497 		spdk_set_thread(NULL);
498 	}
499 
500 	/* And wait for them to gracefully exit */
501 	while (!TAILQ_EMPTY(&g_threads)) {
502 		TAILQ_FOREACH_SAFE(thread, &g_threads, link, tmp) {
503 			if (spdk_thread_is_exited(thread->thread)) {
504 				TAILQ_REMOVE(&g_threads, thread, link);
505 				free(thread->iocq);
506 				spdk_thread_destroy(thread->thread);
507 			} else {
508 				spdk_thread_poll(thread->thread, 0, 0);
509 			}
510 		}
511 	}
512 
513 	pthread_exit(NULL);
514 
515 err_exit:
516 	exit(rc);
517 	return NULL;
518 }
519 
520 static int
521 spdk_fio_init_env(struct thread_data *td)
522 {
523 	pthread_condattr_t attr;
524 	int rc = -1;
525 
526 	if (pthread_condattr_init(&attr)) {
527 		SPDK_ERRLOG("Unable to initialize condition variable\n");
528 		return -1;
529 	}
530 
531 	if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) {
532 		SPDK_ERRLOG("Unable to initialize condition variable\n");
533 		goto out;
534 	}
535 
536 	if (pthread_cond_init(&g_init_cond, &attr)) {
537 		SPDK_ERRLOG("Unable to initialize condition variable\n");
538 		goto out;
539 	}
540 
541 	/*
542 	 * Spawn a thread to handle initialization operations and to poll things
543 	 * like the admin queues periodically.
544 	 */
545 	rc = pthread_create(&g_init_thread_id, NULL, &spdk_init_thread_poll, td->eo);
546 	if (rc != 0) {
547 		SPDK_ERRLOG("Unable to spawn thread to poll admin queue. It won't be polled.\n");
548 	}
549 
550 	/* Wait for background thread to advance past the initialization */
551 	pthread_mutex_lock(&g_init_mtx);
552 	pthread_cond_wait(&g_init_cond, &g_init_mtx);
553 	pthread_mutex_unlock(&g_init_mtx);
554 out:
555 	pthread_condattr_destroy(&attr);
556 	return rc;
557 }
558 
559 static bool
560 fio_redirected_to_dev_null(void)
561 {
562 	char path[PATH_MAX] = "";
563 	ssize_t ret;
564 
565 	ret = readlink("/proc/self/fd/1", path, sizeof(path));
566 
567 	if (ret == -1 || strcmp(path, "/dev/null") != 0) {
568 		return false;
569 	}
570 
571 	ret = readlink("/proc/self/fd/2", path, sizeof(path));
572 
573 	if (ret == -1 || strcmp(path, "/dev/null") != 0) {
574 		return false;
575 	}
576 
577 	return true;
578 }
579 
580 static int
581 spdk_fio_init_spdk_env(struct thread_data *td)
582 {
583 	static pthread_mutex_t setup_lock = PTHREAD_MUTEX_INITIALIZER;
584 
585 	pthread_mutex_lock(&setup_lock);
586 	if (!g_spdk_env_initialized) {
587 		if (spdk_fio_init_env(td)) {
588 			pthread_mutex_unlock(&setup_lock);
589 			SPDK_ERRLOG("failed to initialize\n");
590 			return -1;
591 		}
592 
593 		g_spdk_env_initialized = true;
594 	}
595 	pthread_mutex_unlock(&setup_lock);
596 
597 	return 0;
598 }
599 
600 /* Called for each thread to fill in the 'real_file_size' member for
601  * each file associated with this thread. This is called prior to
602  * the init operation (spdk_fio_init()) below. This call will occur
603  * on the initial start up thread if 'create_serialize' is true, or
604  * on the thread actually associated with 'thread_data' if 'create_serialize'
605  * is false.
606  */
607 static int
608 spdk_fio_setup(struct thread_data *td)
609 {
610 	struct spdk_fio_oat_ctx ctx = { 0 };
611 
612 	/*
613 	 * If we're running in a daemonized FIO instance, it's possible
614 	 * fd 1/2 were re-used for something important by FIO. Newer fio
615 	 * versions are careful to redirect those to /dev/null, but if we're
616 	 * not, we'll abort early, so we don't accidentally write messages to
617 	 * an important file, etc.
618 	 */
619 	if (is_backend && !fio_redirected_to_dev_null()) {
620 		char buf[1024];
621 		snprintf(buf, sizeof(buf),
622 			 "SPDK FIO plugin is in daemon mode, but stdout/stderr "
623 			 "aren't redirected to /dev/null. Aborting.");
624 		fio_server_text_output(FIO_LOG_ERR, buf, sizeof(buf));
625 		return -1;
626 	}
627 
628 	if (!td->o.use_thread) {
629 		SPDK_ERRLOG("must set thread=1 when using spdk plugin\n");
630 		return -1;
631 	}
632 
633 	if (spdk_fio_init_spdk_env(td) != 0) {
634 		return -1;
635 	}
636 
637 	ctx.u.sa.td = td;
638 	spdk_fio_sync_run_oat(spdk_fio_setup_oat, &ctx);
639 	return ctx.ret;
640 }
641 
642 static int
643 _spdk_fio_add_file(void *ctx, struct spdk_bdev *bdev)
644 {
645 	struct thread_data *td = ctx;
646 
647 	add_file(td, spdk_bdev_get_name(bdev), 0, 1);
648 	return 0;
649 }
650 
651 static void
652 spdk_fio_setup_oat(void *_ctx)
653 {
654 	struct spdk_fio_oat_ctx *ctx = _ctx;
655 	struct thread_data *td = ctx->u.sa.td;
656 	unsigned int i;
657 	struct fio_file *f;
658 
659 	if (td->o.nr_files == 1 && strcmp(td->files[0]->file_name, "*") == 0) {
660 		/* add all available bdevs as fio targets */
661 		spdk_for_each_bdev_leaf(td, _spdk_fio_add_file);
662 	}
663 
664 	for_each_file(td, f, i) {
665 		struct spdk_bdev *bdev;
666 
667 		if (strcmp(f->file_name, "*") == 0) {
668 			/* Explicitly set file size to 0 here to make sure fio doesn't try to
669 			 * actually send I/O to this "*" file.
670 			 */
671 			f->real_file_size = 0;
672 			continue;
673 		}
674 
675 		bdev = spdk_bdev_get_by_name(f->file_name);
676 		if (!bdev) {
677 			SPDK_ERRLOG("Unable to find bdev with name %s\n", f->file_name);
678 			ctx->ret = -1;
679 			goto out;
680 		}
681 
682 		f->real_file_size = spdk_bdev_get_num_blocks(bdev) *
683 				    spdk_bdev_get_block_size(bdev);
684 		f->filetype = FIO_TYPE_BLOCK;
685 		fio_file_set_size_known(f);
686 
687 		ctx->ret = spdk_fio_handle_options(td, f, bdev);
688 		if (ctx->ret) {
689 			goto out;
690 		}
691 	}
692 
693 	ctx->ret = 0;
694 out:
695 	spdk_fio_wake_oat_waiter(ctx);
696 }
697 
698 static void
699 fio_bdev_event_cb(enum spdk_bdev_event_type type, struct spdk_bdev *bdev,
700 		  void *event_ctx)
701 {
702 	SPDK_WARNLOG("Unsupported bdev event: type %d\n", type);
703 }
704 
705 static void
706 spdk_fio_bdev_open(void *arg)
707 {
708 	struct thread_data *td = arg;
709 	struct spdk_fio_thread *fio_thread;
710 	unsigned int i;
711 	struct fio_file *f;
712 	int rc;
713 
714 	fio_thread = td->io_ops_data;
715 
716 	for_each_file(td, f, i) {
717 		struct spdk_fio_target *target;
718 
719 		if (strcmp(f->file_name, "*") == 0) {
720 			continue;
721 		}
722 
723 		target = calloc(1, sizeof(*target));
724 		if (!target) {
725 			SPDK_ERRLOG("Unable to allocate memory for I/O target.\n");
726 			fio_thread->failed = true;
727 			return;
728 		}
729 
730 		rc = spdk_bdev_open_ext(f->file_name, true, fio_bdev_event_cb, NULL,
731 					&target->desc);
732 		if (rc) {
733 			SPDK_ERRLOG("Unable to open bdev %s\n", f->file_name);
734 			free(target);
735 			fio_thread->failed = true;
736 			return;
737 		}
738 
739 		target->bdev = spdk_bdev_desc_get_bdev(target->desc);
740 
741 		target->ch = spdk_bdev_get_io_channel(target->desc);
742 		if (!target->ch) {
743 			SPDK_ERRLOG("Unable to get I/O channel for bdev.\n");
744 			spdk_bdev_close(target->desc);
745 			free(target);
746 			fio_thread->failed = true;
747 			return;
748 		}
749 
750 		f->engine_data = target;
751 
752 		rc = spdk_fio_handle_options_per_target(td, f);
753 		if (rc) {
754 			SPDK_ERRLOG("Failed to handle options for: %s\n", f->file_name);
755 			f->engine_data = NULL;
756 			spdk_put_io_channel(target->ch);
757 			spdk_bdev_close(target->desc);
758 			free(target);
759 			fio_thread->failed = true;
760 			return;
761 		}
762 
763 		TAILQ_INSERT_TAIL(&fio_thread->targets, target, link);
764 	}
765 }
766 
767 /* Called for each thread, on that thread, shortly after the thread
768  * starts.
769  *
770  * Also called by spdk_fio_report_zones(), since we need an I/O channel
771  * in order to get the zone report. (fio calls the .report_zones callback
772  * before it calls the .init callback.)
773  * Therefore, if fio was run with --zonemode=zbd, the thread will already
774  * be initialized by the time that fio calls the .init callback.
775  */
776 static int
777 spdk_fio_init(struct thread_data *td)
778 {
779 	struct spdk_fio_thread *fio_thread;
780 	int rc;
781 
782 	if (spdk_fio_init_spdk_env(td) != 0) {
783 		return -1;
784 	}
785 
786 	/* If thread has already been initialized, do nothing. */
787 	if (td->io_ops_data) {
788 		return 0;
789 	}
790 
791 	rc = spdk_fio_init_thread(td);
792 	if (rc) {
793 		return rc;
794 	}
795 
796 	fio_thread = td->io_ops_data;
797 	assert(fio_thread);
798 	fio_thread->failed = false;
799 
800 	spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_open, td);
801 
802 	while (spdk_fio_poll_thread(fio_thread) > 0) {}
803 
804 	if (fio_thread->failed) {
805 		return -1;
806 	}
807 
808 	return 0;
809 }
810 
811 static void
812 spdk_fio_cleanup(struct thread_data *td)
813 {
814 	struct spdk_fio_thread *fio_thread = td->io_ops_data;
815 
816 	spdk_fio_cleanup_thread(fio_thread);
817 	td->io_ops_data = NULL;
818 }
819 
820 static int
821 spdk_fio_open(struct thread_data *td, struct fio_file *f)
822 {
823 
824 	return 0;
825 }
826 
827 static int
828 spdk_fio_close(struct thread_data *td, struct fio_file *f)
829 {
830 	return 0;
831 }
832 
833 static int
834 spdk_fio_iomem_alloc(struct thread_data *td, size_t total_mem)
835 {
836 	struct spdk_fio_thread	*fio_thread = td->io_ops_data;
837 	struct spdk_fio_target	*fio_target;
838 	int32_t numa_id = SPDK_ENV_NUMA_ID_ANY, tmp_numa_id;
839 
840 	/* If all bdevs used by this fio_thread have the same numa socket
841 	 * id, allocate from that socket. If they come from different numa
842 	 * sockets, then don't try to optimize and just use NUMA_ID_ANY.
843 	 */
844 	TAILQ_FOREACH(fio_target, &fio_thread->targets, link) {
845 		tmp_numa_id = spdk_bdev_get_numa_id(fio_target->bdev);
846 		if (numa_id == SPDK_ENV_NUMA_ID_ANY) {
847 			numa_id = tmp_numa_id;
848 		} else if (tmp_numa_id != numa_id &&
849 			   tmp_numa_id != SPDK_ENV_NUMA_ID_ANY) {
850 			numa_id = SPDK_ENV_NUMA_ID_ANY;
851 			break;
852 		}
853 	}
854 
855 	td->orig_buffer = spdk_dma_zmalloc_socket(total_mem, 0x1000, NULL, numa_id);
856 	return td->orig_buffer == NULL;
857 }
858 
859 static void
860 spdk_fio_iomem_free(struct thread_data *td)
861 {
862 	spdk_dma_free(td->orig_buffer);
863 }
864 
865 static int
866 spdk_fio_io_u_init(struct thread_data *td, struct io_u *io_u)
867 {
868 	struct spdk_fio_request	*fio_req;
869 
870 	io_u->engine_data = NULL;
871 
872 	fio_req = calloc(1, sizeof(*fio_req));
873 	if (fio_req == NULL) {
874 		return 1;
875 	}
876 	fio_req->io = io_u;
877 	fio_req->td = td;
878 
879 	io_u->engine_data = fio_req;
880 
881 	return 0;
882 }
883 
884 static void
885 spdk_fio_io_u_free(struct thread_data *td, struct io_u *io_u)
886 {
887 	struct spdk_fio_request *fio_req = io_u->engine_data;
888 
889 	if (fio_req) {
890 		assert(fio_req->io == io_u);
891 		free(fio_req);
892 		io_u->engine_data = NULL;
893 	}
894 }
895 
896 static void
897 spdk_fio_completion_cb(struct spdk_bdev_io *bdev_io,
898 		       bool success,
899 		       void *cb_arg)
900 {
901 	struct spdk_fio_request		*fio_req = cb_arg;
902 	struct thread_data		*td = fio_req->td;
903 	struct spdk_fio_thread		*fio_thread = td->io_ops_data;
904 
905 	assert(fio_thread->iocq_count < fio_thread->iocq_size);
906 	fio_req->io->error = success ? 0 : EIO;
907 	fio_thread->iocq[fio_thread->iocq_count++] = fio_req->io;
908 
909 	spdk_bdev_free_io(bdev_io);
910 }
911 
912 #if FIO_IOOPS_VERSION >= 24
913 typedef enum fio_q_status fio_q_status_t;
914 #else
915 typedef int fio_q_status_t;
916 #endif
917 
918 static uint64_t
919 spdk_fio_zone_bytes_to_blocks(struct spdk_bdev *bdev, uint64_t offset_bytes, uint64_t *zone_start,
920 			      uint64_t num_bytes, uint64_t *num_blocks)
921 {
922 	uint32_t block_size = spdk_bdev_get_block_size(bdev);
923 	*zone_start = spdk_bdev_get_zone_id(bdev, offset_bytes / block_size);
924 	*num_blocks = num_bytes / block_size;
925 	return (offset_bytes % block_size) | (num_bytes % block_size);
926 }
927 
928 static fio_q_status_t
929 spdk_fio_queue(struct thread_data *td, struct io_u *io_u)
930 {
931 	int rc = 1;
932 	struct spdk_fio_request	*fio_req = io_u->engine_data;
933 	struct spdk_fio_target *target = io_u->file->engine_data;
934 
935 	assert(fio_req->td == td);
936 
937 	if (!target) {
938 		SPDK_ERRLOG("Unable to look up correct I/O target.\n");
939 		fio_req->io->error = ENODEV;
940 		return FIO_Q_COMPLETED;
941 	}
942 
943 	switch (io_u->ddir) {
944 	case DDIR_READ:
945 		rc = spdk_bdev_read(target->desc, target->ch,
946 				    io_u->buf, io_u->offset, io_u->xfer_buflen,
947 				    spdk_fio_completion_cb, fio_req);
948 		break;
949 	case DDIR_WRITE:
950 		if (!target->zone_append_enabled) {
951 			rc = spdk_bdev_write(target->desc, target->ch,
952 					     io_u->buf, io_u->offset, io_u->xfer_buflen,
953 					     spdk_fio_completion_cb, fio_req);
954 		} else {
955 			uint64_t zone_start, num_blocks;
956 			if (spdk_fio_zone_bytes_to_blocks(target->bdev, io_u->offset, &zone_start,
957 							  io_u->xfer_buflen, &num_blocks) != 0) {
958 				rc = -EINVAL;
959 				break;
960 			}
961 			rc = spdk_bdev_zone_append(target->desc, target->ch, io_u->buf,
962 						   zone_start, num_blocks, spdk_fio_completion_cb,
963 						   fio_req);
964 		}
965 		break;
966 	case DDIR_TRIM:
967 		rc = spdk_bdev_unmap(target->desc, target->ch,
968 				     io_u->offset, io_u->xfer_buflen,
969 				     spdk_fio_completion_cb, fio_req);
970 		break;
971 	case DDIR_SYNC:
972 		rc = spdk_bdev_flush(target->desc, target->ch,
973 				     io_u->offset, io_u->xfer_buflen,
974 				     spdk_fio_completion_cb, fio_req);
975 		break;
976 	default:
977 		assert(false);
978 		break;
979 	}
980 
981 	if (rc == -ENOMEM) {
982 		return FIO_Q_BUSY;
983 	}
984 
985 	if (rc != 0) {
986 		fio_req->io->error = abs(rc);
987 		return FIO_Q_COMPLETED;
988 	}
989 
990 	return FIO_Q_QUEUED;
991 }
992 
993 static struct io_u *
994 spdk_fio_event(struct thread_data *td, int event)
995 {
996 	struct spdk_fio_thread *fio_thread = td->io_ops_data;
997 
998 	assert(event >= 0);
999 	assert((unsigned)event < fio_thread->iocq_count);
1000 	return fio_thread->iocq[event];
1001 }
1002 
1003 static size_t
1004 spdk_fio_poll_thread(struct spdk_fio_thread *fio_thread)
1005 {
1006 	return spdk_thread_poll(fio_thread->thread, 0, 0);
1007 }
1008 
1009 static int
1010 spdk_fio_getevents(struct thread_data *td, unsigned int min,
1011 		   unsigned int max, const struct timespec *t)
1012 {
1013 	struct spdk_fio_thread *fio_thread = td->io_ops_data;
1014 	struct timespec t0, t1;
1015 	uint64_t timeout = 0;
1016 
1017 	if (t) {
1018 		timeout = t->tv_sec * SPDK_SEC_TO_NSEC + t->tv_nsec;
1019 		clock_gettime(CLOCK_MONOTONIC_RAW, &t0);
1020 	}
1021 
1022 	fio_thread->iocq_count = 0;
1023 
1024 	for (;;) {
1025 		spdk_fio_poll_thread(fio_thread);
1026 
1027 		if (fio_thread->iocq_count >= min) {
1028 			return fio_thread->iocq_count;
1029 		}
1030 
1031 		if (t) {
1032 			clock_gettime(CLOCK_MONOTONIC_RAW, &t1);
1033 			uint64_t elapse = ((t1.tv_sec - t0.tv_sec) * SPDK_SEC_TO_NSEC)
1034 					  + t1.tv_nsec - t0.tv_nsec;
1035 			if (elapse > timeout) {
1036 				break;
1037 			}
1038 		}
1039 	}
1040 
1041 	return fio_thread->iocq_count;
1042 }
1043 
1044 static int
1045 spdk_fio_invalidate(struct thread_data *td, struct fio_file *f)
1046 {
1047 	/* TODO: This should probably send a flush to the device, but for now just return successful. */
1048 	return 0;
1049 }
1050 
1051 #if FIO_HAS_ZBD
1052 /* Runs on app thread (oat) */
1053 static void
1054 spdk_fio_get_zoned_model_oat(void *arg)
1055 {
1056 	struct spdk_fio_oat_ctx *ctx = arg;
1057 	struct fio_file *f = ctx->u.zma.f;
1058 	enum zbd_zoned_model *model = ctx->u.zma.model;
1059 	struct spdk_bdev *bdev;
1060 
1061 	if (f->filetype != FIO_TYPE_BLOCK) {
1062 		SPDK_ERRLOG("Unsupported filetype: %d\n", f->filetype);
1063 		ctx->ret = -EINVAL;
1064 		goto out;
1065 	}
1066 
1067 	bdev = spdk_bdev_get_by_name(f->file_name);
1068 	if (!bdev) {
1069 		SPDK_ERRLOG("Cannot get zoned model, no bdev with name: %s\n", f->file_name);
1070 		ctx->ret = -ENODEV;
1071 		goto out;
1072 	}
1073 
1074 	if (spdk_bdev_is_zoned(bdev)) {
1075 		*model = ZBD_HOST_MANAGED;
1076 	} else {
1077 		*model = ZBD_NONE;
1078 	}
1079 
1080 	ctx->ret = 0;
1081 out:
1082 	spdk_fio_wake_oat_waiter(ctx);
1083 }
1084 
1085 static int
1086 spdk_fio_get_zoned_model(struct thread_data *td, struct fio_file *f, enum zbd_zoned_model *model)
1087 {
1088 	struct spdk_fio_oat_ctx ctx = { 0 };
1089 
1090 	ctx.u.zma.f = f;
1091 	ctx.u.zma.model = model;
1092 
1093 	spdk_fio_sync_run_oat(spdk_fio_get_zoned_model_oat, &ctx);
1094 
1095 	return ctx.ret;
1096 }
1097 
1098 
1099 static void
1100 spdk_fio_bdev_get_zone_info_done(struct spdk_bdev_io *bdev_io, bool success, void *arg)
1101 {
1102 	struct spdk_fio_zone_cb_arg *cb_arg = arg;
1103 	unsigned int i;
1104 	int handled_zones = 0;
1105 
1106 	if (!success) {
1107 		spdk_bdev_free_io(bdev_io);
1108 		cb_arg->completed = -EIO;
1109 		return;
1110 	}
1111 
1112 	for (i = 0; i < cb_arg->nr_zones; i++) {
1113 		struct spdk_bdev_zone_info *zone_src = &cb_arg->spdk_zones[handled_zones];
1114 		struct zbd_zone *zone_dest = &cb_arg->fio_zones[handled_zones];
1115 		uint32_t block_size = spdk_bdev_get_block_size(cb_arg->target->bdev);
1116 
1117 		switch (zone_src->type) {
1118 		case SPDK_BDEV_ZONE_TYPE_SEQWR:
1119 			zone_dest->type = ZBD_ZONE_TYPE_SWR;
1120 			break;
1121 		case SPDK_BDEV_ZONE_TYPE_SEQWP:
1122 			zone_dest->type = ZBD_ZONE_TYPE_SWP;
1123 			break;
1124 		case SPDK_BDEV_ZONE_TYPE_CNV:
1125 			zone_dest->type = ZBD_ZONE_TYPE_CNV;
1126 			break;
1127 		default:
1128 			spdk_bdev_free_io(bdev_io);
1129 			cb_arg->completed = -EIO;
1130 			return;
1131 		}
1132 
1133 		zone_dest->len = spdk_bdev_get_zone_size(cb_arg->target->bdev) * block_size;
1134 		zone_dest->capacity = zone_src->capacity * block_size;
1135 		zone_dest->start = zone_src->zone_id * block_size;
1136 		zone_dest->wp = zone_src->write_pointer * block_size;
1137 
1138 		switch (zone_src->state) {
1139 		case SPDK_BDEV_ZONE_STATE_EMPTY:
1140 			zone_dest->cond = ZBD_ZONE_COND_EMPTY;
1141 			break;
1142 		case SPDK_BDEV_ZONE_STATE_IMP_OPEN:
1143 			zone_dest->cond = ZBD_ZONE_COND_IMP_OPEN;
1144 			break;
1145 		case SPDK_BDEV_ZONE_STATE_EXP_OPEN:
1146 			zone_dest->cond = ZBD_ZONE_COND_EXP_OPEN;
1147 			break;
1148 		case SPDK_BDEV_ZONE_STATE_FULL:
1149 			zone_dest->cond = ZBD_ZONE_COND_FULL;
1150 			break;
1151 		case SPDK_BDEV_ZONE_STATE_CLOSED:
1152 			zone_dest->cond = ZBD_ZONE_COND_CLOSED;
1153 			break;
1154 		case SPDK_BDEV_ZONE_STATE_READ_ONLY:
1155 			zone_dest->cond = ZBD_ZONE_COND_READONLY;
1156 			break;
1157 		case SPDK_BDEV_ZONE_STATE_OFFLINE:
1158 			zone_dest->cond = ZBD_ZONE_COND_OFFLINE;
1159 			break;
1160 		case SPDK_BDEV_ZONE_STATE_NOT_WP:
1161 			zone_dest->cond = ZBD_ZONE_COND_NOT_WP;
1162 			/* Set WP to end of zone for zone types w/o WP (e.g. Conv. zones in SMR) */
1163 			zone_dest->wp = zone_dest->start + zone_dest->capacity;
1164 			break;
1165 		default:
1166 			spdk_bdev_free_io(bdev_io);
1167 			cb_arg->completed = -EIO;
1168 			return;
1169 		}
1170 		handled_zones++;
1171 	}
1172 
1173 	spdk_bdev_free_io(bdev_io);
1174 	cb_arg->completed = handled_zones;
1175 }
1176 
1177 static void
1178 spdk_fio_bdev_get_zone_info(void *arg)
1179 {
1180 	struct spdk_fio_zone_cb_arg *cb_arg = arg;
1181 	struct spdk_fio_target *target = cb_arg->target;
1182 	int rc;
1183 
1184 	rc = spdk_bdev_get_zone_info(target->desc, target->ch, cb_arg->offset_blocks,
1185 				     cb_arg->nr_zones, cb_arg->spdk_zones,
1186 				     spdk_fio_bdev_get_zone_info_done, cb_arg);
1187 	if (rc < 0) {
1188 		cb_arg->completed = rc;
1189 	}
1190 }
1191 
1192 static int
1193 spdk_fio_report_zones(struct thread_data *td, struct fio_file *f, uint64_t offset,
1194 		      struct zbd_zone *zones, unsigned int nr_zones)
1195 {
1196 	struct spdk_fio_target *target;
1197 	struct spdk_fio_thread *fio_thread;
1198 	struct spdk_fio_zone_cb_arg cb_arg;
1199 	uint32_t block_size;
1200 	int rc;
1201 
1202 	if (nr_zones == 0) {
1203 		return 0;
1204 	}
1205 
1206 	/* spdk_fio_report_zones() is only called before the bdev I/O channels have been created.
1207 	 * Since we need an I/O channel for report_zones(), call spdk_fio_init() to initialize
1208 	 * the thread early.
1209 	 * spdk_fio_report_zones() might be called several times by fio, if e.g. the zone report
1210 	 * for all zones does not fit in the buffer that fio has allocated for the zone report.
1211 	 * It is safe to call spdk_fio_init(), even if the thread has already been initialized.
1212 	 */
1213 	rc = spdk_fio_init(td);
1214 	if (rc) {
1215 		return rc;
1216 	}
1217 	fio_thread = td->io_ops_data;
1218 	target = f->engine_data;
1219 
1220 	assert(fio_thread);
1221 	assert(target);
1222 
1223 	block_size = spdk_bdev_get_block_size(target->bdev);
1224 
1225 	cb_arg.target = target;
1226 	cb_arg.completed = 0;
1227 	cb_arg.offset_blocks = offset / block_size;
1228 	cb_arg.fio_zones = zones;
1229 	cb_arg.nr_zones = spdk_min(nr_zones, spdk_bdev_get_num_zones(target->bdev));
1230 
1231 	cb_arg.spdk_zones = calloc(1, sizeof(*cb_arg.spdk_zones) * cb_arg.nr_zones);
1232 	if (!cb_arg.spdk_zones) {
1233 		SPDK_ERRLOG("Could not allocate memory for zone report!\n");
1234 		rc = -ENOMEM;
1235 		goto cleanup_thread;
1236 	}
1237 
1238 	spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_get_zone_info, &cb_arg);
1239 	do {
1240 		spdk_fio_poll_thread(fio_thread);
1241 	} while (!cb_arg.completed);
1242 
1243 	/* Free cb_arg.spdk_zones. The report in fio format is stored in cb_arg.fio_zones/zones. */
1244 	free(cb_arg.spdk_zones);
1245 
1246 	rc = cb_arg.completed;
1247 	if (rc < 0) {
1248 		SPDK_ERRLOG("Failed to get zone info: %d\n", rc);
1249 		goto cleanup_thread;
1250 	}
1251 
1252 	/* Return the amount of zones successfully copied. */
1253 	return rc;
1254 
1255 cleanup_thread:
1256 	spdk_fio_cleanup(td);
1257 
1258 	return rc;
1259 }
1260 
1261 static void
1262 spdk_fio_bdev_zone_reset_done(struct spdk_bdev_io *bdev_io, bool success, void *arg)
1263 {
1264 	struct spdk_fio_zone_cb_arg *cb_arg = arg;
1265 
1266 	spdk_bdev_free_io(bdev_io);
1267 
1268 	if (!success) {
1269 		cb_arg->completed = -EIO;
1270 	} else {
1271 		cb_arg->completed = 1;
1272 	}
1273 }
1274 
1275 static void
1276 spdk_fio_bdev_zone_reset(void *arg)
1277 {
1278 	struct spdk_fio_zone_cb_arg *cb_arg = arg;
1279 	struct spdk_fio_target *target = cb_arg->target;
1280 	int rc;
1281 
1282 	rc = spdk_bdev_zone_management(target->desc, target->ch, cb_arg->offset_blocks,
1283 				       SPDK_BDEV_ZONE_RESET,
1284 				       spdk_fio_bdev_zone_reset_done, cb_arg);
1285 	if (rc < 0) {
1286 		cb_arg->completed = rc;
1287 	}
1288 }
1289 
1290 static int
1291 spdk_fio_reset_zones(struct spdk_fio_thread *fio_thread, struct spdk_fio_target *target,
1292 		     uint64_t offset, uint64_t length)
1293 {
1294 	uint64_t zone_size_bytes;
1295 	uint32_t block_size;
1296 	int rc;
1297 
1298 	assert(fio_thread);
1299 	assert(target);
1300 
1301 	block_size = spdk_bdev_get_block_size(target->bdev);
1302 	zone_size_bytes = spdk_bdev_get_zone_size(target->bdev) * block_size;
1303 
1304 	for (uint64_t cur = offset; cur < offset + length; cur += zone_size_bytes) {
1305 		struct spdk_fio_zone_cb_arg cb_arg = {
1306 			.target = target,
1307 			.completed = 0,
1308 			.offset_blocks = cur / block_size,
1309 		};
1310 
1311 		spdk_thread_send_msg(fio_thread->thread, spdk_fio_bdev_zone_reset, &cb_arg);
1312 		do {
1313 			spdk_fio_poll_thread(fio_thread);
1314 		} while (!cb_arg.completed);
1315 
1316 		rc = cb_arg.completed;
1317 		if (rc < 0) {
1318 			SPDK_ERRLOG("Failed to reset zone: %d\n", rc);
1319 			return rc;
1320 		}
1321 	}
1322 
1323 	return 0;
1324 }
1325 
1326 static int
1327 spdk_fio_reset_wp(struct thread_data *td, struct fio_file *f, uint64_t offset, uint64_t length)
1328 {
1329 	return spdk_fio_reset_zones(td->io_ops_data, f->engine_data, offset, length);
1330 }
1331 #endif
1332 
1333 #if FIO_IOOPS_VERSION >= 30
1334 static void
1335 spdk_fio_get_max_open_zones_oat(void *_ctx)
1336 {
1337 	struct spdk_fio_oat_ctx *ctx = _ctx;
1338 	struct fio_file *f = ctx->u.moza.f;
1339 	struct spdk_bdev *bdev;
1340 
1341 	bdev = spdk_bdev_get_by_name(f->file_name);
1342 	if (!bdev) {
1343 		SPDK_ERRLOG("Cannot get max open zones, no bdev with name: %s\n", f->file_name);
1344 		ctx->ret = -ENODEV;
1345 	} else {
1346 		*ctx->u.moza.max_open_zones = spdk_bdev_get_max_open_zones(bdev);
1347 		ctx->ret = 0;
1348 	}
1349 
1350 	spdk_fio_wake_oat_waiter(ctx);
1351 }
1352 
1353 static int
1354 spdk_fio_get_max_open_zones(struct thread_data *td, struct fio_file *f,
1355 			    unsigned int *max_open_zones)
1356 {
1357 	struct spdk_fio_oat_ctx ctx = { 0 };
1358 
1359 	ctx.u.moza.f = f;
1360 	ctx.u.moza.max_open_zones = max_open_zones;
1361 
1362 	spdk_fio_sync_run_oat(spdk_fio_get_max_open_zones_oat, &ctx);
1363 
1364 	return ctx.ret;
1365 }
1366 #endif
1367 
1368 static int
1369 spdk_fio_handle_options(struct thread_data *td, struct fio_file *f, struct spdk_bdev *bdev)
1370 {
1371 	struct spdk_fio_options *fio_options = td->eo;
1372 
1373 	if (fio_options->initial_zone_reset && spdk_bdev_is_zoned(bdev)) {
1374 #if FIO_HAS_ZBD
1375 		int rc = spdk_fio_init(td);
1376 		if (rc) {
1377 			return rc;
1378 		}
1379 		/* offset used to indicate conventional zones that need to be skipped (reset not allowed) */
1380 		rc = spdk_fio_reset_zones(td->io_ops_data, f->engine_data, td->o.start_offset,
1381 					  f->real_file_size - td->o.start_offset);
1382 		if (rc) {
1383 			spdk_fio_cleanup(td);
1384 			return rc;
1385 		}
1386 #else
1387 		SPDK_ERRLOG("fio version is too old to support zoned block devices\n");
1388 #endif
1389 	}
1390 
1391 	return 0;
1392 }
1393 
1394 static int
1395 spdk_fio_handle_options_per_target(struct thread_data *td, struct fio_file *f)
1396 {
1397 	struct spdk_fio_target *target = f->engine_data;
1398 	struct spdk_fio_options *fio_options = td->eo;
1399 
1400 	if (fio_options->zone_append && spdk_bdev_is_zoned(target->bdev)) {
1401 		if (spdk_bdev_io_type_supported(target->bdev, SPDK_BDEV_IO_TYPE_ZONE_APPEND)) {
1402 			SPDK_DEBUGLOG(fio_bdev, "Using zone appends instead of writes on: '%s'\n",
1403 				      f->file_name);
1404 			target->zone_append_enabled = true;
1405 		} else {
1406 			SPDK_WARNLOG("Falling back to writes on: '%s' - bdev lacks zone append cmd\n",
1407 				     f->file_name);
1408 		}
1409 	}
1410 
1411 	return 0;
1412 }
1413 
1414 static struct fio_option options[] = {
1415 	{
1416 		.name		= "spdk_conf",
1417 		.lname		= "SPDK configuration file",
1418 		.type		= FIO_OPT_STR_STORE,
1419 		.off1		= offsetof(struct spdk_fio_options, conf),
1420 		.help		= "A SPDK JSON configuration file",
1421 		.category	= FIO_OPT_C_ENGINE,
1422 		.group		= FIO_OPT_G_INVALID,
1423 	},
1424 	{
1425 		.name           = "spdk_json_conf",
1426 		.lname          = "SPDK JSON configuration file",
1427 		.type           = FIO_OPT_STR_STORE,
1428 		.off1           = offsetof(struct spdk_fio_options, json_conf),
1429 		.help           = "A SPDK JSON configuration file",
1430 		.category       = FIO_OPT_C_ENGINE,
1431 		.group          = FIO_OPT_G_INVALID,
1432 	},
1433 	{
1434 		.name		= "spdk_mem",
1435 		.lname		= "SPDK memory in MB",
1436 		.type		= FIO_OPT_INT,
1437 		.off1		= offsetof(struct spdk_fio_options, mem_mb),
1438 		.help		= "Amount of memory in MB to allocate for SPDK",
1439 		.category	= FIO_OPT_C_ENGINE,
1440 		.group		= FIO_OPT_G_INVALID,
1441 	},
1442 	{
1443 		.name		= "spdk_single_seg",
1444 		.lname		= "SPDK switch to create just a single hugetlbfs file",
1445 		.type		= FIO_OPT_BOOL,
1446 		.off1		= offsetof(struct spdk_fio_options, mem_single_seg),
1447 		.help		= "If set to 1, SPDK will use just a single hugetlbfs file",
1448 		.def            = "0",
1449 		.category	= FIO_OPT_C_ENGINE,
1450 		.group		= FIO_OPT_G_INVALID,
1451 	},
1452 	{
1453 		.name           = "log_flags",
1454 		.lname          = "log flags",
1455 		.type           = FIO_OPT_STR_STORE,
1456 		.off1           = offsetof(struct spdk_fio_options, log_flags),
1457 		.help           = "SPDK log flags to enable",
1458 		.category       = FIO_OPT_C_ENGINE,
1459 		.group          = FIO_OPT_G_INVALID,
1460 	},
1461 	{
1462 		.name		= "initial_zone_reset",
1463 		.lname		= "Reset Zones on initialization",
1464 		.type		= FIO_OPT_INT,
1465 		.off1		= offsetof(struct spdk_fio_options, initial_zone_reset),
1466 		.def		= "0",
1467 		.help		= "Reset Zones on initialization (0=disable, 1=Reset All Zones)",
1468 		.category	= FIO_OPT_C_ENGINE,
1469 		.group		= FIO_OPT_G_INVALID,
1470 	},
1471 	{
1472 		.name		= "zone_append",
1473 		.lname		= "Use zone append instead of write",
1474 		.type		= FIO_OPT_INT,
1475 		.off1		= offsetof(struct spdk_fio_options, zone_append),
1476 		.def		= "0",
1477 		.help		= "Use zone append instead of write (1=zone append, 0=write)",
1478 		.category	= FIO_OPT_C_ENGINE,
1479 		.group		= FIO_OPT_G_INVALID,
1480 	},
1481 	{
1482 		.name           = "env_context",
1483 		.lname          = "Environment context options",
1484 		.type           = FIO_OPT_STR_STORE,
1485 		.off1           = offsetof(struct spdk_fio_options, env_context),
1486 		.help           = "Opaque context for use of the env implementation",
1487 		.category       = FIO_OPT_C_ENGINE,
1488 		.group          = FIO_OPT_G_INVALID,
1489 	},
1490 	{
1491 		.name		= "spdk_rpc_listen_addr",
1492 		.lname		= "SPDK RPC listen address",
1493 		.type		= FIO_OPT_STR_STORE,
1494 		.off1		= offsetof(struct spdk_fio_options, rpc_listen_addr),
1495 		.help		= "The address to listen the RPC operations",
1496 		.category	= FIO_OPT_C_ENGINE,
1497 		.group		= FIO_OPT_G_INVALID,
1498 	},
1499 	{
1500 		.name		= NULL,
1501 	},
1502 };
1503 
1504 /* FIO imports this structure using dlsym */
1505 struct ioengine_ops ioengine = {
1506 	.name			= "spdk_bdev",
1507 	.version		= FIO_IOOPS_VERSION,
1508 	.flags			= FIO_RAWIO | FIO_NOEXTEND | FIO_NODISKUTIL | FIO_MEMALIGN | FIO_DISKLESSIO,
1509 	.setup			= spdk_fio_setup,
1510 	.init			= spdk_fio_init,
1511 	/* .prep		= unused, */
1512 	.queue			= spdk_fio_queue,
1513 	/* .commit		= unused, */
1514 	.getevents		= spdk_fio_getevents,
1515 	.event			= spdk_fio_event,
1516 	/* .errdetails		= unused, */
1517 	/* .cancel		= unused, */
1518 	.cleanup		= spdk_fio_cleanup,
1519 	.open_file		= spdk_fio_open,
1520 	.close_file		= spdk_fio_close,
1521 	.invalidate		= spdk_fio_invalidate,
1522 	/* .unlink_file		= unused, */
1523 	/* .get_file_size	= unused, */
1524 	/* .terminate		= unused, */
1525 	.iomem_alloc		= spdk_fio_iomem_alloc,
1526 	.iomem_free		= spdk_fio_iomem_free,
1527 	.io_u_init		= spdk_fio_io_u_init,
1528 	.io_u_free		= spdk_fio_io_u_free,
1529 #if FIO_HAS_ZBD
1530 	.get_zoned_model	= spdk_fio_get_zoned_model,
1531 	.report_zones		= spdk_fio_report_zones,
1532 	.reset_wp		= spdk_fio_reset_wp,
1533 #endif
1534 #if FIO_IOOPS_VERSION >= 30
1535 	.get_max_open_zones	= spdk_fio_get_max_open_zones,
1536 #endif
1537 	.option_struct_size	= sizeof(struct spdk_fio_options),
1538 	.options		= options,
1539 };
1540 
1541 static void fio_init
1542 spdk_fio_register(void)
1543 {
1544 	register_ioengine(&ioengine);
1545 }
1546 
1547 static void
1548 spdk_fio_finish_env(void)
1549 {
1550 	pthread_mutex_lock(&g_init_mtx);
1551 	g_poll_loop = false;
1552 	pthread_cond_signal(&g_init_cond);
1553 	pthread_mutex_unlock(&g_init_mtx);
1554 	pthread_join(g_init_thread_id, NULL);
1555 
1556 	spdk_thread_lib_fini();
1557 	spdk_env_fini();
1558 }
1559 
1560 static void fio_exit
1561 spdk_fio_unregister(void)
1562 {
1563 	if (g_spdk_env_initialized) {
1564 		spdk_fio_finish_env();
1565 		g_spdk_env_initialized = false;
1566 	}
1567 	unregister_ioengine(&ioengine);
1568 }
1569 
1570 SPDK_LOG_REGISTER_COMPONENT(fio_bdev)
1571