xref: /spdk/examples/bdev/bdevperf/bdevperf.c (revision 06472fb6d0c234046253a9989fef790e0cbb219e)
1 /*   SPDX-License-Identifier: BSD-3-Clause
2  *   Copyright (C) 2016 Intel Corporation.
3  *   Copyright (c) 2022-2023 NVIDIA CORPORATION & AFFILIATES.
4  *   All rights reserved.
5  */
6 
7 #include "spdk/stdinc.h"
8 
9 #include "spdk/bdev.h"
10 #include "spdk/accel.h"
11 #include "spdk/endian.h"
12 #include "spdk/env.h"
13 #include "spdk/event.h"
14 #include "spdk/log.h"
15 #include "spdk/util.h"
16 #include "spdk/thread.h"
17 #include "spdk/string.h"
18 #include "spdk/rpc.h"
19 #include "spdk/bit_array.h"
20 #include "spdk/conf.h"
21 #include "spdk/zipf.h"
22 #include "spdk/histogram_data.h"
23 
24 #define BDEVPERF_CONFIG_MAX_FILENAME 1024
25 #define BDEVPERF_CONFIG_UNDEFINED -1
26 #define BDEVPERF_CONFIG_ERROR -2
27 #define PATTERN_TYPES_STR "(read, write, randread, randwrite, rw, randrw, verify, reset, unmap, flush, write_zeroes)"
28 
29 struct bdevperf_task {
30 	struct iovec			iov;
31 	struct bdevperf_job		*job;
32 	struct spdk_bdev_io		*bdev_io;
33 	void				*buf;
34 	void				*verify_buf;
35 	void				*md_buf;
36 	uint64_t			offset_blocks;
37 	struct bdevperf_task		*task_to_abort;
38 	enum spdk_bdev_io_type		io_type;
39 	TAILQ_ENTRY(bdevperf_task)	link;
40 	struct spdk_bdev_io_wait_entry	bdev_io_wait;
41 };
42 
43 static char *g_workload_type = NULL;
44 static int g_io_size = 0;
45 /* initialize to invalid value so we can detect if user overrides it. */
46 static int g_rw_percentage = -1;
47 static bool g_verify = false;
48 static bool g_reset = false;
49 static bool g_continue_on_failure = false;
50 static bool g_abort = false;
51 static bool g_error_to_exit = false;
52 static int g_queue_depth = 0;
53 static uint64_t g_time_in_usec;
54 static int g_show_performance_real_time = 0;
55 static uint64_t g_show_performance_period_in_usec = SPDK_SEC_TO_USEC;
56 static uint64_t g_show_performance_period_num = 0;
57 static uint64_t g_show_performance_ema_period = 0;
58 static int g_run_rc = 0;
59 static bool g_shutdown = false;
60 static uint64_t g_start_tsc;
61 static uint64_t g_shutdown_tsc;
62 static bool g_zcopy = false;
63 static struct spdk_thread *g_main_thread;
64 static int g_time_in_sec = 0;
65 static bool g_mix_specified = false;
66 static const char *g_job_bdev_name;
67 static bool g_wait_for_tests = false;
68 static struct spdk_jsonrpc_request *g_request = NULL;
69 static bool g_multithread_mode = false;
70 static int g_timeout_in_sec;
71 static struct spdk_conf *g_bdevperf_conf = NULL;
72 static const char *g_bdevperf_conf_file = NULL;
73 static double g_zipf_theta;
74 static bool g_random_map = false;
75 static bool g_unique_writes = false;
76 
77 static struct spdk_cpuset g_all_cpuset;
78 static struct spdk_poller *g_perf_timer = NULL;
79 
80 static void bdevperf_submit_single(struct bdevperf_job *job, struct bdevperf_task *task);
81 static void rpc_perform_tests_cb(void);
82 static int bdevperf_parse_arg(int ch, char *arg);
83 static int verify_test_params(void);
84 static void bdevperf_usage(void);
85 
86 static uint32_t g_bdev_count = 0;
87 static uint32_t g_latency_display_level;
88 
89 static bool g_one_thread_per_lcore = false;
90 
91 static const double g_latency_cutoffs[] = {
92 	0.01,
93 	0.10,
94 	0.25,
95 	0.50,
96 	0.75,
97 	0.90,
98 	0.95,
99 	0.98,
100 	0.99,
101 	0.995,
102 	0.999,
103 	0.9999,
104 	0.99999,
105 	0.999999,
106 	0.9999999,
107 	-1,
108 };
109 
110 static const char *g_rpc_log_file_name = NULL;
111 static FILE *g_rpc_log_file = NULL;
112 
113 struct latency_info {
114 	uint64_t	min;
115 	uint64_t	max;
116 	uint64_t	total;
117 };
118 
119 
120 enum job_config_rw {
121 	JOB_CONFIG_RW_READ = 0,
122 	JOB_CONFIG_RW_WRITE,
123 	JOB_CONFIG_RW_RANDREAD,
124 	JOB_CONFIG_RW_RANDWRITE,
125 	JOB_CONFIG_RW_RW,
126 	JOB_CONFIG_RW_RANDRW,
127 	JOB_CONFIG_RW_VERIFY,
128 	JOB_CONFIG_RW_RESET,
129 	JOB_CONFIG_RW_UNMAP,
130 	JOB_CONFIG_RW_FLUSH,
131 	JOB_CONFIG_RW_WRITE_ZEROES,
132 };
133 
134 struct bdevperf_job {
135 	char				*name;
136 	struct spdk_bdev		*bdev;
137 	struct spdk_bdev_desc		*bdev_desc;
138 	struct spdk_io_channel		*ch;
139 	TAILQ_ENTRY(bdevperf_job)	link;
140 	struct spdk_thread		*thread;
141 
142 	enum job_config_rw		workload_type;
143 	int				io_size;
144 	int				rw_percentage;
145 	bool				is_random;
146 	bool				verify;
147 	bool				reset;
148 	bool				continue_on_failure;
149 	bool				unmap;
150 	bool				write_zeroes;
151 	bool				flush;
152 	bool				abort;
153 	int				queue_depth;
154 	unsigned int			seed;
155 
156 	uint64_t			io_completed;
157 	uint64_t			io_failed;
158 	uint64_t			io_timeout;
159 	uint64_t			prev_io_completed;
160 	double				ema_io_per_second;
161 	int				current_queue_depth;
162 	uint64_t			size_in_ios;
163 	uint64_t			ios_base;
164 	uint64_t			offset_in_ios;
165 	uint64_t			io_size_blocks;
166 	uint64_t			buf_size;
167 	uint32_t			dif_check_flags;
168 	bool				is_draining;
169 	struct spdk_poller		*run_timer;
170 	struct spdk_poller		*reset_timer;
171 	struct spdk_bit_array		*outstanding;
172 	struct spdk_zipf		*zipf;
173 	TAILQ_HEAD(, bdevperf_task)	task_list;
174 	uint64_t			run_time_in_usec;
175 
176 	/* keep channel's histogram data before being destroyed */
177 	struct spdk_histogram_data	*histogram;
178 	struct spdk_bit_array		*random_map;
179 
180 	/* counter used for generating unique write data (-U option) */
181 	uint32_t			write_io_count;
182 };
183 
184 struct spdk_bdevperf {
185 	TAILQ_HEAD(, bdevperf_job)	jobs;
186 	uint32_t			running_jobs;
187 };
188 
189 static struct spdk_bdevperf g_bdevperf = {
190 	.jobs = TAILQ_HEAD_INITIALIZER(g_bdevperf.jobs),
191 	.running_jobs = 0,
192 };
193 
194 /* Storing values from a section of job config file */
195 struct job_config {
196 	const char			*name;
197 	const char			*filename;
198 	struct spdk_cpuset		cpumask;
199 	int				bs;
200 	int				iodepth;
201 	int				rwmixread;
202 	uint32_t			lcore;
203 	int64_t				offset;
204 	uint64_t			length;
205 	enum job_config_rw		rw;
206 	TAILQ_ENTRY(job_config)	link;
207 };
208 
209 TAILQ_HEAD(, job_config) job_config_list
210 	= TAILQ_HEAD_INITIALIZER(job_config_list);
211 
212 static bool g_performance_dump_active = false;
213 
214 struct bdevperf_aggregate_stats {
215 	struct bdevperf_job		*current_job;
216 	uint64_t			io_time_in_usec;
217 	uint64_t			ema_period;
218 	double				total_io_per_second;
219 	double				total_mb_per_second;
220 	double				total_failed_per_second;
221 	double				total_timeout_per_second;
222 	double				min_latency;
223 	double				max_latency;
224 	uint64_t			total_io_completed;
225 	uint64_t			total_tsc;
226 };
227 
228 static struct bdevperf_aggregate_stats g_stats = {.min_latency = (double)UINT64_MAX};
229 
230 struct lcore_thread {
231 	struct spdk_thread		*thread;
232 	uint32_t			lcore;
233 	TAILQ_ENTRY(lcore_thread)	link;
234 };
235 
236 TAILQ_HEAD(, lcore_thread) g_lcore_thread_list
237 	= TAILQ_HEAD_INITIALIZER(g_lcore_thread_list);
238 
239 
240 static char *
241 parse_workload_type(enum job_config_rw ret)
242 {
243 	switch (ret) {
244 	case JOB_CONFIG_RW_READ:
245 		return "read";
246 	case JOB_CONFIG_RW_RANDREAD:
247 		return "randread";
248 	case JOB_CONFIG_RW_WRITE:
249 		return "write";
250 	case JOB_CONFIG_RW_RANDWRITE:
251 		return "randwrite";
252 	case JOB_CONFIG_RW_VERIFY:
253 		return "verify";
254 	case JOB_CONFIG_RW_RESET:
255 		return "reset";
256 	case JOB_CONFIG_RW_UNMAP:
257 		return "unmap";
258 	case JOB_CONFIG_RW_WRITE_ZEROES:
259 		return "write_zeroes";
260 	case JOB_CONFIG_RW_FLUSH:
261 		return "flush";
262 	case JOB_CONFIG_RW_RW:
263 		return "rw";
264 	case JOB_CONFIG_RW_RANDRW:
265 		return "randrw";
266 	default:
267 		fprintf(stderr, "wrong workload_type code\n");
268 	}
269 
270 	return NULL;
271 }
272 
273 /*
274  * Cumulative Moving Average (CMA): average of all data up to current
275  * Exponential Moving Average (EMA): weighted mean of the previous n data and more weight is given to recent
276  * Simple Moving Average (SMA): unweighted mean of the previous n data
277  *
278  * Bdevperf supports CMA and EMA.
279  */
280 static double
281 get_cma_io_per_second(struct bdevperf_job *job, uint64_t io_time_in_usec)
282 {
283 	return (double)job->io_completed * SPDK_SEC_TO_USEC / io_time_in_usec;
284 }
285 
286 static double
287 get_ema_io_per_second(struct bdevperf_job *job, uint64_t ema_period)
288 {
289 	double io_completed, io_per_second;
290 
291 	io_completed = job->io_completed;
292 	io_per_second = (double)(io_completed - job->prev_io_completed) * SPDK_SEC_TO_USEC
293 			/ g_show_performance_period_in_usec;
294 	job->prev_io_completed = io_completed;
295 
296 	job->ema_io_per_second += (io_per_second - job->ema_io_per_second) * 2
297 				  / (ema_period + 1);
298 	return job->ema_io_per_second;
299 }
300 
301 static void
302 get_avg_latency(void *ctx, uint64_t start, uint64_t end, uint64_t count,
303 		uint64_t total, uint64_t so_far)
304 {
305 	struct latency_info *latency_info = ctx;
306 
307 	if (count == 0) {
308 		return;
309 	}
310 
311 	latency_info->total += (start + end) / 2 * count;
312 
313 	if (so_far == count) {
314 		latency_info->min = start;
315 	}
316 
317 	if (so_far == total) {
318 		latency_info->max = end;
319 	}
320 }
321 
322 static void
323 performance_dump_job(struct bdevperf_aggregate_stats *stats, struct bdevperf_job *job)
324 {
325 	double io_per_second, mb_per_second, failed_per_second, timeout_per_second;
326 	double average_latency = 0.0, min_latency, max_latency;
327 	uint64_t time_in_usec;
328 	uint64_t tsc_rate;
329 	uint64_t total_io;
330 	struct latency_info latency_info = {};
331 
332 	if (job->workload_type == JOB_CONFIG_RW_RW || job->workload_type == JOB_CONFIG_RW_RANDRW) {
333 		printf("\r Job: %s (Core Mask 0x%s, workload: %s, percentage: %d, depth: %d, IO size: %d)\n",
334 		       job->name, spdk_cpuset_fmt(spdk_thread_get_cpumask(job->thread)),
335 		       parse_workload_type(job->workload_type), job->rw_percentage,
336 		       job->queue_depth, job->io_size);
337 	} else {
338 		printf("\r Job: %s (Core Mask 0x%s, workload: %s, depth: %d, IO size: %d)\n",
339 		       job->name, spdk_cpuset_fmt(spdk_thread_get_cpumask(job->thread)),
340 		       parse_workload_type(job->workload_type), job->queue_depth, job->io_size);
341 	}
342 
343 
344 	if (job->io_failed > 0 && !job->reset && !job->continue_on_failure) {
345 		printf("\r Job: %s ended in about %.2f seconds with error\n",
346 		       job->name, (double)job->run_time_in_usec / SPDK_SEC_TO_USEC);
347 	}
348 	if (job->verify) {
349 		printf("\t Verification LBA range: start 0x%" PRIx64 " length 0x%" PRIx64 "\n",
350 		       job->ios_base, job->size_in_ios);
351 	}
352 
353 	if (g_performance_dump_active == true) {
354 		/* Use job's actual run time as Job has ended */
355 		if (job->io_failed > 0 && !job->continue_on_failure) {
356 			time_in_usec = job->run_time_in_usec;
357 		} else {
358 			time_in_usec = stats->io_time_in_usec;
359 		}
360 	} else {
361 		time_in_usec = job->run_time_in_usec;
362 	}
363 
364 	if (stats->ema_period == 0) {
365 		io_per_second = get_cma_io_per_second(job, time_in_usec);
366 	} else {
367 		io_per_second = get_ema_io_per_second(job, stats->ema_period);
368 	}
369 
370 	tsc_rate = spdk_get_ticks_hz();
371 	mb_per_second = io_per_second * job->io_size / (1024 * 1024);
372 
373 	spdk_histogram_data_iterate(job->histogram, get_avg_latency, &latency_info);
374 
375 	total_io = job->io_completed + job->io_failed;
376 	if (total_io != 0) {
377 		average_latency = (double)latency_info.total / total_io * SPDK_SEC_TO_USEC / tsc_rate;
378 	}
379 	min_latency = (double)latency_info.min * SPDK_SEC_TO_USEC / tsc_rate;
380 	max_latency = (double)latency_info.max * SPDK_SEC_TO_USEC / tsc_rate;
381 
382 	failed_per_second = (double)job->io_failed * SPDK_SEC_TO_USEC / time_in_usec;
383 	timeout_per_second = (double)job->io_timeout * SPDK_SEC_TO_USEC / time_in_usec;
384 
385 	printf("\t %-20s: %10.2f %10.2f %10.2f",
386 	       job->name, (float)time_in_usec / SPDK_SEC_TO_USEC, io_per_second, mb_per_second);
387 	printf(" %10.2f %8.2f",
388 	       failed_per_second, timeout_per_second);
389 	printf(" %10.2f %10.2f %10.2f\n",
390 	       average_latency, min_latency, max_latency);
391 
392 	stats->total_io_per_second += io_per_second;
393 	stats->total_mb_per_second += mb_per_second;
394 	stats->total_failed_per_second += failed_per_second;
395 	stats->total_timeout_per_second += timeout_per_second;
396 	stats->total_io_completed += job->io_completed + job->io_failed;
397 	stats->total_tsc += latency_info.total;
398 	if (min_latency < stats->min_latency) {
399 		stats->min_latency = min_latency;
400 	}
401 	if (max_latency > stats->max_latency) {
402 		stats->max_latency = max_latency;
403 	}
404 }
405 
406 static void
407 generate_data(struct bdevperf_job *job, void *buf, void *md_buf, bool unique)
408 {
409 	int offset_blocks = 0, md_offset, data_block_size, inner_offset;
410 	int buf_len = job->buf_size;
411 	int block_size = spdk_bdev_get_block_size(job->bdev);
412 	int md_size = spdk_bdev_get_md_size(job->bdev);
413 	int num_blocks = job->io_size_blocks;
414 
415 	if (buf_len < num_blocks * block_size) {
416 		return;
417 	}
418 
419 	if (md_buf == NULL) {
420 		data_block_size = block_size - md_size;
421 		md_buf = (char *)buf + data_block_size;
422 		md_offset = block_size;
423 	} else {
424 		data_block_size = block_size;
425 		md_offset = md_size;
426 	}
427 
428 	if (unique) {
429 		uint64_t io_count = job->write_io_count++;
430 		unsigned int i;
431 
432 		assert(md_size == 0 || md_size >= (int)sizeof(uint64_t));
433 
434 		while (offset_blocks < num_blocks) {
435 			inner_offset = 0;
436 			while (inner_offset < data_block_size) {
437 				*(uint64_t *)buf = (io_count << 32) | (offset_blocks + inner_offset);
438 				inner_offset += sizeof(uint64_t);
439 				buf += sizeof(uint64_t);
440 			}
441 			for (i = 0; i < md_size / sizeof(uint64_t); i++) {
442 				((uint64_t *)md_buf)[i] = (io_count << 32) | offset_blocks;
443 			}
444 			md_buf += md_offset;
445 			offset_blocks++;
446 		}
447 		return;
448 	}
449 
450 	while (offset_blocks < num_blocks) {
451 		inner_offset = 0;
452 		while (inner_offset < data_block_size) {
453 			*(uint32_t *)buf = offset_blocks + inner_offset;
454 			inner_offset += sizeof(uint32_t);
455 			buf += sizeof(uint32_t);
456 		}
457 		memset(md_buf, offset_blocks, md_size);
458 		md_buf += md_offset;
459 		offset_blocks++;
460 	}
461 }
462 
463 static bool
464 copy_data(void *wr_buf, int wr_buf_len, void *rd_buf, int rd_buf_len, int block_size,
465 	  void *wr_md_buf, void *rd_md_buf, int md_size, int num_blocks)
466 {
467 	if (wr_buf_len < num_blocks * block_size || rd_buf_len < num_blocks * block_size) {
468 		return false;
469 	}
470 
471 	assert((wr_md_buf != NULL) == (rd_md_buf != NULL));
472 
473 	memcpy(wr_buf, rd_buf, block_size * num_blocks);
474 
475 	if (wr_md_buf != NULL) {
476 		memcpy(wr_md_buf, rd_md_buf, md_size * num_blocks);
477 	}
478 
479 	return true;
480 }
481 
482 static bool
483 verify_data(void *wr_buf, int wr_buf_len, void *rd_buf, int rd_buf_len, int block_size,
484 	    void *wr_md_buf, void *rd_md_buf, int md_size, int num_blocks, bool md_check)
485 {
486 	int offset_blocks = 0, md_offset, data_block_size;
487 
488 	if (wr_buf_len < num_blocks * block_size || rd_buf_len < num_blocks * block_size) {
489 		return false;
490 	}
491 
492 	assert((wr_md_buf != NULL) == (rd_md_buf != NULL));
493 
494 	if (wr_md_buf == NULL) {
495 		data_block_size = block_size - md_size;
496 		wr_md_buf = (char *)wr_buf + data_block_size;
497 		rd_md_buf = (char *)rd_buf + data_block_size;
498 		md_offset = block_size;
499 	} else {
500 		data_block_size = block_size;
501 		md_offset = md_size;
502 	}
503 
504 	while (offset_blocks < num_blocks) {
505 		if (memcmp(wr_buf, rd_buf, data_block_size) != 0) {
506 			printf("data_block_size %d, num_blocks %d, offset %d\n", data_block_size, num_blocks,
507 			       offset_blocks);
508 			spdk_log_dump(stdout, "rd_buf", rd_buf, data_block_size);
509 			spdk_log_dump(stdout, "wr_buf", wr_buf, data_block_size);
510 			return false;
511 		}
512 
513 		wr_buf += block_size;
514 		rd_buf += block_size;
515 
516 		if (md_check) {
517 			if (memcmp(wr_md_buf, rd_md_buf, md_size) != 0) {
518 				printf("md_size %d, num_blocks %d, offset %d\n", md_size, num_blocks, offset_blocks);
519 				spdk_log_dump(stdout, "rd_md_buf", rd_md_buf, md_size);
520 				spdk_log_dump(stdout, "wr_md_buf", wr_md_buf, md_size);
521 				return false;
522 			}
523 
524 			wr_md_buf += md_offset;
525 			rd_md_buf += md_offset;
526 		}
527 
528 		offset_blocks++;
529 	}
530 
531 	return true;
532 }
533 
534 static void
535 free_job_config(void)
536 {
537 	struct job_config *config, *tmp;
538 
539 	spdk_conf_free(g_bdevperf_conf);
540 	g_bdevperf_conf = NULL;
541 
542 	TAILQ_FOREACH_SAFE(config, &job_config_list, link, tmp) {
543 		TAILQ_REMOVE(&job_config_list, config, link);
544 		free(config);
545 	}
546 }
547 
548 static void
549 bdevperf_job_free(struct bdevperf_job *job)
550 {
551 	spdk_histogram_data_free(job->histogram);
552 	spdk_bit_array_free(&job->outstanding);
553 	spdk_bit_array_free(&job->random_map);
554 	spdk_zipf_free(&job->zipf);
555 	free(job->name);
556 	free(job);
557 }
558 
559 static void
560 job_thread_exit(void *ctx)
561 {
562 	spdk_thread_exit(spdk_get_thread());
563 }
564 
565 static void
566 check_cutoff(void *ctx, uint64_t start, uint64_t end, uint64_t count,
567 	     uint64_t total, uint64_t so_far)
568 {
569 	double so_far_pct;
570 	double **cutoff = ctx;
571 	uint64_t tsc_rate;
572 
573 	if (count == 0) {
574 		return;
575 	}
576 
577 	tsc_rate = spdk_get_ticks_hz();
578 	so_far_pct = (double)so_far / total;
579 	while (so_far_pct >= **cutoff && **cutoff > 0) {
580 		printf("%9.5f%% : %9.3fus\n", **cutoff * 100, (double)end * SPDK_SEC_TO_USEC / tsc_rate);
581 		(*cutoff)++;
582 	}
583 }
584 
585 static void
586 print_bucket(void *ctx, uint64_t start, uint64_t end, uint64_t count,
587 	     uint64_t total, uint64_t so_far)
588 {
589 	double so_far_pct;
590 	uint64_t tsc_rate;
591 
592 	if (count == 0) {
593 		return;
594 	}
595 
596 	tsc_rate = spdk_get_ticks_hz();
597 	so_far_pct = (double)so_far * 100 / total;
598 	printf("%9.3f - %9.3f: %9.4f%%  (%9ju)\n",
599 	       (double)start * SPDK_SEC_TO_USEC / tsc_rate,
600 	       (double)end * SPDK_SEC_TO_USEC / tsc_rate,
601 	       so_far_pct, count);
602 }
603 
604 static void
605 bdevperf_test_done(void *ctx)
606 {
607 	struct bdevperf_job *job, *jtmp;
608 	struct bdevperf_task *task, *ttmp;
609 	struct lcore_thread *lthread, *lttmp;
610 	double average_latency = 0.0;
611 	uint64_t time_in_usec;
612 	int rc;
613 
614 	if (g_time_in_usec) {
615 		g_stats.io_time_in_usec = g_time_in_usec;
616 
617 		if (!g_run_rc && g_performance_dump_active) {
618 			spdk_thread_send_msg(spdk_get_thread(), bdevperf_test_done, NULL);
619 			return;
620 		}
621 	}
622 
623 	if (g_show_performance_real_time) {
624 		spdk_poller_unregister(&g_perf_timer);
625 	}
626 
627 	if (g_shutdown) {
628 		g_shutdown_tsc = spdk_get_ticks() - g_start_tsc;
629 		time_in_usec = g_shutdown_tsc * SPDK_SEC_TO_USEC / spdk_get_ticks_hz();
630 		g_time_in_usec = (g_time_in_usec > time_in_usec) ? time_in_usec : g_time_in_usec;
631 		printf("Received shutdown signal, test time was about %.6f seconds\n",
632 		       (double)g_time_in_usec / SPDK_SEC_TO_USEC);
633 	}
634 
635 	printf("\n%*s\n", 107, "Latency(us)");
636 	printf("\r %-*s: %10s %10s %10s %10s %8s %10s %10s %10s\n",
637 	       28, "Device Information", "runtime(s)", "IOPS", "MiB/s", "Fail/s", "TO/s", "Average", "min", "max");
638 
639 	TAILQ_FOREACH_SAFE(job, &g_bdevperf.jobs, link, jtmp) {
640 		performance_dump_job(&g_stats, job);
641 	}
642 
643 	printf("\r =================================================================================="
644 	       "=================================\n");
645 	printf("\r %-28s: %10s %10.2f %10.2f",
646 	       "Total", "", g_stats.total_io_per_second, g_stats.total_mb_per_second);
647 	printf(" %10.2f %8.2f",
648 	       g_stats.total_failed_per_second, g_stats.total_timeout_per_second);
649 
650 	if (g_stats.total_io_completed != 0) {
651 		average_latency = ((double)g_stats.total_tsc / g_stats.total_io_completed) * SPDK_SEC_TO_USEC /
652 				  spdk_get_ticks_hz();
653 	}
654 	printf(" %10.2f %10.2f %10.2f\n", average_latency, g_stats.min_latency, g_stats.max_latency);
655 
656 	fflush(stdout);
657 
658 	if (g_latency_display_level == 0 || g_stats.total_io_completed == 0) {
659 		goto clean;
660 	}
661 
662 	printf("\n Latency summary\n");
663 	TAILQ_FOREACH_SAFE(job, &g_bdevperf.jobs, link, jtmp) {
664 		printf("\r =============================================\n");
665 		printf("\r Job: %s (Core Mask 0x%s)\n", job->name,
666 		       spdk_cpuset_fmt(spdk_thread_get_cpumask(job->thread)));
667 
668 		const double *cutoff = g_latency_cutoffs;
669 
670 		spdk_histogram_data_iterate(job->histogram, check_cutoff, &cutoff);
671 
672 		printf("\n");
673 	}
674 
675 	if (g_latency_display_level == 1) {
676 		goto clean;
677 	}
678 
679 	printf("\r Latency histogram\n");
680 	TAILQ_FOREACH_SAFE(job, &g_bdevperf.jobs, link, jtmp) {
681 		printf("\r =============================================\n");
682 		printf("\r Job: %s (Core Mask 0x%s)\n", job->name,
683 		       spdk_cpuset_fmt(spdk_thread_get_cpumask(job->thread)));
684 
685 		spdk_histogram_data_iterate(job->histogram, print_bucket, NULL);
686 		printf("\n");
687 	}
688 
689 clean:
690 	TAILQ_FOREACH_SAFE(job, &g_bdevperf.jobs, link, jtmp) {
691 		TAILQ_REMOVE(&g_bdevperf.jobs, job, link);
692 
693 		if (!g_one_thread_per_lcore) {
694 			spdk_thread_send_msg(job->thread, job_thread_exit, NULL);
695 		}
696 
697 		TAILQ_FOREACH_SAFE(task, &job->task_list, link, ttmp) {
698 			TAILQ_REMOVE(&job->task_list, task, link);
699 			spdk_free(task->buf);
700 			spdk_free(task->verify_buf);
701 			spdk_free(task->md_buf);
702 			free(task);
703 		}
704 
705 		bdevperf_job_free(job);
706 	}
707 
708 	if (g_one_thread_per_lcore) {
709 		TAILQ_FOREACH_SAFE(lthread, &g_lcore_thread_list, link, lttmp) {
710 			TAILQ_REMOVE(&g_lcore_thread_list, lthread, link);
711 			spdk_thread_send_msg(lthread->thread, job_thread_exit, NULL);
712 			free(lthread);
713 		}
714 	}
715 
716 	if (g_bdevperf_conf == NULL) {
717 		free_job_config();
718 	}
719 
720 	rc = g_run_rc;
721 	if (g_request && !g_shutdown) {
722 		rpc_perform_tests_cb();
723 		if (rc != 0) {
724 			spdk_app_stop(rc);
725 		}
726 	} else {
727 		spdk_app_stop(rc);
728 	}
729 }
730 
731 static void
732 bdevperf_job_end(void *ctx)
733 {
734 	assert(g_main_thread == spdk_get_thread());
735 
736 	if (--g_bdevperf.running_jobs == 0) {
737 		bdevperf_test_done(NULL);
738 	}
739 }
740 
741 static void
742 bdevperf_channel_get_histogram_cb(void *cb_arg, int status, struct spdk_histogram_data *histogram)
743 {
744 	struct spdk_histogram_data *job_hist = cb_arg;
745 
746 	if (status == 0) {
747 		spdk_histogram_data_merge(job_hist, histogram);
748 	}
749 }
750 
751 static void
752 bdevperf_job_empty(struct bdevperf_job *job)
753 {
754 	uint64_t end_tsc = 0;
755 
756 	end_tsc = spdk_get_ticks() - g_start_tsc;
757 	job->run_time_in_usec = end_tsc * SPDK_SEC_TO_USEC / spdk_get_ticks_hz();
758 	/* keep histogram info before channel is destroyed */
759 	spdk_bdev_channel_get_histogram(job->ch, bdevperf_channel_get_histogram_cb,
760 					job->histogram);
761 	spdk_put_io_channel(job->ch);
762 	spdk_bdev_close(job->bdev_desc);
763 	spdk_thread_send_msg(g_main_thread, bdevperf_job_end, NULL);
764 }
765 
766 static void
767 bdevperf_end_task(struct bdevperf_task *task)
768 {
769 	struct bdevperf_job     *job = task->job;
770 
771 	TAILQ_INSERT_TAIL(&job->task_list, task, link);
772 	if (job->is_draining) {
773 		if (job->current_queue_depth == 0) {
774 			bdevperf_job_empty(job);
775 		}
776 	}
777 }
778 
779 static void
780 bdevperf_queue_io_wait_with_cb(struct bdevperf_task *task, spdk_bdev_io_wait_cb cb_fn)
781 {
782 	struct bdevperf_job	*job = task->job;
783 
784 	task->bdev_io_wait.bdev = job->bdev;
785 	task->bdev_io_wait.cb_fn = cb_fn;
786 	task->bdev_io_wait.cb_arg = task;
787 	spdk_bdev_queue_io_wait(job->bdev, job->ch, &task->bdev_io_wait);
788 }
789 
790 static int
791 bdevperf_job_drain(void *ctx)
792 {
793 	struct bdevperf_job *job = ctx;
794 
795 	spdk_poller_unregister(&job->run_timer);
796 	if (job->reset) {
797 		spdk_poller_unregister(&job->reset_timer);
798 	}
799 
800 	job->is_draining = true;
801 
802 	return -1;
803 }
804 
805 static int
806 bdevperf_job_drain_timer(void *ctx)
807 {
808 	struct bdevperf_job *job = ctx;
809 
810 	bdevperf_job_drain(ctx);
811 	if (job->current_queue_depth == 0) {
812 		bdevperf_job_empty(job);
813 	}
814 
815 	return SPDK_POLLER_BUSY;
816 }
817 
818 static void
819 bdevperf_abort_complete(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
820 {
821 	struct bdevperf_task	*task = cb_arg;
822 	struct bdevperf_job	*job = task->job;
823 
824 	job->current_queue_depth--;
825 
826 	if (success) {
827 		job->io_completed++;
828 	} else {
829 		job->io_failed++;
830 		if (!job->continue_on_failure) {
831 			bdevperf_job_drain(job);
832 			g_run_rc = -1;
833 		}
834 	}
835 
836 	spdk_bdev_free_io(bdev_io);
837 	bdevperf_end_task(task);
838 }
839 
840 static int
841 bdevperf_verify_dif(struct bdevperf_task *task, struct iovec *iovs, int iovcnt)
842 {
843 	struct bdevperf_job	*job = task->job;
844 	struct spdk_bdev	*bdev = job->bdev;
845 	struct spdk_dif_ctx	dif_ctx;
846 	struct spdk_dif_error	err_blk = {};
847 	int			rc;
848 	struct spdk_dif_ctx_init_ext_opts dif_opts;
849 
850 	dif_opts.size = SPDK_SIZEOF(&dif_opts, dif_pi_format);
851 	dif_opts.dif_pi_format = SPDK_DIF_PI_FORMAT_16;
852 	rc = spdk_dif_ctx_init(&dif_ctx,
853 			       spdk_bdev_get_block_size(bdev),
854 			       spdk_bdev_get_md_size(bdev),
855 			       spdk_bdev_is_md_interleaved(bdev),
856 			       spdk_bdev_is_dif_head_of_md(bdev),
857 			       spdk_bdev_get_dif_type(bdev),
858 			       job->dif_check_flags,
859 			       task->offset_blocks, 0, 0, 0, 0, &dif_opts);
860 	if (rc != 0) {
861 		fprintf(stderr, "Initialization of DIF context failed\n");
862 		return rc;
863 	}
864 
865 	if (spdk_bdev_is_md_interleaved(bdev)) {
866 		rc = spdk_dif_verify(iovs, iovcnt, job->io_size_blocks, &dif_ctx, &err_blk);
867 	} else {
868 		struct iovec md_iov = {
869 			.iov_base	= task->md_buf,
870 			.iov_len	= spdk_bdev_get_md_size(bdev) * job->io_size_blocks,
871 		};
872 
873 		rc = spdk_dix_verify(iovs, iovcnt, &md_iov, job->io_size_blocks, &dif_ctx, &err_blk);
874 	}
875 
876 	if (rc != 0) {
877 		fprintf(stderr, "DIF/DIX error detected. type=%d, offset=%" PRIu32 "\n",
878 			err_blk.err_type, err_blk.err_offset);
879 	}
880 
881 	return rc;
882 }
883 
884 static void
885 bdevperf_complete(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
886 {
887 	struct bdevperf_job	*job;
888 	struct bdevperf_task	*task = cb_arg;
889 	struct iovec		*iovs;
890 	int			iovcnt;
891 	bool			md_check;
892 	uint64_t		offset_in_ios;
893 	int			rc;
894 
895 	job = task->job;
896 	md_check = spdk_bdev_get_dif_type(job->bdev) == SPDK_DIF_DISABLE;
897 
898 	if (g_error_to_exit == true) {
899 		bdevperf_job_drain(job);
900 	} else if (!success) {
901 		if (!job->reset && !job->continue_on_failure) {
902 			bdevperf_job_drain(job);
903 			g_run_rc = -1;
904 			g_error_to_exit = true;
905 			printf("task offset: %" PRIu64 " on job bdev=%s fails\n",
906 			       task->offset_blocks, job->name);
907 		}
908 	} else if (job->verify || job->reset) {
909 		spdk_bdev_io_get_iovec(bdev_io, &iovs, &iovcnt);
910 		assert(iovcnt == 1);
911 		assert(iovs != NULL);
912 		if (!verify_data(task->buf, job->buf_size, iovs[0].iov_base, iovs[0].iov_len,
913 				 spdk_bdev_get_block_size(job->bdev),
914 				 task->md_buf, spdk_bdev_io_get_md_buf(bdev_io),
915 				 spdk_bdev_get_md_size(job->bdev),
916 				 job->io_size_blocks, md_check)) {
917 			printf("Buffer mismatch! Target: %s Disk Offset: %" PRIu64 "\n", job->name, task->offset_blocks);
918 			bdevperf_job_drain(job);
919 			g_run_rc = -1;
920 		}
921 	} else if (job->dif_check_flags != 0) {
922 		if (task->io_type == SPDK_BDEV_IO_TYPE_READ && spdk_bdev_get_md_size(job->bdev) != 0) {
923 			spdk_bdev_io_get_iovec(bdev_io, &iovs, &iovcnt);
924 			assert(iovcnt == 1);
925 			assert(iovs != NULL);
926 			rc = bdevperf_verify_dif(task, iovs, iovcnt);
927 			if (rc != 0) {
928 				printf("DIF error detected. task offset: %" PRIu64 " on job bdev=%s\n",
929 				       task->offset_blocks, job->name);
930 
931 				success = false;
932 				if (!job->reset && !job->continue_on_failure) {
933 					bdevperf_job_drain(job);
934 					g_run_rc = -1;
935 					g_error_to_exit = true;
936 				}
937 			}
938 		}
939 	}
940 
941 	job->current_queue_depth--;
942 
943 	if (success) {
944 		job->io_completed++;
945 	} else {
946 		job->io_failed++;
947 	}
948 
949 	if (job->verify) {
950 		assert(task->offset_blocks / job->io_size_blocks >= job->ios_base);
951 		offset_in_ios = task->offset_blocks / job->io_size_blocks - job->ios_base;
952 
953 		assert(spdk_bit_array_get(job->outstanding, offset_in_ios) == true);
954 		spdk_bit_array_clear(job->outstanding, offset_in_ios);
955 	}
956 
957 	spdk_bdev_free_io(bdev_io);
958 
959 	/*
960 	 * is_draining indicates when time has expired for the test run
961 	 * and we are just waiting for the previously submitted I/O
962 	 * to complete.  In this case, do not submit a new I/O to replace
963 	 * the one just completed.
964 	 */
965 	if (!job->is_draining) {
966 		bdevperf_submit_single(job, task);
967 	} else {
968 		bdevperf_end_task(task);
969 	}
970 }
971 
972 static void
973 bdevperf_verify_submit_read(void *cb_arg)
974 {
975 	struct bdevperf_job	*job;
976 	struct bdevperf_task	*task = cb_arg;
977 	int			rc;
978 
979 	job = task->job;
980 
981 	/* Read the data back in */
982 	rc = spdk_bdev_read_blocks_with_md(job->bdev_desc, job->ch, task->verify_buf, NULL,
983 					   task->offset_blocks, job->io_size_blocks,
984 					   bdevperf_complete, task);
985 
986 	if (rc == -ENOMEM) {
987 		bdevperf_queue_io_wait_with_cb(task, bdevperf_verify_submit_read);
988 	} else if (rc != 0) {
989 		printf("Failed to submit read: %d\n", rc);
990 		bdevperf_job_drain(job);
991 		g_run_rc = rc;
992 	}
993 }
994 
995 static void
996 bdevperf_verify_write_complete(struct spdk_bdev_io *bdev_io, bool success,
997 			       void *cb_arg)
998 {
999 	if (success) {
1000 		spdk_bdev_free_io(bdev_io);
1001 		bdevperf_verify_submit_read(cb_arg);
1002 	} else {
1003 		bdevperf_complete(bdev_io, success, cb_arg);
1004 	}
1005 }
1006 
1007 static void
1008 bdevperf_zcopy_populate_complete(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
1009 {
1010 	if (!success) {
1011 		bdevperf_complete(bdev_io, success, cb_arg);
1012 		return;
1013 	}
1014 
1015 	spdk_bdev_zcopy_end(bdev_io, false, bdevperf_complete, cb_arg);
1016 }
1017 
1018 static int
1019 bdevperf_generate_dif(struct bdevperf_task *task)
1020 {
1021 	struct bdevperf_job	*job = task->job;
1022 	struct spdk_bdev	*bdev = job->bdev;
1023 	struct spdk_dif_ctx	dif_ctx;
1024 	int			rc;
1025 	struct spdk_dif_ctx_init_ext_opts dif_opts;
1026 
1027 	dif_opts.size = SPDK_SIZEOF(&dif_opts, dif_pi_format);
1028 	dif_opts.dif_pi_format = SPDK_DIF_PI_FORMAT_16;
1029 	rc = spdk_dif_ctx_init(&dif_ctx,
1030 			       spdk_bdev_get_block_size(bdev),
1031 			       spdk_bdev_get_md_size(bdev),
1032 			       spdk_bdev_is_md_interleaved(bdev),
1033 			       spdk_bdev_is_dif_head_of_md(bdev),
1034 			       spdk_bdev_get_dif_type(bdev),
1035 			       job->dif_check_flags,
1036 			       task->offset_blocks, 0, 0, 0, 0, &dif_opts);
1037 	if (rc != 0) {
1038 		fprintf(stderr, "Initialization of DIF context failed\n");
1039 		return rc;
1040 	}
1041 
1042 	if (spdk_bdev_is_md_interleaved(bdev)) {
1043 		rc = spdk_dif_generate(&task->iov, 1, job->io_size_blocks, &dif_ctx);
1044 	} else {
1045 		struct iovec md_iov = {
1046 			.iov_base	= task->md_buf,
1047 			.iov_len	= spdk_bdev_get_md_size(bdev) * job->io_size_blocks,
1048 		};
1049 
1050 		rc = spdk_dix_generate(&task->iov, 1, &md_iov, job->io_size_blocks, &dif_ctx);
1051 	}
1052 
1053 	if (rc != 0) {
1054 		fprintf(stderr, "Generation of DIF/DIX failed\n");
1055 	}
1056 
1057 	return rc;
1058 }
1059 
1060 static void
1061 bdevperf_submit_task(void *arg)
1062 {
1063 	struct bdevperf_task	*task = arg;
1064 	struct bdevperf_job	*job = task->job;
1065 	struct spdk_bdev_desc	*desc;
1066 	struct spdk_io_channel	*ch;
1067 	spdk_bdev_io_completion_cb cb_fn;
1068 	uint64_t		offset_in_ios;
1069 	int			rc = 0;
1070 
1071 	desc = job->bdev_desc;
1072 	ch = job->ch;
1073 
1074 	switch (task->io_type) {
1075 	case SPDK_BDEV_IO_TYPE_WRITE:
1076 		if (spdk_bdev_get_md_size(job->bdev) != 0 && job->dif_check_flags != 0) {
1077 			rc = bdevperf_generate_dif(task);
1078 		}
1079 		if (rc == 0) {
1080 			cb_fn = (job->verify || job->reset) ? bdevperf_verify_write_complete : bdevperf_complete;
1081 
1082 			if (g_zcopy) {
1083 				spdk_bdev_zcopy_end(task->bdev_io, true, cb_fn, task);
1084 				return;
1085 			} else {
1086 				rc = spdk_bdev_writev_blocks_with_md(desc, ch, &task->iov, 1,
1087 								     task->md_buf,
1088 								     task->offset_blocks,
1089 								     job->io_size_blocks,
1090 								     cb_fn, task);
1091 			}
1092 		}
1093 		break;
1094 	case SPDK_BDEV_IO_TYPE_FLUSH:
1095 		rc = spdk_bdev_flush_blocks(desc, ch, task->offset_blocks,
1096 					    job->io_size_blocks, bdevperf_complete, task);
1097 		break;
1098 	case SPDK_BDEV_IO_TYPE_UNMAP:
1099 		rc = spdk_bdev_unmap_blocks(desc, ch, task->offset_blocks,
1100 					    job->io_size_blocks, bdevperf_complete, task);
1101 		break;
1102 	case SPDK_BDEV_IO_TYPE_WRITE_ZEROES:
1103 		rc = spdk_bdev_write_zeroes_blocks(desc, ch, task->offset_blocks,
1104 						   job->io_size_blocks, bdevperf_complete, task);
1105 		break;
1106 	case SPDK_BDEV_IO_TYPE_READ:
1107 		if (g_zcopy) {
1108 			rc = spdk_bdev_zcopy_start(desc, ch, NULL, 0, task->offset_blocks, job->io_size_blocks,
1109 						   true, bdevperf_zcopy_populate_complete, task);
1110 		} else {
1111 			rc = spdk_bdev_read_blocks_with_md(desc, ch, task->buf, task->md_buf,
1112 							   task->offset_blocks,
1113 							   job->io_size_blocks,
1114 							   bdevperf_complete, task);
1115 		}
1116 		break;
1117 	case SPDK_BDEV_IO_TYPE_ABORT:
1118 		rc = spdk_bdev_abort(desc, ch, task->task_to_abort, bdevperf_abort_complete, task);
1119 		break;
1120 	default:
1121 		assert(false);
1122 		rc = -EINVAL;
1123 		break;
1124 	}
1125 
1126 	if (rc == -ENOMEM) {
1127 		bdevperf_queue_io_wait_with_cb(task, bdevperf_submit_task);
1128 		return;
1129 	} else if (rc != 0) {
1130 		printf("Failed to submit bdev_io: %d\n", rc);
1131 		if (job->verify) {
1132 			assert(task->offset_blocks / job->io_size_blocks >= job->ios_base);
1133 			offset_in_ios = task->offset_blocks / job->io_size_blocks - job->ios_base;
1134 
1135 			assert(spdk_bit_array_get(job->outstanding, offset_in_ios) == true);
1136 			spdk_bit_array_clear(job->outstanding, offset_in_ios);
1137 		}
1138 		bdevperf_job_drain(job);
1139 		g_run_rc = rc;
1140 		return;
1141 	}
1142 
1143 	job->current_queue_depth++;
1144 }
1145 
1146 static void
1147 bdevperf_zcopy_get_buf_complete(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
1148 {
1149 	struct bdevperf_task	*task = cb_arg;
1150 	struct bdevperf_job	*job = task->job;
1151 	struct iovec		*iovs;
1152 	int			iovcnt;
1153 
1154 	if (!success) {
1155 		bdevperf_job_drain(job);
1156 		g_run_rc = -1;
1157 		return;
1158 	}
1159 
1160 	task->bdev_io = bdev_io;
1161 	task->io_type = SPDK_BDEV_IO_TYPE_WRITE;
1162 
1163 	if (job->verify || job->reset) {
1164 		/* When job->verify or job->reset is enabled, task->buf is used for
1165 		 *  verification of read after write.  For write I/O, when zcopy APIs
1166 		 *  are used, task->buf cannot be used, and data must be written to
1167 		 *  the data buffer allocated underneath bdev layer instead.
1168 		 *  Hence we copy task->buf to the allocated data buffer here.
1169 		 */
1170 		spdk_bdev_io_get_iovec(bdev_io, &iovs, &iovcnt);
1171 		assert(iovcnt == 1);
1172 		assert(iovs != NULL);
1173 
1174 		copy_data(iovs[0].iov_base, iovs[0].iov_len, task->buf, job->buf_size,
1175 			  spdk_bdev_get_block_size(job->bdev),
1176 			  spdk_bdev_io_get_md_buf(bdev_io), task->md_buf,
1177 			  spdk_bdev_get_md_size(job->bdev), job->io_size_blocks);
1178 	}
1179 
1180 	bdevperf_submit_task(task);
1181 }
1182 
1183 static void
1184 bdevperf_prep_zcopy_write_task(void *arg)
1185 {
1186 	struct bdevperf_task	*task = arg;
1187 	struct bdevperf_job	*job = task->job;
1188 	int			rc;
1189 
1190 	rc = spdk_bdev_zcopy_start(job->bdev_desc, job->ch, NULL, 0,
1191 				   task->offset_blocks, job->io_size_blocks,
1192 				   false, bdevperf_zcopy_get_buf_complete, task);
1193 	if (rc != 0) {
1194 		assert(rc == -ENOMEM);
1195 		bdevperf_queue_io_wait_with_cb(task, bdevperf_prep_zcopy_write_task);
1196 		return;
1197 	}
1198 
1199 	job->current_queue_depth++;
1200 }
1201 
1202 static struct bdevperf_task *
1203 bdevperf_job_get_task(struct bdevperf_job *job)
1204 {
1205 	struct bdevperf_task *task;
1206 
1207 	task = TAILQ_FIRST(&job->task_list);
1208 	if (!task) {
1209 		printf("Task allocation failed\n");
1210 		abort();
1211 	}
1212 
1213 	TAILQ_REMOVE(&job->task_list, task, link);
1214 	return task;
1215 }
1216 
1217 static void
1218 bdevperf_submit_single(struct bdevperf_job *job, struct bdevperf_task *task)
1219 {
1220 	uint64_t offset_in_ios;
1221 	uint64_t rand_value;
1222 	uint32_t first_clear;
1223 
1224 	if (job->zipf) {
1225 		offset_in_ios = spdk_zipf_generate(job->zipf);
1226 	} else if (job->is_random) {
1227 		/* RAND_MAX is only INT32_MAX, so use 2 calls to rand_r to
1228 		 * get a large enough value to ensure we are issuing I/O
1229 		 * uniformly across the whole bdev.
1230 		 */
1231 		rand_value = (uint64_t)rand_r(&job->seed) * RAND_MAX + rand_r(&job->seed);
1232 		offset_in_ios = rand_value % job->size_in_ios;
1233 
1234 		if (g_random_map) {
1235 			/* Make sure, that the offset does not exceed the maximum size
1236 			 * of the bit array (verified during job creation)
1237 			 */
1238 			assert(offset_in_ios < UINT32_MAX);
1239 
1240 			first_clear = spdk_bit_array_find_first_clear(job->random_map, (uint32_t)offset_in_ios);
1241 
1242 			if (first_clear == UINT32_MAX) {
1243 				first_clear = spdk_bit_array_find_first_clear(job->random_map, 0);
1244 
1245 				if (first_clear == UINT32_MAX) {
1246 					/* If there are no more clear bits in the array, we start over
1247 					 * and select the previously selected random value.
1248 					 */
1249 					spdk_bit_array_clear_mask(job->random_map);
1250 					first_clear = (uint32_t)offset_in_ios;
1251 				}
1252 			}
1253 
1254 			spdk_bit_array_set(job->random_map, first_clear);
1255 
1256 			offset_in_ios = first_clear;
1257 		}
1258 	} else {
1259 		offset_in_ios = job->offset_in_ios++;
1260 		if (job->offset_in_ios == job->size_in_ios) {
1261 			job->offset_in_ios = 0;
1262 		}
1263 
1264 		/* Increment of offset_in_ios if there's already an outstanding IO
1265 		 * to that location. We only need this with job->verify as random
1266 		 * offsets are not supported with job->verify at this time.
1267 		 */
1268 		if (job->verify) {
1269 			assert(spdk_bit_array_find_first_clear(job->outstanding, 0) != UINT32_MAX);
1270 
1271 			while (spdk_bit_array_get(job->outstanding, offset_in_ios)) {
1272 				offset_in_ios = job->offset_in_ios++;
1273 				if (job->offset_in_ios == job->size_in_ios) {
1274 					job->offset_in_ios = 0;
1275 				}
1276 			}
1277 			spdk_bit_array_set(job->outstanding, offset_in_ios);
1278 		}
1279 	}
1280 
1281 	/* For multi-thread to same job, offset_in_ios is relative
1282 	 * to the LBA range assigned for that job. job->offset_blocks
1283 	 * is absolute (entire bdev LBA range).
1284 	 */
1285 	task->offset_blocks = (offset_in_ios + job->ios_base) * job->io_size_blocks;
1286 
1287 	if (job->flush) {
1288 		task->io_type = SPDK_BDEV_IO_TYPE_FLUSH;
1289 	} else if (job->unmap) {
1290 		task->io_type = SPDK_BDEV_IO_TYPE_UNMAP;
1291 	} else if (job->write_zeroes) {
1292 		task->io_type = SPDK_BDEV_IO_TYPE_WRITE_ZEROES;
1293 	} else if ((job->rw_percentage == 100) ||
1294 		   (job->rw_percentage != 0 && ((rand_r(&job->seed) % 100) < job->rw_percentage))) {
1295 		assert(!job->verify);
1296 		task->io_type = SPDK_BDEV_IO_TYPE_READ;
1297 	} else {
1298 		if (job->verify || job->reset || g_unique_writes) {
1299 			generate_data(job, task->buf, task->md_buf, g_unique_writes);
1300 		}
1301 		if (g_zcopy) {
1302 			bdevperf_prep_zcopy_write_task(task);
1303 			return;
1304 		} else {
1305 			task->iov.iov_base = task->buf;
1306 			task->iov.iov_len = job->buf_size;
1307 			task->io_type = SPDK_BDEV_IO_TYPE_WRITE;
1308 		}
1309 	}
1310 
1311 	bdevperf_submit_task(task);
1312 }
1313 
1314 static int reset_job(void *arg);
1315 
1316 static void
1317 reset_cb(struct spdk_bdev_io *bdev_io, bool success, void *cb_arg)
1318 {
1319 	struct bdevperf_task	*task = cb_arg;
1320 	struct bdevperf_job	*job = task->job;
1321 
1322 	if (!success) {
1323 		printf("Reset blockdev=%s failed\n", spdk_bdev_get_name(job->bdev));
1324 		bdevperf_job_drain(job);
1325 		g_run_rc = -1;
1326 	}
1327 
1328 	TAILQ_INSERT_TAIL(&job->task_list, task, link);
1329 	spdk_bdev_free_io(bdev_io);
1330 
1331 	job->reset_timer = SPDK_POLLER_REGISTER(reset_job, job,
1332 						10 * SPDK_SEC_TO_USEC);
1333 }
1334 
1335 static int
1336 reset_job(void *arg)
1337 {
1338 	struct bdevperf_job *job = arg;
1339 	struct bdevperf_task *task;
1340 	int rc;
1341 
1342 	spdk_poller_unregister(&job->reset_timer);
1343 
1344 	/* Do reset. */
1345 	task = bdevperf_job_get_task(job);
1346 	rc = spdk_bdev_reset(job->bdev_desc, job->ch,
1347 			     reset_cb, task);
1348 	if (rc) {
1349 		printf("Reset failed: %d\n", rc);
1350 		bdevperf_job_drain(job);
1351 		g_run_rc = -1;
1352 	}
1353 
1354 	return -1;
1355 }
1356 
1357 static void
1358 bdevperf_timeout_cb(void *cb_arg, struct spdk_bdev_io *bdev_io)
1359 {
1360 	struct bdevperf_job *job = cb_arg;
1361 	struct bdevperf_task *task;
1362 
1363 	job->io_timeout++;
1364 
1365 	if (job->is_draining || !job->abort ||
1366 	    !spdk_bdev_io_type_supported(job->bdev, SPDK_BDEV_IO_TYPE_ABORT)) {
1367 		return;
1368 	}
1369 
1370 	task = bdevperf_job_get_task(job);
1371 	if (task == NULL) {
1372 		return;
1373 	}
1374 
1375 	task->task_to_abort = spdk_bdev_io_get_cb_arg(bdev_io);
1376 	task->io_type = SPDK_BDEV_IO_TYPE_ABORT;
1377 
1378 	bdevperf_submit_task(task);
1379 }
1380 
1381 static void
1382 bdevperf_job_run(void *ctx)
1383 {
1384 	struct bdevperf_job *job = ctx;
1385 	struct bdevperf_task *task;
1386 	int i;
1387 
1388 	/* Submit initial I/O for this job. Each time one
1389 	 * completes, another will be submitted. */
1390 
1391 	/* Start a timer to stop this I/O chain when the run is over */
1392 	job->run_timer = SPDK_POLLER_REGISTER(bdevperf_job_drain_timer, job, g_time_in_usec);
1393 	if (job->reset) {
1394 		job->reset_timer = SPDK_POLLER_REGISTER(reset_job, job,
1395 							10 * SPDK_SEC_TO_USEC);
1396 	}
1397 
1398 	spdk_bdev_set_timeout(job->bdev_desc, g_timeout_in_sec, bdevperf_timeout_cb, job);
1399 
1400 	for (i = 0; i < job->queue_depth; i++) {
1401 		task = bdevperf_job_get_task(job);
1402 		bdevperf_submit_single(job, task);
1403 	}
1404 }
1405 
1406 static void
1407 _performance_dump_done(void *ctx)
1408 {
1409 	struct bdevperf_aggregate_stats *stats = ctx;
1410 	double average_latency;
1411 
1412 	printf("\r =================================================================================="
1413 	       "=================================\n");
1414 	printf("\r %-28s: %10s %10.2f %10.2f",
1415 	       "Total", "", stats->total_io_per_second, stats->total_mb_per_second);
1416 	printf(" %10.2f %8.2f",
1417 	       stats->total_failed_per_second, stats->total_timeout_per_second);
1418 
1419 	average_latency = ((double)stats->total_tsc / stats->total_io_completed) * SPDK_SEC_TO_USEC /
1420 			  spdk_get_ticks_hz();
1421 	printf(" %10.2f %10.2f %10.2f\n", average_latency, stats->min_latency, stats->max_latency);
1422 	printf("\n");
1423 
1424 	fflush(stdout);
1425 
1426 	g_performance_dump_active = false;
1427 
1428 	free(stats);
1429 }
1430 
1431 static void
1432 _performance_dump(void *ctx)
1433 {
1434 	struct bdevperf_aggregate_stats *stats = ctx;
1435 
1436 	performance_dump_job(stats, stats->current_job);
1437 
1438 	/* This assumes the jobs list is static after start up time.
1439 	 * That's true right now, but if that ever changed this would need a lock. */
1440 	stats->current_job = TAILQ_NEXT(stats->current_job, link);
1441 	if (stats->current_job == NULL) {
1442 		spdk_thread_send_msg(g_main_thread, _performance_dump_done, stats);
1443 	} else {
1444 		spdk_thread_send_msg(stats->current_job->thread, _performance_dump, stats);
1445 	}
1446 }
1447 
1448 static int
1449 performance_statistics_thread(void *arg)
1450 {
1451 	struct bdevperf_aggregate_stats *stats;
1452 
1453 	if (g_performance_dump_active) {
1454 		return -1;
1455 	}
1456 
1457 	g_performance_dump_active = true;
1458 
1459 	stats = calloc(1, sizeof(*stats));
1460 	if (stats == NULL) {
1461 		return -1;
1462 	}
1463 
1464 	stats->min_latency = (double)UINT64_MAX;
1465 
1466 	g_show_performance_period_num++;
1467 
1468 	stats->io_time_in_usec = g_show_performance_period_num * g_show_performance_period_in_usec;
1469 	stats->ema_period = g_show_performance_ema_period;
1470 
1471 	/* Iterate all of the jobs to gather stats
1472 	 * These jobs will not get removed here until a final performance dump is run,
1473 	 * so this should be safe without locking.
1474 	 */
1475 	stats->current_job = TAILQ_FIRST(&g_bdevperf.jobs);
1476 	if (stats->current_job == NULL) {
1477 		spdk_thread_send_msg(g_main_thread, _performance_dump_done, stats);
1478 	} else {
1479 		spdk_thread_send_msg(stats->current_job->thread, _performance_dump, stats);
1480 	}
1481 
1482 	return -1;
1483 }
1484 
1485 static void
1486 bdevperf_test(void)
1487 {
1488 	struct bdevperf_job *job;
1489 
1490 	printf("Running I/O for %" PRIu64 " seconds...\n", g_time_in_usec / (uint64_t)SPDK_SEC_TO_USEC);
1491 	fflush(stdout);
1492 
1493 	/* Start a timer to dump performance numbers */
1494 	g_start_tsc = spdk_get_ticks();
1495 	if (g_show_performance_real_time && !g_perf_timer) {
1496 		printf("%*s\n", 107, "Latency(us)");
1497 		printf("\r %-*s: %10s %10s %10s %10s %8s %10s %10s %10s\n",
1498 		       28, "Device Information", "runtime(s)", "IOPS", "MiB/s", "Fail/s", "TO/s", "Average", "min", "max");
1499 
1500 		g_perf_timer = SPDK_POLLER_REGISTER(performance_statistics_thread, NULL,
1501 						    g_show_performance_period_in_usec);
1502 	}
1503 
1504 	/* Iterate jobs to start all I/O */
1505 	TAILQ_FOREACH(job, &g_bdevperf.jobs, link) {
1506 		g_bdevperf.running_jobs++;
1507 		spdk_thread_send_msg(job->thread, bdevperf_job_run, job);
1508 	}
1509 }
1510 
1511 static void
1512 bdevperf_bdev_removed(enum spdk_bdev_event_type type, struct spdk_bdev *bdev, void *event_ctx)
1513 {
1514 	struct bdevperf_job *job = event_ctx;
1515 
1516 	if (SPDK_BDEV_EVENT_REMOVE == type) {
1517 		bdevperf_job_drain(job);
1518 	}
1519 }
1520 
1521 static void
1522 bdevperf_histogram_status_cb(void *cb_arg, int status)
1523 {
1524 	if (status != 0) {
1525 		g_run_rc = status;
1526 		if (g_continue_on_failure == false) {
1527 			g_error_to_exit = true;
1528 		}
1529 	}
1530 
1531 	if (--g_bdev_count == 0) {
1532 		if (g_run_rc == 0) {
1533 			/* Ready to run the test */
1534 			bdevperf_test();
1535 		} else {
1536 			bdevperf_test_done(NULL);
1537 		}
1538 	}
1539 }
1540 
1541 static uint32_t g_construct_job_count = 0;
1542 
1543 static int
1544 _bdevperf_enable_histogram(void *ctx, struct spdk_bdev *bdev)
1545 {
1546 	bool *enable = ctx;
1547 
1548 	g_bdev_count++;
1549 
1550 	spdk_bdev_histogram_enable(bdev, bdevperf_histogram_status_cb, NULL, *enable);
1551 
1552 	return 0;
1553 }
1554 
1555 static void
1556 bdevperf_enable_histogram(bool enable)
1557 {
1558 	struct spdk_bdev *bdev;
1559 	int rc;
1560 
1561 	/* increment initial g_bdev_count so that it will never reach 0 in the middle of iteration */
1562 	g_bdev_count = 1;
1563 
1564 	if (g_job_bdev_name != NULL) {
1565 		bdev = spdk_bdev_get_by_name(g_job_bdev_name);
1566 		if (bdev) {
1567 			rc = _bdevperf_enable_histogram(&enable, bdev);
1568 		} else {
1569 			fprintf(stderr, "Unable to find bdev '%s'\n", g_job_bdev_name);
1570 			rc = -1;
1571 		}
1572 	} else {
1573 		rc = spdk_for_each_bdev_leaf(&enable, _bdevperf_enable_histogram);
1574 	}
1575 
1576 	bdevperf_histogram_status_cb(NULL, rc);
1577 }
1578 
1579 static void
1580 _bdevperf_construct_job_done(void *ctx)
1581 {
1582 	if (--g_construct_job_count == 0) {
1583 		if (g_run_rc != 0) {
1584 			/* Something failed. */
1585 			bdevperf_test_done(NULL);
1586 			return;
1587 		}
1588 
1589 		/* always enable histogram. */
1590 		bdevperf_enable_histogram(true);
1591 	} else if (g_run_rc != 0) {
1592 		/* Reset error as some jobs constructed right */
1593 		g_run_rc = 0;
1594 		if (g_continue_on_failure == false) {
1595 			g_error_to_exit = true;
1596 		}
1597 	}
1598 }
1599 
1600 /* Checkformat will not allow to use inlined type,
1601    this is a workaround */
1602 typedef struct spdk_thread *spdk_thread_t;
1603 
1604 static spdk_thread_t
1605 construct_job_thread(struct spdk_cpuset *cpumask, const char *tag)
1606 {
1607 	struct spdk_cpuset tmp;
1608 
1609 	/* This function runs on the main thread. */
1610 	assert(g_main_thread == spdk_get_thread());
1611 
1612 	/* Handle default mask */
1613 	if (spdk_cpuset_count(cpumask) == 0) {
1614 		cpumask = &g_all_cpuset;
1615 	}
1616 
1617 	/* Warn user that mask might need to be changed */
1618 	spdk_cpuset_copy(&tmp, cpumask);
1619 	spdk_cpuset_or(&tmp, &g_all_cpuset);
1620 	if (!spdk_cpuset_equal(&tmp, &g_all_cpuset)) {
1621 		fprintf(stderr, "cpumask for '%s' is too big\n", tag);
1622 	}
1623 
1624 	return spdk_thread_create(tag, cpumask);
1625 }
1626 
1627 static uint32_t
1628 _get_next_core(void)
1629 {
1630 	static uint32_t current_core = SPDK_ENV_LCORE_ID_ANY;
1631 
1632 	if (current_core == SPDK_ENV_LCORE_ID_ANY) {
1633 		current_core = spdk_env_get_first_core();
1634 		return current_core;
1635 	}
1636 
1637 	current_core = spdk_env_get_next_core(current_core);
1638 	if (current_core == SPDK_ENV_LCORE_ID_ANY) {
1639 		current_core = spdk_env_get_first_core();
1640 	}
1641 
1642 	return current_core;
1643 }
1644 
1645 static void
1646 _bdevperf_construct_job(void *ctx)
1647 {
1648 	struct bdevperf_job *job = ctx;
1649 	int rc;
1650 
1651 	rc = spdk_bdev_open_ext(spdk_bdev_get_name(job->bdev), true, bdevperf_bdev_removed, job,
1652 				&job->bdev_desc);
1653 	if (rc != 0) {
1654 		SPDK_ERRLOG("Could not open leaf bdev %s, error=%d\n", spdk_bdev_get_name(job->bdev), rc);
1655 		g_run_rc = -EINVAL;
1656 		goto end;
1657 	}
1658 
1659 	if (g_zcopy) {
1660 		if (!spdk_bdev_io_type_supported(job->bdev, SPDK_BDEV_IO_TYPE_ZCOPY)) {
1661 			printf("Test requires ZCOPY but bdev module does not support ZCOPY\n");
1662 			g_run_rc = -ENOTSUP;
1663 			goto end;
1664 		}
1665 	}
1666 
1667 	job->ch = spdk_bdev_get_io_channel(job->bdev_desc);
1668 	if (!job->ch) {
1669 		SPDK_ERRLOG("Could not get io_channel for device %s, error=%d\n", spdk_bdev_get_name(job->bdev),
1670 			    rc);
1671 		spdk_bdev_close(job->bdev_desc);
1672 		TAILQ_REMOVE(&g_bdevperf.jobs, job, link);
1673 		g_run_rc = -ENOMEM;
1674 		goto end;
1675 	}
1676 
1677 end:
1678 	spdk_thread_send_msg(g_main_thread, _bdevperf_construct_job_done, NULL);
1679 }
1680 
1681 static void
1682 job_init_rw(struct bdevperf_job *job, enum job_config_rw rw)
1683 {
1684 	switch (rw) {
1685 	case JOB_CONFIG_RW_READ:
1686 		job->rw_percentage = 100;
1687 		break;
1688 	case JOB_CONFIG_RW_WRITE:
1689 		job->rw_percentage = 0;
1690 		break;
1691 	case JOB_CONFIG_RW_RANDREAD:
1692 		job->is_random = true;
1693 		job->rw_percentage = 100;
1694 		job->seed = rand();
1695 		break;
1696 	case JOB_CONFIG_RW_RANDWRITE:
1697 		job->is_random = true;
1698 		job->rw_percentage = 0;
1699 		job->seed = rand();
1700 		break;
1701 	case JOB_CONFIG_RW_RW:
1702 		job->is_random = false;
1703 		break;
1704 	case JOB_CONFIG_RW_RANDRW:
1705 		job->is_random = true;
1706 		job->seed = rand();
1707 		break;
1708 	case JOB_CONFIG_RW_RESET:
1709 		/* Reset shares the flow with verify. */
1710 		job->reset = true;
1711 	/* fallthrough */
1712 	case JOB_CONFIG_RW_VERIFY:
1713 		job->verify = true;
1714 		/* For verify flow read is done on write completion
1715 		 * callback only, rw_percentage shall not be used. */
1716 		job->rw_percentage = 0;
1717 		break;
1718 	case JOB_CONFIG_RW_UNMAP:
1719 		job->unmap = true;
1720 		break;
1721 	case JOB_CONFIG_RW_FLUSH:
1722 		job->flush = true;
1723 		break;
1724 	case JOB_CONFIG_RW_WRITE_ZEROES:
1725 		job->write_zeroes = true;
1726 		break;
1727 	}
1728 }
1729 
1730 static int
1731 bdevperf_construct_job(struct spdk_bdev *bdev, struct job_config *config,
1732 		       struct spdk_thread *thread)
1733 {
1734 	struct bdevperf_job *job;
1735 	struct bdevperf_task *task;
1736 	int block_size, data_block_size;
1737 	int rc;
1738 	int task_num, n;
1739 
1740 	block_size = spdk_bdev_get_block_size(bdev);
1741 	data_block_size = spdk_bdev_get_data_block_size(bdev);
1742 
1743 	job = calloc(1, sizeof(struct bdevperf_job));
1744 	if (!job) {
1745 		fprintf(stderr, "Unable to allocate memory for new job.\n");
1746 		return -ENOMEM;
1747 	}
1748 
1749 	job->name = strdup(spdk_bdev_get_name(bdev));
1750 	if (!job->name) {
1751 		fprintf(stderr, "Unable to allocate memory for job name.\n");
1752 		bdevperf_job_free(job);
1753 		return -ENOMEM;
1754 	}
1755 
1756 	job->workload_type = config->rw;
1757 	job->io_size = config->bs;
1758 	job->rw_percentage = config->rwmixread;
1759 	job->continue_on_failure = g_continue_on_failure;
1760 	job->queue_depth = config->iodepth;
1761 	job->bdev = bdev;
1762 	job->io_size_blocks = job->io_size / data_block_size;
1763 	job->buf_size = job->io_size_blocks * block_size;
1764 	job->abort = g_abort;
1765 	job_init_rw(job, config->rw);
1766 
1767 	if ((job->io_size % data_block_size) != 0) {
1768 		SPDK_ERRLOG("IO size (%d) is not multiples of data block size of bdev %s (%"PRIu32")\n",
1769 			    job->io_size, spdk_bdev_get_name(bdev), data_block_size);
1770 		bdevperf_job_free(job);
1771 		return -ENOTSUP;
1772 	}
1773 
1774 	if (job->unmap && !spdk_bdev_io_type_supported(bdev, SPDK_BDEV_IO_TYPE_UNMAP)) {
1775 		printf("Skipping %s because it does not support unmap\n", spdk_bdev_get_name(bdev));
1776 		bdevperf_job_free(job);
1777 		return -ENOTSUP;
1778 	}
1779 
1780 	if (spdk_bdev_is_dif_check_enabled(bdev, SPDK_DIF_CHECK_TYPE_REFTAG)) {
1781 		job->dif_check_flags |= SPDK_DIF_FLAGS_REFTAG_CHECK;
1782 	}
1783 	if (spdk_bdev_is_dif_check_enabled(bdev, SPDK_DIF_CHECK_TYPE_GUARD)) {
1784 		job->dif_check_flags |= SPDK_DIF_FLAGS_GUARD_CHECK;
1785 	}
1786 
1787 	job->offset_in_ios = 0;
1788 
1789 	if (config->length != 0) {
1790 		/* Use subset of disk */
1791 		job->size_in_ios = config->length / job->io_size_blocks;
1792 		job->ios_base = config->offset / job->io_size_blocks;
1793 	} else {
1794 		/* Use whole disk */
1795 		job->size_in_ios = spdk_bdev_get_num_blocks(bdev) / job->io_size_blocks;
1796 		job->ios_base = 0;
1797 	}
1798 
1799 	if (job->is_random && g_zipf_theta > 0) {
1800 		job->zipf = spdk_zipf_create(job->size_in_ios, g_zipf_theta, 0);
1801 	}
1802 
1803 	if (job->verify) {
1804 		if (job->size_in_ios >= UINT32_MAX) {
1805 			SPDK_ERRLOG("Due to constraints of verify operation, the job storage capacity is too large\n");
1806 			bdevperf_job_free(job);
1807 			return -ENOMEM;
1808 		}
1809 		job->outstanding = spdk_bit_array_create(job->size_in_ios);
1810 		if (job->outstanding == NULL) {
1811 			SPDK_ERRLOG("Could not create outstanding array bitmap for bdev %s\n",
1812 				    spdk_bdev_get_name(bdev));
1813 			bdevperf_job_free(job);
1814 			return -ENOMEM;
1815 		}
1816 		if (job->queue_depth > (int)job->size_in_ios) {
1817 			SPDK_WARNLOG("Due to constraints of verify job, queue depth (-q, %d) can't exceed the number of IO "
1818 				     "requests which can be submitted to the bdev %s simultaneously (%"PRIu64"). "
1819 				     "Queue depth is limited to %"PRIu64"\n",
1820 				     job->queue_depth, job->name, job->size_in_ios, job->size_in_ios);
1821 			job->queue_depth = (int)job->size_in_ios;
1822 		}
1823 	}
1824 
1825 	job->histogram = spdk_histogram_data_alloc();
1826 	if (job->histogram == NULL) {
1827 		fprintf(stderr, "Failed to allocate histogram\n");
1828 		bdevperf_job_free(job);
1829 		return -ENOMEM;
1830 	}
1831 
1832 	TAILQ_INIT(&job->task_list);
1833 
1834 	if (g_random_map) {
1835 		if (job->size_in_ios >= UINT32_MAX) {
1836 			SPDK_ERRLOG("Due to constraints of the random map, the job storage capacity is too large\n");
1837 			bdevperf_job_free(job);
1838 			return -ENOMEM;
1839 		}
1840 		job->random_map = spdk_bit_array_create(job->size_in_ios);
1841 		if (job->random_map == NULL) {
1842 			SPDK_ERRLOG("Could not create random_map array bitmap for bdev %s\n",
1843 				    spdk_bdev_get_name(bdev));
1844 			bdevperf_job_free(job);
1845 			return -ENOMEM;
1846 		}
1847 	}
1848 
1849 	task_num = job->queue_depth;
1850 	if (job->reset) {
1851 		task_num += 1;
1852 	}
1853 	if (job->abort) {
1854 		task_num += job->queue_depth;
1855 	}
1856 
1857 	TAILQ_INSERT_TAIL(&g_bdevperf.jobs, job, link);
1858 
1859 	for (n = 0; n < task_num; n++) {
1860 		task = calloc(1, sizeof(struct bdevperf_task));
1861 		if (!task) {
1862 			fprintf(stderr, "Failed to allocate task from memory\n");
1863 			spdk_zipf_free(&job->zipf);
1864 			return -ENOMEM;
1865 		}
1866 
1867 		task->buf = spdk_zmalloc(job->buf_size, spdk_bdev_get_buf_align(job->bdev), NULL,
1868 					 SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1869 		if (!task->buf) {
1870 			fprintf(stderr, "Cannot allocate buf for task=%p\n", task);
1871 			spdk_zipf_free(&job->zipf);
1872 			free(task);
1873 			return -ENOMEM;
1874 		}
1875 
1876 		if (job->verify && job->buf_size > SPDK_BDEV_LARGE_BUF_MAX_SIZE) {
1877 			task->verify_buf = spdk_zmalloc(job->buf_size, spdk_bdev_get_buf_align(job->bdev), NULL,
1878 							SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1879 			if (!task->verify_buf) {
1880 				fprintf(stderr, "Cannot allocate buf_verify for task=%p\n", task);
1881 				spdk_free(task->buf);
1882 				spdk_zipf_free(&job->zipf);
1883 				free(task);
1884 				return -ENOMEM;
1885 			}
1886 
1887 		}
1888 
1889 		if (spdk_bdev_is_md_separate(job->bdev)) {
1890 			task->md_buf = spdk_zmalloc(job->io_size_blocks *
1891 						    spdk_bdev_get_md_size(job->bdev), 0, NULL,
1892 						    SPDK_ENV_LCORE_ID_ANY, SPDK_MALLOC_DMA);
1893 			if (!task->md_buf) {
1894 				fprintf(stderr, "Cannot allocate md buf for task=%p\n", task);
1895 				spdk_zipf_free(&job->zipf);
1896 				spdk_free(task->verify_buf);
1897 				spdk_free(task->buf);
1898 				free(task);
1899 				return -ENOMEM;
1900 			}
1901 		}
1902 
1903 		task->job = job;
1904 		TAILQ_INSERT_TAIL(&job->task_list, task, link);
1905 	}
1906 
1907 	job->thread = thread;
1908 
1909 	g_construct_job_count++;
1910 
1911 	rc = spdk_thread_send_msg(thread, _bdevperf_construct_job, job);
1912 	assert(rc == 0);
1913 
1914 	return rc;
1915 }
1916 
1917 static int
1918 parse_rw(const char *str, enum job_config_rw ret)
1919 {
1920 	if (str == NULL) {
1921 		return ret;
1922 	}
1923 
1924 	if (!strcmp(str, "read")) {
1925 		ret = JOB_CONFIG_RW_READ;
1926 	} else if (!strcmp(str, "randread")) {
1927 		ret = JOB_CONFIG_RW_RANDREAD;
1928 	} else if (!strcmp(str, "write")) {
1929 		ret = JOB_CONFIG_RW_WRITE;
1930 	} else if (!strcmp(str, "randwrite")) {
1931 		ret = JOB_CONFIG_RW_RANDWRITE;
1932 	} else if (!strcmp(str, "verify")) {
1933 		ret = JOB_CONFIG_RW_VERIFY;
1934 	} else if (!strcmp(str, "reset")) {
1935 		ret = JOB_CONFIG_RW_RESET;
1936 	} else if (!strcmp(str, "unmap")) {
1937 		ret = JOB_CONFIG_RW_UNMAP;
1938 	} else if (!strcmp(str, "write_zeroes")) {
1939 		ret = JOB_CONFIG_RW_WRITE_ZEROES;
1940 	} else if (!strcmp(str, "flush")) {
1941 		ret = JOB_CONFIG_RW_FLUSH;
1942 	} else if (!strcmp(str, "rw")) {
1943 		ret = JOB_CONFIG_RW_RW;
1944 	} else if (!strcmp(str, "randrw")) {
1945 		ret = JOB_CONFIG_RW_RANDRW;
1946 	} else {
1947 		fprintf(stderr, "rw must be one of\n"
1948 			PATTERN_TYPES_STR "\n");
1949 		ret = BDEVPERF_CONFIG_ERROR;
1950 	}
1951 
1952 	return ret;
1953 }
1954 
1955 static const char *
1956 config_filename_next(const char *filename, char *out)
1957 {
1958 	int i, k;
1959 
1960 	if (filename == NULL) {
1961 		out[0] = '\0';
1962 		return NULL;
1963 	}
1964 
1965 	if (filename[0] == ':') {
1966 		filename++;
1967 	}
1968 
1969 	for (i = 0, k = 0;
1970 	     filename[i] != '\0' &&
1971 	     filename[i] != ':' &&
1972 	     i < BDEVPERF_CONFIG_MAX_FILENAME &&
1973 	     k < (BDEVPERF_CONFIG_MAX_FILENAME - 1);
1974 	     i++) {
1975 		if (filename[i] == ' ' || filename[i] == '\t') {
1976 			continue;
1977 		}
1978 
1979 		out[k++] = filename[i];
1980 	}
1981 	out[k] = 0;
1982 
1983 	return filename + i;
1984 }
1985 
1986 static struct spdk_thread *
1987 get_lcore_thread(uint32_t lcore)
1988 {
1989 	struct lcore_thread *lthread;
1990 
1991 	TAILQ_FOREACH(lthread, &g_lcore_thread_list, link) {
1992 		if (lthread->lcore == lcore) {
1993 			return lthread->thread;
1994 		}
1995 	}
1996 
1997 	return NULL;
1998 }
1999 
2000 static void
2001 create_lcore_thread(uint32_t lcore)
2002 {
2003 	struct lcore_thread *lthread;
2004 	struct spdk_cpuset cpumask = {};
2005 	char name[32];
2006 
2007 	lthread = calloc(1, sizeof(*lthread));
2008 	assert(lthread != NULL);
2009 
2010 	lthread->lcore = lcore;
2011 
2012 	snprintf(name, sizeof(name), "lcore_%u", lcore);
2013 	spdk_cpuset_set_cpu(&cpumask, lcore, true);
2014 
2015 	lthread->thread = spdk_thread_create(name, &cpumask);
2016 	assert(lthread->thread != NULL);
2017 
2018 	TAILQ_INSERT_TAIL(&g_lcore_thread_list, lthread, link);
2019 }
2020 
2021 static void
2022 bdevperf_construct_jobs(void)
2023 {
2024 	char filename[BDEVPERF_CONFIG_MAX_FILENAME];
2025 	struct spdk_thread *thread;
2026 	struct job_config *config;
2027 	struct spdk_bdev *bdev;
2028 	const char *filenames;
2029 	uint32_t i;
2030 	int rc;
2031 
2032 	if (g_one_thread_per_lcore) {
2033 		SPDK_ENV_FOREACH_CORE(i) {
2034 			create_lcore_thread(i);
2035 		}
2036 	}
2037 
2038 	TAILQ_FOREACH(config, &job_config_list, link) {
2039 		filenames = config->filename;
2040 
2041 		if (!g_one_thread_per_lcore) {
2042 			thread = construct_job_thread(&config->cpumask, config->name);
2043 		} else {
2044 			thread = get_lcore_thread(config->lcore);
2045 		}
2046 		assert(thread);
2047 
2048 		while (filenames) {
2049 			filenames = config_filename_next(filenames, filename);
2050 			if (strlen(filename) == 0) {
2051 				break;
2052 			}
2053 
2054 			bdev = spdk_bdev_get_by_name(filename);
2055 			if (!bdev) {
2056 				fprintf(stderr, "Unable to find bdev '%s'\n", filename);
2057 				g_run_rc = -EINVAL;
2058 				return;
2059 			}
2060 
2061 			rc = bdevperf_construct_job(bdev, config, thread);
2062 			if (rc < 0) {
2063 				g_run_rc = rc;
2064 				return;
2065 			}
2066 		}
2067 	}
2068 }
2069 
2070 static int
2071 make_cli_job_config(const char *filename, int64_t offset, uint64_t range)
2072 {
2073 	struct job_config *config = calloc(1, sizeof(*config));
2074 
2075 	if (config == NULL) {
2076 		fprintf(stderr, "Unable to allocate memory for job config\n");
2077 		return -ENOMEM;
2078 	}
2079 
2080 	config->name = filename;
2081 	config->filename = filename;
2082 	config->lcore = _get_next_core();
2083 	spdk_cpuset_zero(&config->cpumask);
2084 	spdk_cpuset_set_cpu(&config->cpumask, config->lcore, true);
2085 	config->bs = g_io_size;
2086 	config->iodepth = g_queue_depth;
2087 	config->rwmixread = g_rw_percentage;
2088 	config->offset = offset;
2089 	config->length = range;
2090 	config->rw = parse_rw(g_workload_type, BDEVPERF_CONFIG_ERROR);
2091 	if ((int)config->rw == BDEVPERF_CONFIG_ERROR) {
2092 		free(config);
2093 		return -EINVAL;
2094 	}
2095 
2096 	TAILQ_INSERT_TAIL(&job_config_list, config, link);
2097 	return 0;
2098 }
2099 
2100 static int
2101 bdevperf_construct_multithread_job_config(void *ctx, struct spdk_bdev *bdev)
2102 {
2103 	uint32_t *num_cores = ctx;
2104 	uint32_t i;
2105 	uint64_t blocks_per_job;
2106 	int64_t offset;
2107 	int rc;
2108 
2109 	blocks_per_job = spdk_bdev_get_num_blocks(bdev) / *num_cores;
2110 	offset = 0;
2111 
2112 	SPDK_ENV_FOREACH_CORE(i) {
2113 		rc = make_cli_job_config(spdk_bdev_get_name(bdev), offset, blocks_per_job);
2114 		if (rc) {
2115 			return rc;
2116 		}
2117 
2118 		offset += blocks_per_job;
2119 	}
2120 
2121 	return 0;
2122 }
2123 
2124 static void
2125 bdevperf_construct_multithread_job_configs(void)
2126 {
2127 	struct spdk_bdev *bdev;
2128 	uint32_t i;
2129 	uint32_t num_cores;
2130 
2131 	num_cores = 0;
2132 	SPDK_ENV_FOREACH_CORE(i) {
2133 		num_cores++;
2134 	}
2135 
2136 	if (num_cores == 0) {
2137 		g_run_rc = -EINVAL;
2138 		return;
2139 	}
2140 
2141 	if (g_job_bdev_name != NULL) {
2142 		bdev = spdk_bdev_get_by_name(g_job_bdev_name);
2143 		if (!bdev) {
2144 			fprintf(stderr, "Unable to find bdev '%s'\n", g_job_bdev_name);
2145 			return;
2146 		}
2147 		g_run_rc = bdevperf_construct_multithread_job_config(&num_cores, bdev);
2148 	} else {
2149 		g_run_rc = spdk_for_each_bdev_leaf(&num_cores, bdevperf_construct_multithread_job_config);
2150 	}
2151 
2152 }
2153 
2154 static int
2155 bdevperf_construct_job_config(void *ctx, struct spdk_bdev *bdev)
2156 {
2157 	/* Construct the job */
2158 	return make_cli_job_config(spdk_bdev_get_name(bdev), 0, 0);
2159 }
2160 
2161 static void
2162 bdevperf_construct_job_configs(void)
2163 {
2164 	struct spdk_bdev *bdev;
2165 
2166 	/* There are three different modes for allocating jobs. Standard mode
2167 	 * (the default) creates one spdk_thread per bdev and runs the I/O job there.
2168 	 *
2169 	 * The -C flag places bdevperf into "multithread" mode, meaning it creates
2170 	 * one spdk_thread per bdev PER CORE, and runs a copy of the job on each.
2171 	 * This runs multiple threads per bdev, effectively.
2172 	 *
2173 	 * The -j flag implies "FIO" mode which tries to mimic semantic of FIO jobs.
2174 	 * In "FIO" mode, threads are spawned per-job instead of per-bdev.
2175 	 * Each FIO job can be individually parameterized by filename, cpu mask, etc,
2176 	 * which is different from other modes in that they only support global options.
2177 	 *
2178 	 * Both for standard mode and "multithread" mode, if the -E flag is specified,
2179 	 * it creates one spdk_thread PER CORE. On each core, one spdk_thread is shared by
2180 	 * multiple jobs.
2181 	 */
2182 
2183 	if (g_bdevperf_conf) {
2184 		goto end;
2185 	}
2186 
2187 	if (g_multithread_mode) {
2188 		bdevperf_construct_multithread_job_configs();
2189 	} else if (g_job_bdev_name != NULL) {
2190 		bdev = spdk_bdev_get_by_name(g_job_bdev_name);
2191 		if (bdev) {
2192 			/* Construct the job */
2193 			g_run_rc = make_cli_job_config(g_job_bdev_name, 0, 0);
2194 		} else {
2195 			fprintf(stderr, "Unable to find bdev '%s'\n", g_job_bdev_name);
2196 		}
2197 	} else {
2198 		g_run_rc = spdk_for_each_bdev_leaf(NULL, bdevperf_construct_job_config);
2199 	}
2200 
2201 end:
2202 	/* Increment initial construct_jobs count so that it will never reach 0 in the middle
2203 	 * of iteration.
2204 	 */
2205 	g_construct_job_count = 1;
2206 
2207 	if (g_run_rc == 0) {
2208 		bdevperf_construct_jobs();
2209 	}
2210 
2211 	_bdevperf_construct_job_done(NULL);
2212 }
2213 
2214 static int
2215 parse_uint_option(struct spdk_conf_section *s, const char *name, int def)
2216 {
2217 	const char *job_name;
2218 	int tmp;
2219 
2220 	tmp = spdk_conf_section_get_intval(s, name);
2221 	if (tmp == -1) {
2222 		/* Field was not found. Check default value
2223 		 * In [global] section it is ok to have undefined values
2224 		 * but for other sections it is not ok */
2225 		if (def == BDEVPERF_CONFIG_UNDEFINED) {
2226 			job_name = spdk_conf_section_get_name(s);
2227 			if (strcmp(job_name, "global") == 0) {
2228 				return def;
2229 			}
2230 
2231 			fprintf(stderr,
2232 				"Job '%s' has no '%s' assigned\n",
2233 				job_name, name);
2234 			return BDEVPERF_CONFIG_ERROR;
2235 		}
2236 		return def;
2237 	}
2238 
2239 	/* NOTE: get_intval returns nonnegative on success */
2240 	if (tmp < 0) {
2241 		fprintf(stderr, "Job '%s' has bad '%s' value.\n",
2242 			spdk_conf_section_get_name(s), name);
2243 		return BDEVPERF_CONFIG_ERROR;
2244 	}
2245 
2246 	return tmp;
2247 }
2248 
2249 /* CLI arguments override parameters for global sections */
2250 static void
2251 config_set_cli_args(struct job_config *config)
2252 {
2253 	if (g_job_bdev_name) {
2254 		config->filename = g_job_bdev_name;
2255 	}
2256 	if (g_io_size > 0) {
2257 		config->bs = g_io_size;
2258 	}
2259 	if (g_queue_depth > 0) {
2260 		config->iodepth = g_queue_depth;
2261 	}
2262 	if (g_rw_percentage > 0) {
2263 		config->rwmixread = g_rw_percentage;
2264 	}
2265 	if (g_workload_type) {
2266 		config->rw = parse_rw(g_workload_type, config->rw);
2267 	}
2268 }
2269 
2270 static int
2271 read_job_config(void)
2272 {
2273 	struct job_config global_default_config;
2274 	struct job_config global_config;
2275 	struct spdk_conf_section *s;
2276 	struct job_config *config = NULL;
2277 	const char *cpumask;
2278 	const char *rw;
2279 	bool is_global;
2280 	int n = 0;
2281 	int val;
2282 
2283 	if (g_bdevperf_conf_file == NULL) {
2284 		return 0;
2285 	}
2286 
2287 	g_bdevperf_conf = spdk_conf_allocate();
2288 	if (g_bdevperf_conf == NULL) {
2289 		fprintf(stderr, "Could not allocate job config structure\n");
2290 		return 1;
2291 	}
2292 
2293 	spdk_conf_disable_sections_merge(g_bdevperf_conf);
2294 	if (spdk_conf_read(g_bdevperf_conf, g_bdevperf_conf_file)) {
2295 		fprintf(stderr, "Invalid job config");
2296 		return 1;
2297 	}
2298 
2299 	/* Initialize global defaults */
2300 	global_default_config.filename = NULL;
2301 	/* Zero mask is the same as g_all_cpuset
2302 	 * The g_all_cpuset is not initialized yet,
2303 	 * so use zero mask as the default instead */
2304 	spdk_cpuset_zero(&global_default_config.cpumask);
2305 	global_default_config.bs = BDEVPERF_CONFIG_UNDEFINED;
2306 	global_default_config.iodepth = BDEVPERF_CONFIG_UNDEFINED;
2307 	/* bdevperf has no default for -M option but in FIO the default is 50 */
2308 	global_default_config.rwmixread = 50;
2309 	global_default_config.offset = 0;
2310 	/* length 0 means 100% */
2311 	global_default_config.length = 0;
2312 	global_default_config.rw = BDEVPERF_CONFIG_UNDEFINED;
2313 	config_set_cli_args(&global_default_config);
2314 
2315 	if ((int)global_default_config.rw == BDEVPERF_CONFIG_ERROR) {
2316 		return 1;
2317 	}
2318 
2319 	/* There is only a single instance of global job_config
2320 	 * We just reset its value when we encounter new [global] section */
2321 	global_config = global_default_config;
2322 
2323 	for (s = spdk_conf_first_section(g_bdevperf_conf);
2324 	     s != NULL;
2325 	     s = spdk_conf_next_section(s)) {
2326 		config = calloc(1, sizeof(*config));
2327 		if (config == NULL) {
2328 			fprintf(stderr, "Unable to allocate memory for job config\n");
2329 			return 1;
2330 		}
2331 
2332 		config->name = spdk_conf_section_get_name(s);
2333 		is_global = strcmp(config->name, "global") == 0;
2334 
2335 		if (is_global) {
2336 			global_config = global_default_config;
2337 		}
2338 
2339 		config->filename = spdk_conf_section_get_val(s, "filename");
2340 		if (config->filename == NULL) {
2341 			config->filename = global_config.filename;
2342 		}
2343 		if (!is_global) {
2344 			if (config->filename == NULL) {
2345 				fprintf(stderr, "Job '%s' expects 'filename' parameter\n", config->name);
2346 				goto error;
2347 			} else if (strnlen(config->filename, BDEVPERF_CONFIG_MAX_FILENAME)
2348 				   >= BDEVPERF_CONFIG_MAX_FILENAME) {
2349 				fprintf(stderr,
2350 					"filename for '%s' job is too long. Max length is %d\n",
2351 					config->name, BDEVPERF_CONFIG_MAX_FILENAME);
2352 				goto error;
2353 			}
2354 		}
2355 
2356 		cpumask = spdk_conf_section_get_val(s, "cpumask");
2357 		if (cpumask == NULL) {
2358 			config->cpumask = global_config.cpumask;
2359 		} else if (spdk_cpuset_parse(&config->cpumask, cpumask)) {
2360 			fprintf(stderr, "Job '%s' has bad 'cpumask' value\n", config->name);
2361 			goto error;
2362 		}
2363 
2364 		config->bs = parse_uint_option(s, "bs", global_config.bs);
2365 		if (config->bs == BDEVPERF_CONFIG_ERROR) {
2366 			goto error;
2367 		} else if (config->bs == 0) {
2368 			fprintf(stderr, "'bs' of job '%s' must be greater than 0\n", config->name);
2369 			goto error;
2370 		}
2371 
2372 		config->iodepth = parse_uint_option(s, "iodepth", global_config.iodepth);
2373 		if (config->iodepth == BDEVPERF_CONFIG_ERROR) {
2374 			goto error;
2375 		} else if (config->iodepth == 0) {
2376 			fprintf(stderr,
2377 				"'iodepth' of job '%s' must be greater than 0\n",
2378 				config->name);
2379 			goto error;
2380 		}
2381 
2382 		config->rwmixread = parse_uint_option(s, "rwmixread", global_config.rwmixread);
2383 		if (config->rwmixread == BDEVPERF_CONFIG_ERROR) {
2384 			goto error;
2385 		} else if (config->rwmixread > 100) {
2386 			fprintf(stderr,
2387 				"'rwmixread' value of '%s' job is not in 0-100 range\n",
2388 				config->name);
2389 			goto error;
2390 		}
2391 
2392 		config->offset = parse_uint_option(s, "offset", global_config.offset);
2393 		if (config->offset == BDEVPERF_CONFIG_ERROR) {
2394 			goto error;
2395 		}
2396 
2397 		val = parse_uint_option(s, "length", global_config.length);
2398 		if (val == BDEVPERF_CONFIG_ERROR) {
2399 			goto error;
2400 		}
2401 		config->length = val;
2402 
2403 		rw = spdk_conf_section_get_val(s, "rw");
2404 		config->rw = parse_rw(rw, global_config.rw);
2405 		if ((int)config->rw == BDEVPERF_CONFIG_ERROR) {
2406 			fprintf(stderr, "Job '%s' has bad 'rw' value\n", config->name);
2407 			goto error;
2408 		} else if (!is_global && (int)config->rw == BDEVPERF_CONFIG_UNDEFINED) {
2409 			fprintf(stderr, "Job '%s' has no 'rw' assigned\n", config->name);
2410 			goto error;
2411 		}
2412 
2413 		if (is_global) {
2414 			config_set_cli_args(config);
2415 			global_config = *config;
2416 			free(config);
2417 			config = NULL;
2418 		} else {
2419 			TAILQ_INSERT_TAIL(&job_config_list, config, link);
2420 			n++;
2421 		}
2422 	}
2423 
2424 	if (g_rpc_log_file_name != NULL) {
2425 		g_rpc_log_file = fopen(g_rpc_log_file_name, "a");
2426 		if (g_rpc_log_file == NULL) {
2427 			fprintf(stderr, "Failed to open %s\n", g_rpc_log_file_name);
2428 			goto error;
2429 		}
2430 	}
2431 
2432 	printf("Using job config with %d jobs\n", n);
2433 	return 0;
2434 error:
2435 	free(config);
2436 	return 1;
2437 }
2438 
2439 static void
2440 bdevperf_run(void *arg1)
2441 {
2442 	uint32_t i;
2443 
2444 	g_main_thread = spdk_get_thread();
2445 
2446 	spdk_cpuset_zero(&g_all_cpuset);
2447 	SPDK_ENV_FOREACH_CORE(i) {
2448 		spdk_cpuset_set_cpu(&g_all_cpuset, i, true);
2449 	}
2450 
2451 	if (g_wait_for_tests) {
2452 		/* Do not perform any tests until RPC is received */
2453 		return;
2454 	}
2455 
2456 	bdevperf_construct_job_configs();
2457 }
2458 
2459 static void
2460 rpc_perform_tests_reset(void)
2461 {
2462 	/* Reset g_run_rc to 0 for the next test run. */
2463 	g_run_rc = 0;
2464 
2465 	/* Reset g_stats to 0 for the next test run. */
2466 	memset(&g_stats, 0, sizeof(g_stats));
2467 
2468 	/* Reset g_show_performance_period_num to 0 for the next test run. */
2469 	g_show_performance_period_num = 0;
2470 }
2471 
2472 static void
2473 rpc_perform_tests_cb(void)
2474 {
2475 	struct spdk_json_write_ctx *w;
2476 	struct spdk_jsonrpc_request *request = g_request;
2477 
2478 	g_request = NULL;
2479 
2480 	if (g_run_rc == 0) {
2481 		w = spdk_jsonrpc_begin_result(request);
2482 		spdk_json_write_uint32(w, g_run_rc);
2483 		spdk_jsonrpc_end_result(request, w);
2484 	} else {
2485 		spdk_jsonrpc_send_error_response_fmt(request, SPDK_JSONRPC_ERROR_INTERNAL_ERROR,
2486 						     "bdevperf failed with error %s", spdk_strerror(-g_run_rc));
2487 	}
2488 
2489 	rpc_perform_tests_reset();
2490 }
2491 
2492 struct rpc_bdevperf_params {
2493 	int	time_in_sec;
2494 	char	*workload_type;
2495 	int	queue_depth;
2496 	char	*io_size;
2497 	int	rw_percentage;
2498 };
2499 
2500 static const struct spdk_json_object_decoder rpc_bdevperf_params_decoders[] = {
2501 	{"time_in_sec", offsetof(struct rpc_bdevperf_params, time_in_sec), spdk_json_decode_int32, true},
2502 	{"workload_type", offsetof(struct rpc_bdevperf_params, workload_type), spdk_json_decode_string, true},
2503 	{"queue_depth", offsetof(struct rpc_bdevperf_params, queue_depth), spdk_json_decode_int32, true},
2504 	{"io_size", offsetof(struct rpc_bdevperf_params, io_size), spdk_json_decode_string, true},
2505 	{"rw_percentage", offsetof(struct rpc_bdevperf_params, rw_percentage), spdk_json_decode_int32, true},
2506 };
2507 
2508 static void
2509 rpc_apply_bdevperf_params(struct rpc_bdevperf_params *params)
2510 {
2511 	if (params->workload_type) {
2512 		/* we need to clear previously settled parameter to avoid memory leak */
2513 		free(g_workload_type);
2514 		g_workload_type = strdup(params->workload_type);
2515 	}
2516 	if (params->queue_depth) {
2517 		g_queue_depth = params->queue_depth;
2518 	}
2519 	if (params->io_size) {
2520 		bdevperf_parse_arg('o', params->io_size);
2521 	}
2522 	if (params->time_in_sec) {
2523 		g_time_in_sec = params->time_in_sec;
2524 	}
2525 	if (params->rw_percentage) {
2526 		g_rw_percentage = params->rw_percentage;
2527 		g_mix_specified = true;
2528 	} else {
2529 		g_mix_specified = false;
2530 	}
2531 }
2532 
2533 static void
2534 rpc_perform_tests(struct spdk_jsonrpc_request *request, const struct spdk_json_val *params)
2535 {
2536 	struct rpc_bdevperf_params req = {}, backup = {};
2537 	int rc;
2538 
2539 	if (g_request != NULL) {
2540 		fprintf(stderr, "Another test is already in progress.\n");
2541 		spdk_jsonrpc_send_error_response(request, SPDK_JSONRPC_ERROR_INTERNAL_ERROR,
2542 						 spdk_strerror(-EINPROGRESS));
2543 		return;
2544 	}
2545 
2546 	if (params) {
2547 		if (spdk_json_decode_object_relaxed(params, rpc_bdevperf_params_decoders,
2548 						    SPDK_COUNTOF(rpc_bdevperf_params_decoders),
2549 						    &req)) {
2550 			spdk_jsonrpc_send_error_response(request, SPDK_JSONRPC_ERROR_PARSE_ERROR,
2551 							 "spdk_json_decode_object failed");
2552 			return;
2553 		}
2554 
2555 		if (g_workload_type) {
2556 			backup.workload_type = strdup(g_workload_type);
2557 		}
2558 		backup.queue_depth = g_queue_depth;
2559 		if (asprintf(&backup.io_size, "%d", g_io_size) < 0) {
2560 			fprintf(stderr, "Couldn't allocate memory for queue depth");
2561 			goto rpc_error;
2562 		}
2563 		backup.time_in_sec = g_time_in_sec;
2564 		backup.rw_percentage = g_rw_percentage;
2565 
2566 		rpc_apply_bdevperf_params(&req);
2567 
2568 		free(req.workload_type);
2569 		free(req.io_size);
2570 	}
2571 
2572 	rc = verify_test_params();
2573 
2574 	if (rc) {
2575 		spdk_jsonrpc_send_error_response(request, SPDK_JSONRPC_ERROR_PARSE_ERROR,
2576 						 "Invalid parameters provided");
2577 		/* restore old params on error */
2578 		rpc_apply_bdevperf_params(&backup);
2579 		goto rpc_error;
2580 	}
2581 
2582 	g_request = request;
2583 
2584 	/* Only construct job configs at the first test run.  */
2585 	if (TAILQ_EMPTY(&job_config_list)) {
2586 		bdevperf_construct_job_configs();
2587 	} else {
2588 		bdevperf_construct_jobs();
2589 	}
2590 
2591 rpc_error:
2592 	free(backup.io_size);
2593 	free(backup.workload_type);
2594 }
2595 SPDK_RPC_REGISTER("perform_tests", rpc_perform_tests, SPDK_RPC_RUNTIME)
2596 
2597 static void
2598 _bdevperf_job_drain(void *ctx)
2599 {
2600 	bdevperf_job_drain(ctx);
2601 }
2602 
2603 static void
2604 spdk_bdevperf_shutdown_cb(void)
2605 {
2606 	g_shutdown = true;
2607 	struct bdevperf_job *job, *tmp;
2608 
2609 	if (g_bdevperf.running_jobs == 0) {
2610 		bdevperf_test_done(NULL);
2611 		return;
2612 	}
2613 
2614 	/* Iterate jobs to stop all I/O */
2615 	TAILQ_FOREACH_SAFE(job, &g_bdevperf.jobs, link, tmp) {
2616 		spdk_thread_send_msg(job->thread, _bdevperf_job_drain, job);
2617 	}
2618 }
2619 
2620 static int
2621 bdevperf_parse_arg(int ch, char *arg)
2622 {
2623 	long long tmp;
2624 
2625 	if (ch == 'w') {
2626 		g_workload_type = strdup(arg);
2627 	} else if (ch == 'T') {
2628 		g_job_bdev_name = arg;
2629 	} else if (ch == 'z') {
2630 		g_wait_for_tests = true;
2631 	} else if (ch == 'Z') {
2632 		g_zcopy = true;
2633 	} else if (ch == 'X') {
2634 		g_abort = true;
2635 	} else if (ch == 'C') {
2636 		g_multithread_mode = true;
2637 	} else if (ch == 'f') {
2638 		g_continue_on_failure = true;
2639 	} else if (ch == 'j') {
2640 		g_bdevperf_conf_file = arg;
2641 	} else if (ch == 'F') {
2642 		char *endptr;
2643 
2644 		errno = 0;
2645 		g_zipf_theta = strtod(arg, &endptr);
2646 		if (errno || arg == endptr || g_zipf_theta < 0) {
2647 			fprintf(stderr, "Illegal zipf theta value %s\n", arg);
2648 			return -EINVAL;
2649 		}
2650 	} else if (ch == 'l') {
2651 		g_latency_display_level++;
2652 	} else if (ch == 'D') {
2653 		g_random_map = true;
2654 	} else if (ch == 'E') {
2655 		g_one_thread_per_lcore = true;
2656 	} else if (ch == 'J') {
2657 		g_rpc_log_file_name = arg;
2658 	} else if (ch == 'o') {
2659 		uint64_t size;
2660 
2661 		if (spdk_parse_capacity(arg, &size, NULL) != 0) {
2662 			fprintf(stderr, "Invalid IO size: %s\n", arg);
2663 			return -EINVAL;
2664 		}
2665 		g_io_size = (int)size;
2666 	} else if (ch == 'U') {
2667 		g_unique_writes = true;
2668 	} else {
2669 		tmp = spdk_strtoll(arg, 10);
2670 		if (tmp < 0) {
2671 			fprintf(stderr, "Parse failed for the option %c.\n", ch);
2672 			return tmp;
2673 		} else if (tmp >= INT_MAX) {
2674 			fprintf(stderr, "Parsed option was too large %c.\n", ch);
2675 			return -ERANGE;
2676 		}
2677 
2678 		switch (ch) {
2679 		case 'q':
2680 			g_queue_depth = tmp;
2681 			break;
2682 		case 't':
2683 			g_time_in_sec = tmp;
2684 			break;
2685 		case 'k':
2686 			g_timeout_in_sec = tmp;
2687 			break;
2688 		case 'M':
2689 			g_rw_percentage = tmp;
2690 			g_mix_specified = true;
2691 			break;
2692 		case 'P':
2693 			g_show_performance_ema_period = tmp;
2694 			break;
2695 		case 'S':
2696 			g_show_performance_real_time = 1;
2697 			g_show_performance_period_in_usec = tmp * SPDK_SEC_TO_USEC;
2698 			break;
2699 		default:
2700 			return -EINVAL;
2701 		}
2702 	}
2703 	return 0;
2704 }
2705 
2706 static void
2707 bdevperf_usage(void)
2708 {
2709 	printf(" -q <depth>                io depth\n");
2710 	printf(" -o <size>                 io size in bytes\n");
2711 	printf(" -w <type>                 io pattern type, must be one of " PATTERN_TYPES_STR "\n");
2712 	printf(" -t <time>                 time in seconds\n");
2713 	printf(" -k <timeout>              timeout in seconds to detect starved I/O (default is 0 and disabled)\n");
2714 	printf(" -M <percent>              rwmixread (100 for reads, 0 for writes)\n");
2715 	printf(" -P <num>                  number of moving average period\n");
2716 	printf("\t\t(If set to n, show weighted mean of the previous n IO/s in real time)\n");
2717 	printf("\t\t(Formula: M = 2 / (n + 1), EMA[i+1] = IO/s * M + (1 - M) * EMA[i])\n");
2718 	printf("\t\t(only valid with -S)\n");
2719 	printf(" -S <period>               show performance result in real time every <period> seconds\n");
2720 	printf(" -T <bdev>                 bdev to run against. Default: all available bdevs.\n");
2721 	printf(" -f                        continue processing I/O even after failures\n");
2722 	printf(" -F <zipf theta>           use zipf distribution for random I/O\n");
2723 	printf(" -Z                        enable using zcopy bdev API for read or write I/O\n");
2724 	printf(" -z                        start bdevperf, but wait for perform_tests RPC to start tests\n");
2725 	printf("                           (See examples/bdev/bdevperf/bdevperf.py)\n");
2726 	printf(" -X                        abort timed out I/O\n");
2727 	printf(" -C                        enable every core to send I/Os to each bdev\n");
2728 	printf(" -j <filename>             use job config file\n");
2729 	printf(" -l                        display latency histogram, default: disable. -l display summary, -ll display details\n");
2730 	printf(" -D                        use a random map for picking offsets not previously read or written (for all jobs)\n");
2731 	printf(" -E                        share per lcore thread among jobs. Available only if -j is not used.\n");
2732 	printf(" -J                        File name to open with append mode and log JSON RPC calls.\n");
2733 	printf(" -U                        generate unique data for each write I/O, has no effect on non-write I/O\n");
2734 }
2735 
2736 static void
2737 bdevperf_fini(void)
2738 {
2739 	free_job_config();
2740 	free(g_workload_type);
2741 
2742 	if (g_rpc_log_file != NULL) {
2743 		fclose(g_rpc_log_file);
2744 		g_rpc_log_file = NULL;
2745 	}
2746 }
2747 
2748 static int
2749 verify_test_params(void)
2750 {
2751 	if (!g_bdevperf_conf_file && g_queue_depth <= 0) {
2752 		goto out;
2753 	}
2754 	if (!g_bdevperf_conf_file && g_io_size <= 0) {
2755 		goto out;
2756 	}
2757 	if (!g_bdevperf_conf_file && !g_workload_type) {
2758 		goto out;
2759 	}
2760 	if (g_bdevperf_conf_file && g_one_thread_per_lcore) {
2761 		printf("If bdevperf's config file is used, per lcore thread cannot be used\n");
2762 		goto out;
2763 	}
2764 	if (g_time_in_sec <= 0) {
2765 		goto out;
2766 	}
2767 	g_time_in_usec = g_time_in_sec * SPDK_SEC_TO_USEC;
2768 
2769 	if (g_timeout_in_sec < 0) {
2770 		goto out;
2771 	}
2772 
2773 	if (g_abort && !g_timeout_in_sec) {
2774 		printf("Timeout must be set for abort option, Ignoring g_abort\n");
2775 	}
2776 
2777 	if (g_show_performance_ema_period > 0 &&
2778 	    g_show_performance_real_time == 0) {
2779 		fprintf(stderr, "-P option must be specified with -S option\n");
2780 		return 1;
2781 	}
2782 
2783 	if (g_io_size > SPDK_BDEV_LARGE_BUF_MAX_SIZE) {
2784 		printf("I/O size of %d is greater than zero copy threshold (%d).\n",
2785 		       g_io_size, SPDK_BDEV_LARGE_BUF_MAX_SIZE);
2786 		printf("Zero copy mechanism will not be used.\n");
2787 		g_zcopy = false;
2788 	}
2789 
2790 	if (g_bdevperf_conf_file) {
2791 		/* workload_type verification happens during config file parsing */
2792 		return 0;
2793 	}
2794 
2795 	if (!strcmp(g_workload_type, "verify") ||
2796 	    !strcmp(g_workload_type, "reset")) {
2797 		g_rw_percentage = 50;
2798 		g_verify = true;
2799 		if (!strcmp(g_workload_type, "reset")) {
2800 			g_reset = true;
2801 		}
2802 	}
2803 
2804 	if (!strcmp(g_workload_type, "read") ||
2805 	    !strcmp(g_workload_type, "randread") ||
2806 	    !strcmp(g_workload_type, "write") ||
2807 	    !strcmp(g_workload_type, "randwrite") ||
2808 	    !strcmp(g_workload_type, "verify") ||
2809 	    !strcmp(g_workload_type, "reset") ||
2810 	    !strcmp(g_workload_type, "unmap") ||
2811 	    !strcmp(g_workload_type, "write_zeroes") ||
2812 	    !strcmp(g_workload_type, "flush")) {
2813 		if (g_mix_specified) {
2814 			fprintf(stderr, "Ignoring -M option... Please use -M option"
2815 				" only when using rw or randrw.\n");
2816 		}
2817 	}
2818 
2819 	if (!strcmp(g_workload_type, "rw") ||
2820 	    !strcmp(g_workload_type, "randrw")) {
2821 		if (g_rw_percentage < 0 || g_rw_percentage > 100) {
2822 			fprintf(stderr,
2823 				"-M must be specified to value from 0 to 100 "
2824 				"for rw or randrw.\n");
2825 			return 1;
2826 		}
2827 	}
2828 
2829 	if (strcmp(g_workload_type, "randread") &&
2830 	    strcmp(g_workload_type, "randwrite") &&
2831 	    strcmp(g_workload_type, "randrw")) {
2832 		if (g_random_map) {
2833 			fprintf(stderr, "Ignoring -D option... Please use -D option"
2834 				" only when using randread, randwrite or randrw.\n");
2835 			return 1;
2836 		}
2837 	}
2838 
2839 	return 0;
2840 out:
2841 	return 1;
2842 }
2843 
2844 int
2845 main(int argc, char **argv)
2846 {
2847 	struct spdk_app_opts opts = {};
2848 	int rc;
2849 
2850 	/* Use the runtime PID to set the random seed */
2851 	srand(getpid());
2852 
2853 	spdk_app_opts_init(&opts, sizeof(opts));
2854 	opts.name = "bdevperf";
2855 	opts.rpc_addr = NULL;
2856 	opts.shutdown_cb = spdk_bdevperf_shutdown_cb;
2857 
2858 	if ((rc = spdk_app_parse_args(argc, argv, &opts, "Zzfq:o:t:w:k:CEF:J:M:P:S:T:Xlj:DU", NULL,
2859 				      bdevperf_parse_arg, bdevperf_usage)) !=
2860 	    SPDK_APP_PARSE_ARGS_SUCCESS) {
2861 		return rc;
2862 	}
2863 
2864 	/* Set the default address if no rpc_addr was provided in args
2865 	 * and RPC is used for starting tests */
2866 	if (g_wait_for_tests && opts.rpc_addr == NULL) {
2867 		opts.rpc_addr = SPDK_DEFAULT_RPC_ADDR;
2868 	}
2869 
2870 	if (read_job_config()) {
2871 		bdevperf_fini();
2872 		return 1;
2873 	}
2874 
2875 	if (g_rpc_log_file != NULL) {
2876 		opts.rpc_log_file = g_rpc_log_file;
2877 	}
2878 
2879 	if (verify_test_params() != 0 && !g_wait_for_tests) {
2880 		spdk_app_usage();
2881 		bdevperf_usage();
2882 		bdevperf_fini();
2883 		exit(1);
2884 	}
2885 
2886 	rc = spdk_app_start(&opts, bdevperf_run, NULL);
2887 
2888 	spdk_app_fini();
2889 	bdevperf_fini();
2890 	return rc;
2891 }
2892