filesetup: make trim jobs respect --readonly during file open
[fio.git] / init.c
1 /*
2  * This file contains job initialization and setup functions.
3  */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <ctype.h>
8 #include <string.h>
9 #include <errno.h>
10 #include <sys/ipc.h>
11 #include <sys/types.h>
12 #include <dlfcn.h>
13 #ifdef CONFIG_VALGRIND_DEV
14 #include <valgrind/drd.h>
15 #else
16 #define DRD_IGNORE_VAR(x) do { } while (0)
17 #endif
18
19 #include "fio.h"
20 #ifndef FIO_NO_HAVE_SHM_H
21 #include <sys/shm.h>
22 #endif
23
24 #include "parse.h"
25 #include "smalloc.h"
26 #include "filehash.h"
27 #include "verify.h"
28 #include "profile.h"
29 #include "server.h"
30 #include "idletime.h"
31 #include "filelock.h"
32 #include "steadystate.h"
33
34 #include "oslib/getopt.h"
35 #include "oslib/strcasestr.h"
36
37 #include "crc/test.h"
38 #include "lib/pow2.h"
39 #include "lib/memcpy.h"
40
41 const char fio_version_string[] = FIO_VERSION;
42
43 #define FIO_RANDSEED            (0xb1899bedUL)
44
45 static char **ini_file;
46 static int max_jobs = FIO_MAX_JOBS;
47 static int dump_cmdline;
48 static int parse_only;
49
50 static struct thread_data def_thread;
51 struct thread_data *threads = NULL;
52 static char **job_sections;
53 static int nr_job_sections;
54
55 int exitall_on_terminate = 0;
56 int output_format = FIO_OUTPUT_NORMAL;
57 int eta_print = FIO_ETA_AUTO;
58 unsigned int eta_interval_msec = 1000;
59 int eta_new_line = 0;
60 FILE *f_out = NULL;
61 FILE *f_err = NULL;
62 char *exec_profile = NULL;
63 int warnings_fatal = 0;
64 int terse_version = 3;
65 int is_backend = 0;
66 int nr_clients = 0;
67 int log_syslog = 0;
68
69 int write_bw_log = 0;
70 int read_only = 0;
71 int status_interval = 0;
72
73 char *trigger_file = NULL;
74 long long trigger_timeout = 0;
75 char *trigger_cmd = NULL;
76 char *trigger_remote_cmd = NULL;
77
78 char *aux_path = NULL;
79
80 static int prev_group_jobs;
81
82 unsigned long fio_debug = 0;
83 unsigned int fio_debug_jobno = -1;
84 unsigned int *fio_debug_jobp = NULL;
85 unsigned int *fio_warned = NULL;
86
87 static char cmd_optstr[256];
88 static bool did_arg;
89
90 #define FIO_CLIENT_FLAG         (1 << 16)
91
92 /*
93  * Command line options. These will contain the above, plus a few
94  * extra that only pertain to fio itself and not jobs.
95  */
96 static struct option l_opts[FIO_NR_OPTIONS] = {
97         {
98                 .name           = (char *) "output",
99                 .has_arg        = required_argument,
100                 .val            = 'o' | FIO_CLIENT_FLAG,
101         },
102         {
103                 .name           = (char *) "latency-log",
104                 .has_arg        = required_argument,
105                 .val            = 'l' | FIO_CLIENT_FLAG,
106         },
107         {
108                 .name           = (char *) "bandwidth-log",
109                 .has_arg        = no_argument,
110                 .val            = 'b' | FIO_CLIENT_FLAG,
111         },
112         {
113                 .name           = (char *) "minimal",
114                 .has_arg        = no_argument,
115                 .val            = 'm' | FIO_CLIENT_FLAG,
116         },
117         {
118                 .name           = (char *) "output-format",
119                 .has_arg        = required_argument,
120                 .val            = 'F' | FIO_CLIENT_FLAG,
121         },
122         {
123                 .name           = (char *) "append-terse",
124                 .has_arg        = optional_argument,
125                 .val            = 'f',
126         },
127         {
128                 .name           = (char *) "version",
129                 .has_arg        = no_argument,
130                 .val            = 'v' | FIO_CLIENT_FLAG,
131         },
132         {
133                 .name           = (char *) "help",
134                 .has_arg        = no_argument,
135                 .val            = 'h' | FIO_CLIENT_FLAG,
136         },
137         {
138                 .name           = (char *) "cmdhelp",
139                 .has_arg        = optional_argument,
140                 .val            = 'c' | FIO_CLIENT_FLAG,
141         },
142         {
143                 .name           = (char *) "enghelp",
144                 .has_arg        = optional_argument,
145                 .val            = 'i' | FIO_CLIENT_FLAG,
146         },
147         {
148                 .name           = (char *) "showcmd",
149                 .has_arg        = no_argument,
150                 .val            = 's' | FIO_CLIENT_FLAG,
151         },
152         {
153                 .name           = (char *) "readonly",
154                 .has_arg        = no_argument,
155                 .val            = 'r' | FIO_CLIENT_FLAG,
156         },
157         {
158                 .name           = (char *) "eta",
159                 .has_arg        = required_argument,
160                 .val            = 'e' | FIO_CLIENT_FLAG,
161         },
162         {
163                 .name           = (char *) "eta-interval",
164                 .has_arg        = required_argument,
165                 .val            = 'O' | FIO_CLIENT_FLAG,
166         },
167         {
168                 .name           = (char *) "eta-newline",
169                 .has_arg        = required_argument,
170                 .val            = 'E' | FIO_CLIENT_FLAG,
171         },
172         {
173                 .name           = (char *) "debug",
174                 .has_arg        = required_argument,
175                 .val            = 'd' | FIO_CLIENT_FLAG,
176         },
177         {
178                 .name           = (char *) "parse-only",
179                 .has_arg        = no_argument,
180                 .val            = 'P' | FIO_CLIENT_FLAG,
181         },
182         {
183                 .name           = (char *) "section",
184                 .has_arg        = required_argument,
185                 .val            = 'x' | FIO_CLIENT_FLAG,
186         },
187 #ifdef CONFIG_ZLIB
188         {
189                 .name           = (char *) "inflate-log",
190                 .has_arg        = required_argument,
191                 .val            = 'X' | FIO_CLIENT_FLAG,
192         },
193 #endif
194         {
195                 .name           = (char *) "alloc-size",
196                 .has_arg        = required_argument,
197                 .val            = 'a' | FIO_CLIENT_FLAG,
198         },
199         {
200                 .name           = (char *) "profile",
201                 .has_arg        = required_argument,
202                 .val            = 'p' | FIO_CLIENT_FLAG,
203         },
204         {
205                 .name           = (char *) "warnings-fatal",
206                 .has_arg        = no_argument,
207                 .val            = 'w' | FIO_CLIENT_FLAG,
208         },
209         {
210                 .name           = (char *) "max-jobs",
211                 .has_arg        = required_argument,
212                 .val            = 'j' | FIO_CLIENT_FLAG,
213         },
214         {
215                 .name           = (char *) "terse-version",
216                 .has_arg        = required_argument,
217                 .val            = 'V' | FIO_CLIENT_FLAG,
218         },
219         {
220                 .name           = (char *) "server",
221                 .has_arg        = optional_argument,
222                 .val            = 'S',
223         },
224         {       .name           = (char *) "daemonize",
225                 .has_arg        = required_argument,
226                 .val            = 'D',
227         },
228         {
229                 .name           = (char *) "client",
230                 .has_arg        = required_argument,
231                 .val            = 'C',
232         },
233         {
234                 .name           = (char *) "remote-config",
235                 .has_arg        = required_argument,
236                 .val            = 'R',
237         },
238         {
239                 .name           = (char *) "cpuclock-test",
240                 .has_arg        = no_argument,
241                 .val            = 'T',
242         },
243         {
244                 .name           = (char *) "crctest",
245                 .has_arg        = optional_argument,
246                 .val            = 'G',
247         },
248         {
249                 .name           = (char *) "memcpytest",
250                 .has_arg        = optional_argument,
251                 .val            = 'M',
252         },
253         {
254                 .name           = (char *) "idle-prof",
255                 .has_arg        = required_argument,
256                 .val            = 'I',
257         },
258         {
259                 .name           = (char *) "status-interval",
260                 .has_arg        = required_argument,
261                 .val            = 'L',
262         },
263         {
264                 .name           = (char *) "trigger-file",
265                 .has_arg        = required_argument,
266                 .val            = 'W',
267         },
268         {
269                 .name           = (char *) "trigger-timeout",
270                 .has_arg        = required_argument,
271                 .val            = 'B',
272         },
273         {
274                 .name           = (char *) "trigger",
275                 .has_arg        = required_argument,
276                 .val            = 'H',
277         },
278         {
279                 .name           = (char *) "trigger-remote",
280                 .has_arg        = required_argument,
281                 .val            = 'J',
282         },
283         {
284                 .name           = (char *) "aux-path",
285                 .has_arg        = required_argument,
286                 .val            = 'K',
287         },
288         {
289                 .name           = NULL,
290         },
291 };
292
293 void free_threads_shm(void)
294 {
295         if (threads) {
296                 void *tp = threads;
297 #ifndef CONFIG_NO_SHM
298                 struct shmid_ds sbuf;
299
300                 threads = NULL;
301                 shmdt(tp);
302                 shmctl(shm_id, IPC_RMID, &sbuf);
303                 shm_id = -1;
304 #else
305                 threads = NULL;
306                 free(tp);
307 #endif
308         }
309 }
310
311 static void free_shm(void)
312 {
313         if (threads) {
314                 flow_exit();
315                 fio_debug_jobp = NULL;
316                 fio_warned = NULL;
317                 free_threads_shm();
318         }
319
320         free(trigger_file);
321         free(trigger_cmd);
322         free(trigger_remote_cmd);
323         trigger_file = trigger_cmd = trigger_remote_cmd = NULL;
324
325         options_free(fio_options, &def_thread.o);
326         fio_filelock_exit();
327         file_hash_exit();
328         scleanup();
329 }
330
331 /*
332  * The thread area is shared between the main process and the job
333  * threads/processes. So setup a shared memory segment that will hold
334  * all the job info. We use the end of the region for keeping track of
335  * open files across jobs, for file sharing.
336  */
337 static int setup_thread_area(void)
338 {
339         int i;
340
341         if (threads)
342                 return 0;
343
344         /*
345          * 1024 is too much on some machines, scale max_jobs if
346          * we get a failure that looks like too large a shm segment
347          */
348         do {
349                 size_t size = max_jobs * sizeof(struct thread_data);
350
351                 size += 2 * sizeof(unsigned int);
352
353 #ifndef CONFIG_NO_SHM
354                 shm_id = shmget(0, size, IPC_CREAT | 0600);
355                 if (shm_id != -1)
356                         break;
357                 if (errno != EINVAL && errno != ENOMEM && errno != ENOSPC) {
358                         perror("shmget");
359                         break;
360                 }
361 #else
362                 threads = malloc(size);
363                 if (threads)
364                         break;
365 #endif
366
367                 max_jobs >>= 1;
368         } while (max_jobs);
369
370 #ifndef CONFIG_NO_SHM
371         if (shm_id == -1)
372                 return 1;
373
374         threads = shmat(shm_id, NULL, 0);
375         if (threads == (void *) -1) {
376                 perror("shmat");
377                 return 1;
378         }
379         if (shm_attach_to_open_removed())
380                 shmctl(shm_id, IPC_RMID, NULL);
381 #endif
382
383         memset(threads, 0, max_jobs * sizeof(struct thread_data));
384         for (i = 0; i < max_jobs; i++)
385                 DRD_IGNORE_VAR(threads[i]);
386         fio_debug_jobp = (unsigned int *)(threads + max_jobs);
387         *fio_debug_jobp = -1;
388         fio_warned = fio_debug_jobp + 1;
389         *fio_warned = 0;
390
391         flow_init();
392
393         return 0;
394 }
395
396 static void dump_print_option(struct print_option *p)
397 {
398         const char *delim;
399
400         if (!strcmp("description", p->name))
401                 delim = "\"";
402         else
403                 delim = "";
404
405         log_info("--%s%s", p->name, p->value ? "" : " ");
406         if (p->value)
407                 log_info("=%s%s%s ", delim, p->value, delim);
408 }
409
410 static void dump_opt_list(struct thread_data *td)
411 {
412         struct flist_head *entry;
413         struct print_option *p;
414
415         if (flist_empty(&td->opt_list))
416                 return;
417
418         flist_for_each(entry, &td->opt_list) {
419                 p = flist_entry(entry, struct print_option, list);
420                 dump_print_option(p);
421         }
422 }
423
424 static void fio_dump_options_free(struct thread_data *td)
425 {
426         while (!flist_empty(&td->opt_list)) {
427                 struct print_option *p;
428
429                 p = flist_first_entry(&td->opt_list, struct print_option, list);
430                 flist_del_init(&p->list);
431                 free(p->name);
432                 free(p->value);
433                 free(p);
434         }
435 }
436
437 static void copy_opt_list(struct thread_data *dst, struct thread_data *src)
438 {
439         struct flist_head *entry;
440
441         if (flist_empty(&src->opt_list))
442                 return;
443
444         flist_for_each(entry, &src->opt_list) {
445                 struct print_option *srcp, *dstp;
446
447                 srcp = flist_entry(entry, struct print_option, list);
448                 dstp = malloc(sizeof(*dstp));
449                 dstp->name = strdup(srcp->name);
450                 if (srcp->value)
451                         dstp->value = strdup(srcp->value);
452                 else
453                         dstp->value = NULL;
454                 flist_add_tail(&dstp->list, &dst->opt_list);
455         }
456 }
457
458 /*
459  * Return a free job structure.
460  */
461 static struct thread_data *get_new_job(bool global, struct thread_data *parent,
462                                        bool preserve_eo, const char *jobname)
463 {
464         struct thread_data *td;
465
466         if (global)
467                 return &def_thread;
468         if (setup_thread_area()) {
469                 log_err("error: failed to setup shm segment\n");
470                 return NULL;
471         }
472         if (thread_number >= max_jobs) {
473                 log_err("error: maximum number of jobs (%d) reached.\n",
474                                 max_jobs);
475                 return NULL;
476         }
477
478         td = &threads[thread_number++];
479         *td = *parent;
480
481         INIT_FLIST_HEAD(&td->opt_list);
482         if (parent != &def_thread)
483                 copy_opt_list(td, parent);
484
485         td->io_ops = NULL;
486         td->io_ops_init = 0;
487         if (!preserve_eo)
488                 td->eo = NULL;
489
490         td->o.uid = td->o.gid = -1U;
491
492         dup_files(td, parent);
493         fio_options_mem_dupe(td);
494
495         profile_add_hooks(td);
496
497         td->thread_number = thread_number;
498         td->subjob_number = 0;
499
500         if (jobname)
501                 td->o.name = strdup(jobname);
502
503         if (!parent->o.group_reporting || parent == &def_thread)
504                 stat_number++;
505
506         return td;
507 }
508
509 static void put_job(struct thread_data *td)
510 {
511         if (td == &def_thread)
512                 return;
513
514         profile_td_exit(td);
515         flow_exit_job(td);
516
517         if (td->error)
518                 log_info("fio: %s\n", td->verror);
519
520         fio_options_free(td);
521         fio_dump_options_free(td);
522         if (td->io_ops)
523                 free_ioengine(td);
524
525         if (td->o.name)
526                 free(td->o.name);
527
528         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
529         thread_number--;
530 }
531
532 static int __setup_rate(struct thread_data *td, enum fio_ddir ddir)
533 {
534         unsigned int bs = td->o.min_bs[ddir];
535
536         assert(ddir_rw(ddir));
537
538         if (td->o.rate[ddir])
539                 td->rate_bps[ddir] = td->o.rate[ddir];
540         else
541                 td->rate_bps[ddir] = (uint64_t) td->o.rate_iops[ddir] * bs;
542
543         if (!td->rate_bps[ddir]) {
544                 log_err("rate lower than supported\n");
545                 return -1;
546         }
547
548         td->rate_next_io_time[ddir] = 0;
549         td->rate_io_issue_bytes[ddir] = 0;
550         td->last_usec[ddir] = 0;
551         return 0;
552 }
553
554 static int setup_rate(struct thread_data *td)
555 {
556         int ret = 0;
557
558         if (td->o.rate[DDIR_READ] || td->o.rate_iops[DDIR_READ])
559                 ret = __setup_rate(td, DDIR_READ);
560         if (td->o.rate[DDIR_WRITE] || td->o.rate_iops[DDIR_WRITE])
561                 ret |= __setup_rate(td, DDIR_WRITE);
562         if (td->o.rate[DDIR_TRIM] || td->o.rate_iops[DDIR_TRIM])
563                 ret |= __setup_rate(td, DDIR_TRIM);
564
565         return ret;
566 }
567
568 static int fixed_block_size(struct thread_options *o)
569 {
570         return o->min_bs[DDIR_READ] == o->max_bs[DDIR_READ] &&
571                 o->min_bs[DDIR_WRITE] == o->max_bs[DDIR_WRITE] &&
572                 o->min_bs[DDIR_TRIM] == o->max_bs[DDIR_TRIM] &&
573                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_WRITE] &&
574                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_TRIM];
575 }
576
577 /*
578  * <3 Johannes
579  */
580 static unsigned int gcd(unsigned int m, unsigned int n)
581 {
582         if (!n)
583                 return m;
584
585         return gcd(n, m % n);
586 }
587
588 /*
589  * Lazy way of fixing up options that depend on each other. We could also
590  * define option callback handlers, but this is easier.
591  */
592 static int fixup_options(struct thread_data *td)
593 {
594         struct thread_options *o = &td->o;
595         int ret = 0;
596
597 #ifndef CONFIG_PSHARED
598         if (!o->use_thread) {
599                 log_info("fio: this platform does not support process shared"
600                          " mutexes, forcing use of threads. Use the 'thread'"
601                          " option to get rid of this warning.\n");
602                 o->use_thread = 1;
603                 ret = warnings_fatal;
604         }
605 #endif
606
607         if (o->write_iolog_file && o->read_iolog_file) {
608                 log_err("fio: read iolog overrides write_iolog\n");
609                 free(o->write_iolog_file);
610                 o->write_iolog_file = NULL;
611                 ret = warnings_fatal;
612         }
613
614         /*
615          * only really works with 1 file
616          */
617         if (o->zone_size && o->open_files > 1)
618                 o->zone_size = 0;
619
620         /*
621          * If zone_range isn't specified, backward compatibility dictates it
622          * should be made equal to zone_size.
623          */
624         if (o->zone_size && !o->zone_range)
625                 o->zone_range = o->zone_size;
626
627         /*
628          * Reads can do overwrites, we always need to pre-create the file
629          */
630         if (td_read(td))
631                 o->overwrite = 1;
632
633         if (!o->min_bs[DDIR_READ])
634                 o->min_bs[DDIR_READ] = o->bs[DDIR_READ];
635         if (!o->max_bs[DDIR_READ])
636                 o->max_bs[DDIR_READ] = o->bs[DDIR_READ];
637         if (!o->min_bs[DDIR_WRITE])
638                 o->min_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
639         if (!o->max_bs[DDIR_WRITE])
640                 o->max_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
641         if (!o->min_bs[DDIR_TRIM])
642                 o->min_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
643         if (!o->max_bs[DDIR_TRIM])
644                 o->max_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
645
646         o->rw_min_bs = min(o->min_bs[DDIR_READ], o->min_bs[DDIR_WRITE]);
647         o->rw_min_bs = min(o->min_bs[DDIR_TRIM], o->rw_min_bs);
648
649         /*
650          * For random IO, allow blockalign offset other than min_bs.
651          */
652         if (!o->ba[DDIR_READ] || !td_random(td))
653                 o->ba[DDIR_READ] = o->min_bs[DDIR_READ];
654         if (!o->ba[DDIR_WRITE] || !td_random(td))
655                 o->ba[DDIR_WRITE] = o->min_bs[DDIR_WRITE];
656         if (!o->ba[DDIR_TRIM] || !td_random(td))
657                 o->ba[DDIR_TRIM] = o->min_bs[DDIR_TRIM];
658
659         if ((o->ba[DDIR_READ] != o->min_bs[DDIR_READ] ||
660             o->ba[DDIR_WRITE] != o->min_bs[DDIR_WRITE] ||
661             o->ba[DDIR_TRIM] != o->min_bs[DDIR_TRIM]) &&
662             !o->norandommap) {
663                 log_err("fio: Any use of blockalign= turns off randommap\n");
664                 o->norandommap = 1;
665                 ret = warnings_fatal;
666         }
667
668         if (!o->file_size_high)
669                 o->file_size_high = o->file_size_low;
670
671         if (o->start_delay_high) {
672                 if (!o->start_delay_orig)
673                         o->start_delay_orig = o->start_delay;
674                 o->start_delay = rand_between(&td->delay_state,
675                                                 o->start_delay_orig,
676                                                 o->start_delay_high);
677         }
678
679         if (o->norandommap && o->verify != VERIFY_NONE
680             && !fixed_block_size(o))  {
681                 log_err("fio: norandommap given for variable block sizes, "
682                         "verify limited\n");
683                 ret = warnings_fatal;
684         }
685         if (o->bs_unaligned && (o->odirect || td_ioengine_flagged(td, FIO_RAWIO)))
686                 log_err("fio: bs_unaligned may not work with raw io\n");
687
688         /*
689          * thinktime_spin must be less than thinktime
690          */
691         if (o->thinktime_spin > o->thinktime)
692                 o->thinktime_spin = o->thinktime;
693
694         /*
695          * The low water mark cannot be bigger than the iodepth
696          */
697         if (o->iodepth_low > o->iodepth || !o->iodepth_low)
698                 o->iodepth_low = o->iodepth;
699
700         /*
701          * If batch number isn't set, default to the same as iodepth
702          */
703         if (o->iodepth_batch > o->iodepth || !o->iodepth_batch)
704                 o->iodepth_batch = o->iodepth;
705
706         /*
707          * If max batch complete number isn't set or set incorrectly,
708          * default to the same as iodepth_batch_complete_min
709          */
710         if (o->iodepth_batch_complete_min > o->iodepth_batch_complete_max)
711                 o->iodepth_batch_complete_max = o->iodepth_batch_complete_min;
712
713         /*
714          * There's no need to check for in-flight overlapping IOs if the job
715          * isn't changing data or the maximum iodepth is guaranteed to be 1
716          */
717         if (o->serialize_overlap && !(td->flags & TD_F_READ_IOLOG) &&
718             (!(td_write(td) || td_trim(td)) || o->iodepth == 1))
719                 o->serialize_overlap = 0;
720         /*
721          * Currently can't check for overlaps in offload mode
722          */
723         if (o->serialize_overlap && o->io_submit_mode == IO_MODE_OFFLOAD) {
724                 log_err("fio: checking for in-flight overlaps when the "
725                         "io_submit_mode is offload is not supported\n");
726                 o->serialize_overlap = 0;
727                 ret = warnings_fatal;
728         }
729
730         if (o->nr_files > td->files_index)
731                 o->nr_files = td->files_index;
732
733         if (o->open_files > o->nr_files || !o->open_files)
734                 o->open_files = o->nr_files;
735
736         if (((o->rate[DDIR_READ] + o->rate[DDIR_WRITE] + o->rate[DDIR_TRIM]) &&
737             (o->rate_iops[DDIR_READ] + o->rate_iops[DDIR_WRITE] + o->rate_iops[DDIR_TRIM])) ||
738             ((o->ratemin[DDIR_READ] + o->ratemin[DDIR_WRITE] + o->ratemin[DDIR_TRIM]) &&
739             (o->rate_iops_min[DDIR_READ] + o->rate_iops_min[DDIR_WRITE] + o->rate_iops_min[DDIR_TRIM]))) {
740                 log_err("fio: rate and rate_iops are mutually exclusive\n");
741                 ret = 1;
742         }
743         if ((o->rate[DDIR_READ] && (o->rate[DDIR_READ] < o->ratemin[DDIR_READ])) ||
744             (o->rate[DDIR_WRITE] && (o->rate[DDIR_WRITE] < o->ratemin[DDIR_WRITE])) ||
745             (o->rate[DDIR_TRIM] && (o->rate[DDIR_TRIM] < o->ratemin[DDIR_TRIM])) ||
746             (o->rate_iops[DDIR_READ] && (o->rate_iops[DDIR_READ] < o->rate_iops_min[DDIR_READ])) ||
747             (o->rate_iops[DDIR_WRITE] && (o->rate_iops[DDIR_WRITE] < o->rate_iops_min[DDIR_WRITE])) ||
748             (o->rate_iops[DDIR_TRIM] && (o->rate_iops[DDIR_TRIM] < o->rate_iops_min[DDIR_TRIM]))) {
749                 log_err("fio: minimum rate exceeds rate\n");
750                 ret = 1;
751         }
752
753         if (!o->timeout && o->time_based) {
754                 log_err("fio: time_based requires a runtime/timeout setting\n");
755                 o->time_based = 0;
756                 ret = warnings_fatal;
757         }
758
759         if (o->fill_device && !o->size)
760                 o->size = -1ULL;
761
762         if (o->verify != VERIFY_NONE) {
763                 if (td_write(td) && o->do_verify && o->numjobs > 1 &&
764                     (o->filename ||
765                      !(o->unique_filename &&
766                        strstr(o->filename_format, "$jobname") &&
767                        strstr(o->filename_format, "$jobnum") &&
768                        strstr(o->filename_format, "$filenum")))) {
769                         log_info("fio: multiple writers may overwrite blocks "
770                                 "that belong to other jobs. This can cause "
771                                 "verification failures.\n");
772                         ret = warnings_fatal;
773                 }
774
775                 /*
776                  * Warn if verification is requested but no verification of any
777                  * kind can be started due to time constraints
778                  */
779                 if (td_write(td) && o->do_verify && o->timeout &&
780                     o->time_based && !td_read(td) && !o->verify_backlog) {
781                         log_info("fio: verification read phase will never "
782                                  "start because write phase uses all of "
783                                  "runtime\n");
784                         ret = warnings_fatal;
785                 }
786
787                 if (!fio_option_is_set(o, refill_buffers))
788                         o->refill_buffers = 1;
789
790                 if (o->max_bs[DDIR_WRITE] != o->min_bs[DDIR_WRITE] &&
791                     !o->verify_interval)
792                         o->verify_interval = o->min_bs[DDIR_WRITE];
793
794                 /*
795                  * Verify interval must be smaller or equal to the
796                  * write size.
797                  */
798                 if (o->verify_interval > o->min_bs[DDIR_WRITE])
799                         o->verify_interval = o->min_bs[DDIR_WRITE];
800                 else if (td_read(td) && o->verify_interval > o->min_bs[DDIR_READ])
801                         o->verify_interval = o->min_bs[DDIR_READ];
802
803                 /*
804                  * Verify interval must be a factor of both min and max
805                  * write size
806                  */
807                 if (!o->verify_interval ||
808                     (o->min_bs[DDIR_WRITE] % o->verify_interval) ||
809                     (o->max_bs[DDIR_WRITE] % o->verify_interval))
810                         o->verify_interval = gcd(o->min_bs[DDIR_WRITE],
811                                                         o->max_bs[DDIR_WRITE]);
812         }
813
814         if (o->pre_read) {
815                 if (o->invalidate_cache)
816                         o->invalidate_cache = 0;
817                 if (td_ioengine_flagged(td, FIO_PIPEIO)) {
818                         log_info("fio: cannot pre-read files with an IO engine"
819                                  " that isn't seekable. Pre-read disabled.\n");
820                         ret = warnings_fatal;
821                 }
822         }
823
824         if (o->unit_base == N2S_NONE) {
825                 if (td_ioengine_flagged(td, FIO_BIT_BASED))
826                         o->unit_base = N2S_BITPERSEC;
827                 else
828                         o->unit_base = N2S_BYTEPERSEC;
829         }
830
831 #ifndef FIO_HAVE_ANY_FALLOCATE
832         /* Platform doesn't support any fallocate so force it to none */
833         o->fallocate_mode = FIO_FALLOCATE_NONE;
834 #endif
835
836 #ifndef CONFIG_FDATASYNC
837         if (o->fdatasync_blocks) {
838                 log_info("fio: this platform does not support fdatasync()"
839                          " falling back to using fsync().  Use the 'fsync'"
840                          " option instead of 'fdatasync' to get rid of"
841                          " this warning\n");
842                 o->fsync_blocks = o->fdatasync_blocks;
843                 o->fdatasync_blocks = 0;
844                 ret = warnings_fatal;
845         }
846 #endif
847
848 #ifdef WIN32
849         /*
850          * Windows doesn't support O_DIRECT or O_SYNC with the _open interface,
851          * so fail if we're passed those flags
852          */
853         if (td_ioengine_flagged(td, FIO_SYNCIO) && (o->odirect || o->sync_io)) {
854                 log_err("fio: Windows does not support direct or non-buffered io with"
855                                 " the synchronous ioengines. Use the 'windowsaio' ioengine"
856                                 " with 'direct=1' and 'iodepth=1' instead.\n");
857                 ret = 1;
858         }
859 #endif
860
861         /*
862          * For fully compressible data, just zero them at init time.
863          * It's faster than repeatedly filling it. For non-zero
864          * compression, we should have refill_buffers set. Set it, unless
865          * the job file already changed it.
866          */
867         if (o->compress_percentage) {
868                 if (o->compress_percentage == 100) {
869                         o->zero_buffers = 1;
870                         o->compress_percentage = 0;
871                 } else if (!fio_option_is_set(o, refill_buffers)) {
872                         o->refill_buffers = 1;
873                         td->flags |= TD_F_REFILL_BUFFERS;
874                 }
875         }
876
877         /*
878          * Using a non-uniform random distribution excludes usage of
879          * a random map
880          */
881         if (o->random_distribution != FIO_RAND_DIST_RANDOM)
882                 o->norandommap = 1;
883
884         /*
885          * If size is set but less than the min block size, complain
886          */
887         if (o->size && o->size < td_min_bs(td)) {
888                 log_err("fio: size too small, must not be less than minimum block size: %llu < %u\n",
889                         (unsigned long long) o->size, td_min_bs(td));
890                 ret = 1;
891         }
892
893         /*
894          * O_ATOMIC implies O_DIRECT
895          */
896         if (o->oatomic)
897                 o->odirect = 1;
898
899         /*
900          * If randseed is set, that overrides randrepeat
901          */
902         if (fio_option_is_set(o, rand_seed))
903                 o->rand_repeatable = 0;
904
905         if (td_ioengine_flagged(td, FIO_NOEXTEND) && o->file_append) {
906                 log_err("fio: can't append/extent with IO engine %s\n", td->io_ops->name);
907                 ret = 1;
908         }
909
910         if (fio_option_is_set(o, gtod_cpu)) {
911                 fio_gtod_init();
912                 fio_gtod_set_cpu(o->gtod_cpu);
913                 fio_gtod_offload = 1;
914         }
915
916         td->loops = o->loops;
917         if (!td->loops)
918                 td->loops = 1;
919
920         if (o->block_error_hist && o->nr_files != 1) {
921                 log_err("fio: block error histogram only available "
922                         "with a single file per job, but %d files "
923                         "provided\n", o->nr_files);
924                 ret = 1;
925         }
926
927         if (fio_option_is_set(o, clat_percentiles) &&
928             !fio_option_is_set(o, lat_percentiles)) {
929                 o->lat_percentiles = !o->clat_percentiles;
930         } else if (fio_option_is_set(o, lat_percentiles) &&
931                    !fio_option_is_set(o, clat_percentiles)) {
932                 o->clat_percentiles = !o->lat_percentiles;
933         } else if (fio_option_is_set(o, lat_percentiles) &&
934                    fio_option_is_set(o, clat_percentiles) &&
935                    o->lat_percentiles && o->clat_percentiles) {
936                 log_err("fio: lat_percentiles and clat_percentiles are "
937                         "mutually exclusive\n");
938                 ret = 1;
939         }
940
941         if (o->disable_lat)
942                 o->lat_percentiles = 0;
943         if (o->disable_clat)
944                 o->clat_percentiles = 0;
945
946         /*
947          * Fix these up to be nsec internally
948          */
949         o->max_latency *= 1000ULL;
950         o->latency_target *= 1000ULL;
951         o->latency_window *= 1000ULL;
952
953         return ret;
954 }
955
956 static void init_rand_file_service(struct thread_data *td)
957 {
958         unsigned long nranges = td->o.nr_files << FIO_FSERVICE_SHIFT;
959         const unsigned int seed = td->rand_seeds[FIO_RAND_FILE_OFF];
960
961         if (td->o.file_service_type == FIO_FSERVICE_ZIPF) {
962                 zipf_init(&td->next_file_zipf, nranges, td->zipf_theta, seed);
963                 zipf_disable_hash(&td->next_file_zipf);
964         } else if (td->o.file_service_type == FIO_FSERVICE_PARETO) {
965                 pareto_init(&td->next_file_zipf, nranges, td->pareto_h, seed);
966                 zipf_disable_hash(&td->next_file_zipf);
967         } else if (td->o.file_service_type == FIO_FSERVICE_GAUSS) {
968                 gauss_init(&td->next_file_gauss, nranges, td->gauss_dev, seed);
969                 gauss_disable_hash(&td->next_file_gauss);
970         }
971 }
972
973 void td_fill_verify_state_seed(struct thread_data *td)
974 {
975         bool use64;
976
977         if (td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE64)
978                 use64 = true;
979         else
980                 use64 = false;
981
982         init_rand_seed(&td->verify_state, td->rand_seeds[FIO_RAND_VER_OFF],
983                 use64);
984 }
985
986 static void td_fill_rand_seeds_internal(struct thread_data *td, bool use64)
987 {
988         unsigned int read_seed = td->rand_seeds[FIO_RAND_BS_OFF];
989         unsigned int write_seed = td->rand_seeds[FIO_RAND_BS1_OFF];
990         unsigned int trim_seed = td->rand_seeds[FIO_RAND_BS2_OFF];
991         int i;
992
993         /*
994          * trimwrite is special in that we need to generate the same
995          * offsets to get the "write after trim" effect. If we are
996          * using bssplit to set buffer length distributions, ensure that
997          * we seed the trim and write generators identically. Ditto for
998          * verify, read and writes must have the same seed, if we are doing
999          * read verify.
1000          */
1001         if (td->o.verify != VERIFY_NONE)
1002                 write_seed = read_seed;
1003         if (td_trimwrite(td))
1004                 trim_seed = write_seed;
1005         init_rand_seed(&td->bsrange_state[DDIR_READ], read_seed, use64);
1006         init_rand_seed(&td->bsrange_state[DDIR_WRITE], write_seed, use64);
1007         init_rand_seed(&td->bsrange_state[DDIR_TRIM], trim_seed, use64);
1008
1009         td_fill_verify_state_seed(td);
1010         init_rand_seed(&td->rwmix_state, td->rand_seeds[FIO_RAND_MIX_OFF], false);
1011
1012         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
1013                 init_rand_seed(&td->next_file_state, td->rand_seeds[FIO_RAND_FILE_OFF], use64);
1014         else if (td->o.file_service_type & __FIO_FSERVICE_NONUNIFORM)
1015                 init_rand_file_service(td);
1016
1017         init_rand_seed(&td->file_size_state, td->rand_seeds[FIO_RAND_FILE_SIZE_OFF], use64);
1018         init_rand_seed(&td->trim_state, td->rand_seeds[FIO_RAND_TRIM_OFF], use64);
1019         init_rand_seed(&td->delay_state, td->rand_seeds[FIO_RAND_START_DELAY], use64);
1020         init_rand_seed(&td->poisson_state[0], td->rand_seeds[FIO_RAND_POISSON_OFF], 0);
1021         init_rand_seed(&td->poisson_state[1], td->rand_seeds[FIO_RAND_POISSON2_OFF], 0);
1022         init_rand_seed(&td->poisson_state[2], td->rand_seeds[FIO_RAND_POISSON3_OFF], 0);
1023         init_rand_seed(&td->dedupe_state, td->rand_seeds[FIO_DEDUPE_OFF], false);
1024         init_rand_seed(&td->zone_state, td->rand_seeds[FIO_RAND_ZONE_OFF], false);
1025
1026         if (!td_random(td))
1027                 return;
1028
1029         if (td->o.rand_repeatable)
1030                 td->rand_seeds[FIO_RAND_BLOCK_OFF] = FIO_RANDSEED * td->thread_number;
1031
1032         init_rand_seed(&td->random_state, td->rand_seeds[FIO_RAND_BLOCK_OFF], use64);
1033
1034         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1035                 struct frand_state *s = &td->seq_rand_state[i];
1036
1037                 init_rand_seed(s, td->rand_seeds[FIO_RAND_SEQ_RAND_READ_OFF], false);
1038         }
1039 }
1040
1041 void td_fill_rand_seeds(struct thread_data *td)
1042 {
1043         bool use64;
1044
1045         if (td->o.allrand_repeatable) {
1046                 unsigned int i;
1047
1048                 for (i = 0; i < FIO_RAND_NR_OFFS; i++)
1049                         td->rand_seeds[i] = FIO_RANDSEED * td->thread_number
1050                                 + i;
1051         }
1052
1053         if (td->o.random_generator == FIO_RAND_GEN_TAUSWORTHE64)
1054                 use64 = true;
1055         else
1056                 use64 = false;
1057
1058         td_fill_rand_seeds_internal(td, use64);
1059
1060         init_rand_seed(&td->buf_state, td->rand_seeds[FIO_RAND_BUF_OFF], use64);
1061         frand_copy(&td->buf_state_prev, &td->buf_state);
1062 }
1063
1064 /*
1065  * Initializes the ioengine configured for a job, if it has not been done so
1066  * already.
1067  */
1068 int ioengine_load(struct thread_data *td)
1069 {
1070         if (!td->o.ioengine) {
1071                 log_err("fio: internal fault, no IO engine specified\n");
1072                 return 1;
1073         }
1074
1075         if (td->io_ops) {
1076                 struct ioengine_ops *ops;
1077                 void *dlhandle;
1078
1079                 /* An engine is loaded, but the requested ioengine
1080                  * may have changed.
1081                  */
1082                 if (!strcmp(td->io_ops->name, td->o.ioengine)) {
1083                         /* The right engine is already loaded */
1084                         return 0;
1085                 }
1086
1087                 /*
1088                  * Name of file and engine may be different, load ops
1089                  * for this name and see if they match. If they do, then
1090                  * the engine is unchanged.
1091                  */
1092                 dlhandle = td->io_ops_dlhandle;
1093                 ops = load_ioengine(td);
1094                 if (ops == td->io_ops && dlhandle == td->io_ops_dlhandle) {
1095                         if (dlhandle)
1096                                 dlclose(dlhandle);
1097                         return 0;
1098                 }
1099
1100                 if (dlhandle && dlhandle != td->io_ops_dlhandle)
1101                         dlclose(dlhandle);
1102
1103                 /* Unload the old engine. */
1104                 free_ioengine(td);
1105         }
1106
1107         td->io_ops = load_ioengine(td);
1108         if (!td->io_ops) {
1109                 log_err("fio: failed to load engine\n");
1110                 return 1;
1111         }
1112
1113         if (td->io_ops->option_struct_size && td->io_ops->options) {
1114                 /*
1115                  * In cases where td->eo is set, clone it for a child thread.
1116                  * This requires that the parent thread has the same ioengine,
1117                  * but that requirement must be enforced by the code which
1118                  * cloned the thread.
1119                  */
1120                 void *origeo = td->eo;
1121                 /*
1122                  * Otherwise use the default thread options.
1123                  */
1124                 if (!origeo && td != &def_thread && def_thread.eo &&
1125                     def_thread.io_ops->options == td->io_ops->options)
1126                         origeo = def_thread.eo;
1127
1128                 options_init(td->io_ops->options);
1129                 td->eo = malloc(td->io_ops->option_struct_size);
1130                 /*
1131                  * Use the default thread as an option template if this uses the
1132                  * same options structure and there are non-default options
1133                  * used.
1134                  */
1135                 if (origeo) {
1136                         memcpy(td->eo, origeo, td->io_ops->option_struct_size);
1137                         options_mem_dupe(td->io_ops->options, td->eo);
1138                 } else {
1139                         memset(td->eo, 0, td->io_ops->option_struct_size);
1140                         fill_default_options(td->eo, td->io_ops->options);
1141                 }
1142                 *(struct thread_data **)td->eo = td;
1143         }
1144
1145         if (td->o.odirect)
1146                 td->io_ops->flags |= FIO_RAWIO;
1147
1148         td_set_ioengine_flags(td);
1149         return 0;
1150 }
1151
1152 static void init_flags(struct thread_data *td)
1153 {
1154         struct thread_options *o = &td->o;
1155         int i;
1156
1157         if (o->verify_backlog)
1158                 td->flags |= TD_F_VER_BACKLOG;
1159         if (o->trim_backlog)
1160                 td->flags |= TD_F_TRIM_BACKLOG;
1161         if (o->read_iolog_file)
1162                 td->flags |= TD_F_READ_IOLOG;
1163         if (o->refill_buffers)
1164                 td->flags |= TD_F_REFILL_BUFFERS;
1165         /*
1166          * Always scramble buffers if asked to
1167          */
1168         if (o->scramble_buffers && fio_option_is_set(o, scramble_buffers))
1169                 td->flags |= TD_F_SCRAMBLE_BUFFERS;
1170         /*
1171          * But also scramble buffers, unless we were explicitly asked
1172          * to zero them.
1173          */
1174         if (o->scramble_buffers && !(o->zero_buffers &&
1175             fio_option_is_set(o, zero_buffers)))
1176                 td->flags |= TD_F_SCRAMBLE_BUFFERS;
1177         if (o->verify != VERIFY_NONE)
1178                 td->flags |= TD_F_DO_VERIFY;
1179
1180         if (o->verify_async || o->io_submit_mode == IO_MODE_OFFLOAD)
1181                 td->flags |= TD_F_NEED_LOCK;
1182
1183         if (o->mem_type == MEM_CUDA_MALLOC)
1184                 td->flags &= ~TD_F_SCRAMBLE_BUFFERS;
1185
1186         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1187                 if (option_check_rate(td, i)) {
1188                         td->flags |= TD_F_CHECK_RATE;
1189                         break;
1190                 }
1191         }
1192 }
1193
1194 static int setup_random_seeds(struct thread_data *td)
1195 {
1196         unsigned long seed;
1197         unsigned int i;
1198
1199         if (!td->o.rand_repeatable && !fio_option_is_set(&td->o, rand_seed)) {
1200                 int ret = init_random_seeds(td->rand_seeds, sizeof(td->rand_seeds));
1201                 if (!ret)
1202                         td_fill_rand_seeds(td);
1203                 return ret;
1204         }
1205
1206         seed = td->o.rand_seed;
1207         for (i = 0; i < 4; i++)
1208                 seed *= 0x9e370001UL;
1209
1210         for (i = 0; i < FIO_RAND_NR_OFFS; i++) {
1211                 td->rand_seeds[i] = seed * td->thread_number + i;
1212                 seed *= 0x9e370001UL;
1213         }
1214
1215         td_fill_rand_seeds(td);
1216         return 0;
1217 }
1218
1219 enum {
1220         FPRE_NONE = 0,
1221         FPRE_JOBNAME,
1222         FPRE_JOBNUM,
1223         FPRE_FILENUM
1224 };
1225
1226 static struct fpre_keyword {
1227         const char *keyword;
1228         size_t strlen;
1229         int key;
1230 } fpre_keywords[] = {
1231         { .keyword = "$jobname",        .key = FPRE_JOBNAME, },
1232         { .keyword = "$jobnum",         .key = FPRE_JOBNUM, },
1233         { .keyword = "$filenum",        .key = FPRE_FILENUM, },
1234         { .keyword = NULL, },
1235         };
1236
1237 static char *make_filename(char *buf, size_t buf_size,struct thread_options *o,
1238                            const char *jobname, int jobnum, int filenum)
1239 {
1240         struct fpre_keyword *f;
1241         char copy[PATH_MAX];
1242         size_t dst_left = PATH_MAX - 1;
1243
1244         if (!o->filename_format || !strlen(o->filename_format)) {
1245                 sprintf(buf, "%s.%d.%d", jobname, jobnum, filenum);
1246                 return buf;
1247         }
1248
1249         for (f = &fpre_keywords[0]; f->keyword; f++)
1250                 f->strlen = strlen(f->keyword);
1251
1252         buf[buf_size - 1] = '\0';
1253         strncpy(buf, o->filename_format, buf_size - 1);
1254
1255         memset(copy, 0, sizeof(copy));
1256         for (f = &fpre_keywords[0]; f->keyword; f++) {
1257                 do {
1258                         size_t pre_len, post_start = 0;
1259                         char *str, *dst = copy;
1260
1261                         str = strcasestr(buf, f->keyword);
1262                         if (!str)
1263                                 break;
1264
1265                         pre_len = str - buf;
1266                         if (strlen(str) != f->strlen)
1267                                 post_start = pre_len + f->strlen;
1268
1269                         if (pre_len) {
1270                                 strncpy(dst, buf, pre_len);
1271                                 dst += pre_len;
1272                                 dst_left -= pre_len;
1273                         }
1274
1275                         switch (f->key) {
1276                         case FPRE_JOBNAME: {
1277                                 int ret;
1278
1279                                 ret = snprintf(dst, dst_left, "%s", jobname);
1280                                 if (ret < 0)
1281                                         break;
1282                                 else if (ret > dst_left) {
1283                                         log_err("fio: truncated filename\n");
1284                                         dst += dst_left;
1285                                         dst_left = 0;
1286                                 } else {
1287                                         dst += ret;
1288                                         dst_left -= ret;
1289                                 }
1290                                 break;
1291                                 }
1292                         case FPRE_JOBNUM: {
1293                                 int ret;
1294
1295                                 ret = snprintf(dst, dst_left, "%d", jobnum);
1296                                 if (ret < 0)
1297                                         break;
1298                                 else if (ret > dst_left) {
1299                                         log_err("fio: truncated filename\n");
1300                                         dst += dst_left;
1301                                         dst_left = 0;
1302                                 } else {
1303                                         dst += ret;
1304                                         dst_left -= ret;
1305                                 }
1306                                 break;
1307                                 }
1308                         case FPRE_FILENUM: {
1309                                 int ret;
1310
1311                                 ret = snprintf(dst, dst_left, "%d", filenum);
1312                                 if (ret < 0)
1313                                         break;
1314                                 else if (ret > dst_left) {
1315                                         log_err("fio: truncated filename\n");
1316                                         dst += dst_left;
1317                                         dst_left = 0;
1318                                 } else {
1319                                         dst += ret;
1320                                         dst_left -= ret;
1321                                 }
1322                                 break;
1323                                 }
1324                         default:
1325                                 assert(0);
1326                                 break;
1327                         }
1328
1329                         if (post_start)
1330                                 strncpy(dst, buf + post_start, dst_left);
1331
1332                         strncpy(buf, copy, buf_size - 1);
1333                 } while (1);
1334         }
1335
1336         return buf;
1337 }
1338
1339 bool parse_dryrun(void)
1340 {
1341         return dump_cmdline || parse_only;
1342 }
1343
1344 static void gen_log_name(char *name, size_t size, const char *logtype,
1345                          const char *logname, unsigned int num,
1346                          const char *suf, int per_job)
1347 {
1348         if (per_job)
1349                 snprintf(name, size, "%s_%s.%d.%s", logname, logtype, num, suf);
1350         else
1351                 snprintf(name, size, "%s_%s.%s", logname, logtype, suf);
1352 }
1353
1354 static int check_waitees(char *waitee)
1355 {
1356         struct thread_data *td;
1357         int i, ret = 0;
1358
1359         for_each_td(td, i) {
1360                 if (td->subjob_number)
1361                         continue;
1362
1363                 ret += !strcmp(td->o.name, waitee);
1364         }
1365
1366         return ret;
1367 }
1368
1369 static bool wait_for_ok(const char *jobname, struct thread_options *o)
1370 {
1371         int nw;
1372
1373         if (!o->wait_for)
1374                 return true;
1375
1376         if (!strcmp(jobname, o->wait_for)) {
1377                 log_err("%s: a job cannot wait for itself (wait_for=%s).\n",
1378                                 jobname, o->wait_for);
1379                 return false;
1380         }
1381
1382         if (!(nw = check_waitees(o->wait_for))) {
1383                 log_err("%s: waitee job %s unknown.\n", jobname, o->wait_for);
1384                 return false;
1385         }
1386
1387         if (nw > 1) {
1388                 log_err("%s: multiple waitees %s found,\n"
1389                         "please avoid duplicates when using wait_for option.\n",
1390                                 jobname, o->wait_for);
1391                 return false;
1392         }
1393
1394         return true;
1395 }
1396
1397 /*
1398  * Adds a job to the list of things todo. Sanitizes the various options
1399  * to make sure we don't have conflicts, and initializes various
1400  * members of td.
1401  */
1402 static int add_job(struct thread_data *td, const char *jobname, int job_add_num,
1403                    int recursed, int client_type)
1404 {
1405         unsigned int i;
1406         char fname[PATH_MAX];
1407         int numjobs, file_alloced;
1408         struct thread_options *o = &td->o;
1409         char logname[PATH_MAX + 32];
1410
1411         /*
1412          * the def_thread is just for options, it's not a real job
1413          */
1414         if (td == &def_thread)
1415                 return 0;
1416
1417         init_flags(td);
1418
1419         /*
1420          * if we are just dumping the output command line, don't add the job
1421          */
1422         if (parse_dryrun()) {
1423                 put_job(td);
1424                 return 0;
1425         }
1426
1427         td->client_type = client_type;
1428
1429         if (profile_td_init(td))
1430                 goto err;
1431
1432         if (ioengine_load(td))
1433                 goto err;
1434
1435         file_alloced = 0;
1436         if (!o->filename && !td->files_index && !o->read_iolog_file) {
1437                 file_alloced = 1;
1438
1439                 if (o->nr_files == 1 && exists_and_not_regfile(jobname))
1440                         add_file(td, jobname, job_add_num, 0);
1441                 else {
1442                         for (i = 0; i < o->nr_files; i++)
1443                                 add_file(td, make_filename(fname, sizeof(fname), o, jobname, job_add_num, i), job_add_num, 0);
1444                 }
1445         }
1446
1447         if (setup_random_seeds(td)) {
1448                 td_verror(td, errno, "setup_random_seeds");
1449                 goto err;
1450         }
1451
1452         if (fixup_options(td))
1453                 goto err;
1454
1455         /*
1456          * Belongs to fixup_options, but o->name is not necessarily set as yet
1457          */
1458         if (!wait_for_ok(jobname, o))
1459                 goto err;
1460
1461         flow_init_job(td);
1462
1463         /*
1464          * IO engines only need this for option callbacks, and the address may
1465          * change in subprocesses.
1466          */
1467         if (td->eo)
1468                 *(struct thread_data **)td->eo = NULL;
1469
1470         if (td_ioengine_flagged(td, FIO_DISKLESSIO)) {
1471                 struct fio_file *f;
1472
1473                 for_each_file(td, f, i)
1474                         f->real_file_size = -1ULL;
1475         }
1476
1477         td->sem = fio_sem_init(FIO_SEM_LOCKED);
1478
1479         td->ts.clat_percentiles = o->clat_percentiles;
1480         td->ts.lat_percentiles = o->lat_percentiles;
1481         td->ts.percentile_precision = o->percentile_precision;
1482         memcpy(td->ts.percentile_list, o->percentile_list, sizeof(o->percentile_list));
1483         td->ts.sig_figs = o->sig_figs;
1484
1485         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1486                 td->ts.clat_stat[i].min_val = ULONG_MAX;
1487                 td->ts.slat_stat[i].min_val = ULONG_MAX;
1488                 td->ts.lat_stat[i].min_val = ULONG_MAX;
1489                 td->ts.bw_stat[i].min_val = ULONG_MAX;
1490                 td->ts.iops_stat[i].min_val = ULONG_MAX;
1491         }
1492         td->ts.sync_stat.min_val = ULONG_MAX;
1493         td->ddir_seq_nr = o->ddir_seq_nr;
1494
1495         if ((o->stonewall || o->new_group) && prev_group_jobs) {
1496                 prev_group_jobs = 0;
1497                 groupid++;
1498                 if (groupid == INT_MAX) {
1499                         log_err("fio: too many groups defined\n");
1500                         goto err;
1501                 }
1502         }
1503
1504         td->groupid = groupid;
1505         prev_group_jobs++;
1506
1507         if (setup_rate(td))
1508                 goto err;
1509
1510         if (o->write_lat_log) {
1511                 struct log_params p = {
1512                         .td = td,
1513                         .avg_msec = o->log_avg_msec,
1514                         .hist_msec = o->log_hist_msec,
1515                         .hist_coarseness = o->log_hist_coarseness,
1516                         .log_type = IO_LOG_TYPE_LAT,
1517                         .log_offset = o->log_offset,
1518                         .log_gz = o->log_gz,
1519                         .log_gz_store = o->log_gz_store,
1520                 };
1521                 const char *pre = o->lat_log_file ? o->lat_log_file : o->name;
1522                 const char *suf;
1523
1524                 if (p.log_gz_store)
1525                         suf = "log.fz";
1526                 else
1527                         suf = "log";
1528
1529                 gen_log_name(logname, sizeof(logname), "lat", pre,
1530                                 td->thread_number, suf, o->per_job_logs);
1531                 setup_log(&td->lat_log, &p, logname);
1532
1533                 gen_log_name(logname, sizeof(logname), "slat", pre,
1534                                 td->thread_number, suf, o->per_job_logs);
1535                 setup_log(&td->slat_log, &p, logname);
1536
1537                 gen_log_name(logname, sizeof(logname), "clat", pre,
1538                                 td->thread_number, suf, o->per_job_logs);
1539                 setup_log(&td->clat_log, &p, logname);
1540         }
1541
1542         if (o->write_hist_log) {
1543                 struct log_params p = {
1544                         .td = td,
1545                         .avg_msec = o->log_avg_msec,
1546                         .hist_msec = o->log_hist_msec,
1547                         .hist_coarseness = o->log_hist_coarseness,
1548                         .log_type = IO_LOG_TYPE_HIST,
1549                         .log_offset = o->log_offset,
1550                         .log_gz = o->log_gz,
1551                         .log_gz_store = o->log_gz_store,
1552                 };
1553                 const char *pre = o->hist_log_file ? o->hist_log_file : o->name;
1554                 const char *suf;
1555
1556 #ifndef CONFIG_ZLIB
1557                 if (td->client_type) {
1558                         log_err("fio: --write_hist_log requires zlib in client/server mode\n");
1559                         goto err;
1560                 }
1561 #endif
1562
1563                 if (p.log_gz_store)
1564                         suf = "log.fz";
1565                 else
1566                         suf = "log";
1567
1568                 gen_log_name(logname, sizeof(logname), "clat_hist", pre,
1569                                 td->thread_number, suf, o->per_job_logs);
1570                 setup_log(&td->clat_hist_log, &p, logname);
1571         }
1572
1573         if (o->write_bw_log) {
1574                 struct log_params p = {
1575                         .td = td,
1576                         .avg_msec = o->log_avg_msec,
1577                         .hist_msec = o->log_hist_msec,
1578                         .hist_coarseness = o->log_hist_coarseness,
1579                         .log_type = IO_LOG_TYPE_BW,
1580                         .log_offset = o->log_offset,
1581                         .log_gz = o->log_gz,
1582                         .log_gz_store = o->log_gz_store,
1583                 };
1584                 const char *pre = o->bw_log_file ? o->bw_log_file : o->name;
1585                 const char *suf;
1586
1587                 if (fio_option_is_set(o, bw_avg_time))
1588                         p.avg_msec = min(o->log_avg_msec, o->bw_avg_time);
1589                 else
1590                         o->bw_avg_time = p.avg_msec;
1591
1592                 p.hist_msec = o->log_hist_msec;
1593                 p.hist_coarseness = o->log_hist_coarseness;
1594
1595                 if (p.log_gz_store)
1596                         suf = "log.fz";
1597                 else
1598                         suf = "log";
1599
1600                 gen_log_name(logname, sizeof(logname), "bw", pre,
1601                                 td->thread_number, suf, o->per_job_logs);
1602                 setup_log(&td->bw_log, &p, logname);
1603         }
1604         if (o->write_iops_log) {
1605                 struct log_params p = {
1606                         .td = td,
1607                         .avg_msec = o->log_avg_msec,
1608                         .hist_msec = o->log_hist_msec,
1609                         .hist_coarseness = o->log_hist_coarseness,
1610                         .log_type = IO_LOG_TYPE_IOPS,
1611                         .log_offset = o->log_offset,
1612                         .log_gz = o->log_gz,
1613                         .log_gz_store = o->log_gz_store,
1614                 };
1615                 const char *pre = o->iops_log_file ? o->iops_log_file : o->name;
1616                 const char *suf;
1617
1618                 if (fio_option_is_set(o, iops_avg_time))
1619                         p.avg_msec = min(o->log_avg_msec, o->iops_avg_time);
1620                 else
1621                         o->iops_avg_time = p.avg_msec;
1622
1623                 p.hist_msec = o->log_hist_msec;
1624                 p.hist_coarseness = o->log_hist_coarseness;
1625
1626                 if (p.log_gz_store)
1627                         suf = "log.fz";
1628                 else
1629                         suf = "log";
1630
1631                 gen_log_name(logname, sizeof(logname), "iops", pre,
1632                                 td->thread_number, suf, o->per_job_logs);
1633                 setup_log(&td->iops_log, &p, logname);
1634         }
1635
1636         if (!o->name)
1637                 o->name = strdup(jobname);
1638
1639         if (output_format & FIO_OUTPUT_NORMAL) {
1640                 if (!job_add_num) {
1641                         if (is_backend && !recursed)
1642                                 fio_server_send_add_job(td);
1643
1644                         if (!td_ioengine_flagged(td, FIO_NOIO)) {
1645                                 char *c1, *c2, *c3, *c4;
1646                                 char *c5 = NULL, *c6 = NULL;
1647                                 int i2p = is_power_of_2(o->kb_base);
1648
1649                                 c1 = num2str(o->min_bs[DDIR_READ], o->sig_figs, 1, i2p, N2S_BYTE);
1650                                 c2 = num2str(o->max_bs[DDIR_READ], o->sig_figs, 1, i2p, N2S_BYTE);
1651                                 c3 = num2str(o->min_bs[DDIR_WRITE], o->sig_figs, 1, i2p, N2S_BYTE);
1652                                 c4 = num2str(o->max_bs[DDIR_WRITE], o->sig_figs, 1, i2p, N2S_BYTE);
1653
1654                                 if (!o->bs_is_seq_rand) {
1655                                         c5 = num2str(o->min_bs[DDIR_TRIM], o->sig_figs, 1, i2p, N2S_BYTE);
1656                                         c6 = num2str(o->max_bs[DDIR_TRIM], o->sig_figs, 1, i2p, N2S_BYTE);
1657                                 }
1658
1659                                 log_info("%s: (g=%d): rw=%s, ", td->o.name,
1660                                                         td->groupid,
1661                                                         ddir_str(o->td_ddir));
1662
1663                                 if (o->bs_is_seq_rand)
1664                                         log_info("bs=(R) %s-%s, (W) %s-%s, bs_is_seq_rand, ",
1665                                                         c1, c2, c3, c4);
1666                                 else
1667                                         log_info("bs=(R) %s-%s, (W) %s-%s, (T) %s-%s, ",
1668                                                         c1, c2, c3, c4, c5, c6);
1669
1670                                 log_info("ioengine=%s, iodepth=%u\n",
1671                                                 td->io_ops->name, o->iodepth);
1672
1673                                 free(c1);
1674                                 free(c2);
1675                                 free(c3);
1676                                 free(c4);
1677                                 free(c5);
1678                                 free(c6);
1679                         }
1680                 } else if (job_add_num == 1)
1681                         log_info("...\n");
1682         }
1683
1684         if (td_steadystate_init(td))
1685                 goto err;
1686
1687         /*
1688          * recurse add identical jobs, clear numjobs and stonewall options
1689          * as they don't apply to sub-jobs
1690          */
1691         numjobs = o->numjobs;
1692         while (--numjobs) {
1693                 struct thread_data *td_new = get_new_job(false, td, true, jobname);
1694
1695                 if (!td_new)
1696                         goto err;
1697
1698                 td_new->o.numjobs = 1;
1699                 td_new->o.stonewall = 0;
1700                 td_new->o.new_group = 0;
1701                 td_new->subjob_number = numjobs;
1702                 td_new->o.ss_dur = o->ss_dur * 1000000l;
1703                 td_new->o.ss_limit = o->ss_limit;
1704
1705                 if (file_alloced) {
1706                         if (td_new->files) {
1707                                 struct fio_file *f;
1708                                 for_each_file(td_new, f, i) {
1709                                         if (f->file_name)
1710                                                 sfree(f->file_name);
1711                                         sfree(f);
1712                                 }
1713                                 free(td_new->files);
1714                                 td_new->files = NULL;
1715                         }
1716                         td_new->files_index = 0;
1717                         td_new->files_size = 0;
1718                         if (td_new->o.filename) {
1719                                 free(td_new->o.filename);
1720                                 td_new->o.filename = NULL;
1721                         }
1722                 }
1723
1724                 if (add_job(td_new, jobname, numjobs, 1, client_type))
1725                         goto err;
1726         }
1727
1728         return 0;
1729 err:
1730         put_job(td);
1731         return -1;
1732 }
1733
1734 /*
1735  * Parse as if 'o' was a command line
1736  */
1737 void add_job_opts(const char **o, int client_type)
1738 {
1739         struct thread_data *td, *td_parent;
1740         int i, in_global = 1;
1741         char jobname[32];
1742
1743         i = 0;
1744         td_parent = td = NULL;
1745         while (o[i]) {
1746                 if (!strncmp(o[i], "name", 4)) {
1747                         in_global = 0;
1748                         if (td)
1749                                 add_job(td, jobname, 0, 0, client_type);
1750                         td = NULL;
1751                         sprintf(jobname, "%s", o[i] + 5);
1752                 }
1753                 if (in_global && !td_parent)
1754                         td_parent = get_new_job(true, &def_thread, false, jobname);
1755                 else if (!in_global && !td) {
1756                         if (!td_parent)
1757                                 td_parent = &def_thread;
1758                         td = get_new_job(false, td_parent, false, jobname);
1759                 }
1760                 if (in_global)
1761                         fio_options_parse(td_parent, (char **) &o[i], 1);
1762                 else
1763                         fio_options_parse(td, (char **) &o[i], 1);
1764                 i++;
1765         }
1766
1767         if (td)
1768                 add_job(td, jobname, 0, 0, client_type);
1769 }
1770
1771 static int skip_this_section(const char *name)
1772 {
1773         int i;
1774
1775         if (!nr_job_sections)
1776                 return 0;
1777         if (!strncmp(name, "global", 6))
1778                 return 0;
1779
1780         for (i = 0; i < nr_job_sections; i++)
1781                 if (!strcmp(job_sections[i], name))
1782                         return 0;
1783
1784         return 1;
1785 }
1786
1787 static int is_empty_or_comment(char *line)
1788 {
1789         unsigned int i;
1790
1791         for (i = 0; i < strlen(line); i++) {
1792                 if (line[i] == ';')
1793                         return 1;
1794                 if (line[i] == '#')
1795                         return 1;
1796                 if (!isspace((int) line[i]) && !iscntrl((int) line[i]))
1797                         return 0;
1798         }
1799
1800         return 1;
1801 }
1802
1803 /*
1804  * This is our [ini] type file parser.
1805  */
1806 static int __parse_jobs_ini(struct thread_data *td,
1807                 char *file, int is_buf, int stonewall_flag, int type,
1808                 int nested, char *name, char ***popts, int *aopts, int *nopts)
1809 {
1810         bool global = false;
1811         char *string;
1812         FILE *f;
1813         char *p;
1814         int ret = 0, stonewall;
1815         int first_sect = 1;
1816         int skip_fgets = 0;
1817         int inside_skip = 0;
1818         char **opts;
1819         int i, alloc_opts, num_opts;
1820
1821         dprint(FD_PARSE, "Parsing ini file %s\n", file);
1822         assert(td || !nested);
1823
1824         if (is_buf)
1825                 f = NULL;
1826         else {
1827                 if (!strcmp(file, "-"))
1828                         f = stdin;
1829                 else
1830                         f = fopen(file, "r");
1831
1832                 if (!f) {
1833                         int __err = errno;
1834
1835                         log_err("fio: unable to open '%s' job file\n", file);
1836                         if (td)
1837                                 td_verror(td, __err, "job file open");
1838                         return 1;
1839                 }
1840         }
1841
1842         string = malloc(4096);
1843
1844         /*
1845          * it's really 256 + small bit, 280 should suffice
1846          */
1847         if (!nested) {
1848                 name = malloc(280);
1849                 memset(name, 0, 280);
1850         }
1851
1852         opts = NULL;
1853         if (nested && popts) {
1854                 opts = *popts;
1855                 alloc_opts = *aopts;
1856                 num_opts = *nopts;
1857         }
1858
1859         if (!opts) {
1860                 alloc_opts = 8;
1861                 opts = malloc(sizeof(char *) * alloc_opts);
1862                 num_opts = 0;
1863         }
1864
1865         stonewall = stonewall_flag;
1866         do {
1867                 /*
1868                  * if skip_fgets is set, we already have loaded a line we
1869                  * haven't handled.
1870                  */
1871                 if (!skip_fgets) {
1872                         if (is_buf)
1873                                 p = strsep(&file, "\n");
1874                         else
1875                                 p = fgets(string, 4096, f);
1876                         if (!p)
1877                                 break;
1878                 }
1879
1880                 skip_fgets = 0;
1881                 strip_blank_front(&p);
1882                 strip_blank_end(p);
1883
1884                 dprint(FD_PARSE, "%s\n", p);
1885                 if (is_empty_or_comment(p))
1886                         continue;
1887
1888                 if (!nested) {
1889                         if (sscanf(p, "[%255[^\n]]", name) != 1) {
1890                                 if (inside_skip)
1891                                         continue;
1892
1893                                 log_err("fio: option <%s> outside of "
1894                                         "[] job section\n", p);
1895                                 ret = 1;
1896                                 break;
1897                         }
1898
1899                         name[strlen(name) - 1] = '\0';
1900
1901                         if (skip_this_section(name)) {
1902                                 inside_skip = 1;
1903                                 continue;
1904                         } else
1905                                 inside_skip = 0;
1906
1907                         dprint(FD_PARSE, "Parsing section [%s]\n", name);
1908
1909                         global = !strncmp(name, "global", 6);
1910
1911                         if (dump_cmdline) {
1912                                 if (first_sect)
1913                                         log_info("fio ");
1914                                 if (!global)
1915                                         log_info("--name=%s ", name);
1916                                 first_sect = 0;
1917                         }
1918
1919                         td = get_new_job(global, &def_thread, false, name);
1920                         if (!td) {
1921                                 ret = 1;
1922                                 break;
1923                         }
1924
1925                         /*
1926                          * Separate multiple job files by a stonewall
1927                          */
1928                         if (!global && stonewall) {
1929                                 td->o.stonewall = stonewall;
1930                                 stonewall = 0;
1931                         }
1932
1933                         num_opts = 0;
1934                         memset(opts, 0, alloc_opts * sizeof(char *));
1935                 }
1936                 else
1937                         skip_fgets = 1;
1938
1939                 while (1) {
1940                         if (!skip_fgets) {
1941                                 if (is_buf)
1942                                         p = strsep(&file, "\n");
1943                                 else
1944                                         p = fgets(string, 4096, f);
1945                                 if (!p)
1946                                         break;
1947                                 dprint(FD_PARSE, "%s", p);
1948                         }
1949                         else
1950                                 skip_fgets = 0;
1951
1952                         if (is_empty_or_comment(p))
1953                                 continue;
1954
1955                         strip_blank_front(&p);
1956
1957                         /*
1958                          * new section, break out and make sure we don't
1959                          * fgets() a new line at the top.
1960                          */
1961                         if (p[0] == '[') {
1962                                 if (nested) {
1963                                         log_err("No new sections in included files\n");
1964                                         ret = 1;
1965                                         goto out;
1966                                 }
1967
1968                                 skip_fgets = 1;
1969                                 break;
1970                         }
1971
1972                         strip_blank_end(p);
1973
1974                         if (!strncmp(p, "include", strlen("include"))) {
1975                                 char *filename = p + strlen("include") + 1,
1976                                         *ts, *full_fn = NULL;
1977
1978                                 /*
1979                                  * Allow for the include filename
1980                                  * specification to be relative.
1981                                  */
1982                                 if (access(filename, F_OK) &&
1983                                     (ts = strrchr(file, '/'))) {
1984                                         int len = ts - file +
1985                                                 strlen(filename) + 2;
1986
1987                                         if (!(full_fn = calloc(1, len))) {
1988                                                 ret = ENOMEM;
1989                                                 break;
1990                                         }
1991
1992                                         strncpy(full_fn,
1993                                                 file, (ts - file) + 1);
1994                                         strncpy(full_fn + (ts - file) + 1,
1995                                                 filename, strlen(filename));
1996                                         full_fn[len - 1] = 0;
1997                                         filename = full_fn;
1998                                 }
1999
2000                                 ret = __parse_jobs_ini(td, filename, is_buf,
2001                                                        stonewall_flag, type, 1,
2002                                                        name, &opts,
2003                                                        &alloc_opts, &num_opts);
2004
2005                                 if (ret) {
2006                                         log_err("Error %d while parsing "
2007                                                 "include file %s\n",
2008                                                 ret, filename);
2009                                 }
2010
2011                                 if (full_fn)
2012                                         free(full_fn);
2013
2014                                 if (ret)
2015                                         break;
2016
2017                                 continue;
2018                         }
2019
2020                         if (num_opts == alloc_opts) {
2021                                 alloc_opts <<= 1;
2022                                 opts = realloc(opts,
2023                                                 alloc_opts * sizeof(char *));
2024                         }
2025
2026                         opts[num_opts] = strdup(p);
2027                         num_opts++;
2028                 }
2029
2030                 if (nested) {
2031                         *popts = opts;
2032                         *aopts = alloc_opts;
2033                         *nopts = num_opts;
2034                         goto out;
2035                 }
2036
2037                 ret = fio_options_parse(td, opts, num_opts);
2038                 if (!ret) {
2039                         if (dump_cmdline)
2040                                 dump_opt_list(td);
2041
2042                         ret = add_job(td, name, 0, 0, type);
2043                 } else {
2044                         log_err("fio: job %s dropped\n", name);
2045                         put_job(td);
2046                 }
2047
2048                 for (i = 0; i < num_opts; i++)
2049                         free(opts[i]);
2050                 num_opts = 0;
2051         } while (!ret);
2052
2053         if (dump_cmdline)
2054                 log_info("\n");
2055
2056         i = 0;
2057         while (i < nr_job_sections) {
2058                 free(job_sections[i]);
2059                 i++;
2060         }
2061
2062         free(opts);
2063 out:
2064         free(string);
2065         if (!nested)
2066                 free(name);
2067         if (!is_buf && f != stdin)
2068                 fclose(f);
2069         return ret;
2070 }
2071
2072 int parse_jobs_ini(char *file, int is_buf, int stonewall_flag, int type)
2073 {
2074         return __parse_jobs_ini(NULL, file, is_buf, stonewall_flag, type,
2075                         0, NULL, NULL, NULL, NULL);
2076 }
2077
2078 static int fill_def_thread(void)
2079 {
2080         memset(&def_thread, 0, sizeof(def_thread));
2081         INIT_FLIST_HEAD(&def_thread.opt_list);
2082
2083         fio_getaffinity(getpid(), &def_thread.o.cpumask);
2084         def_thread.o.error_dump = 1;
2085
2086         /*
2087          * fill default options
2088          */
2089         fio_fill_default_options(&def_thread);
2090         return 0;
2091 }
2092
2093 static void show_debug_categories(void)
2094 {
2095 #ifdef FIO_INC_DEBUG
2096         const struct debug_level *dl = &debug_levels[0];
2097         int curlen, first = 1;
2098
2099         curlen = 0;
2100         while (dl->name) {
2101                 int has_next = (dl + 1)->name != NULL;
2102
2103                 if (first || curlen + strlen(dl->name) >= 80) {
2104                         if (!first) {
2105                                 printf("\n");
2106                                 curlen = 0;
2107                         }
2108                         curlen += printf("\t\t\t%s", dl->name);
2109                         curlen += 3 * (8 - 1);
2110                         if (has_next)
2111                                 curlen += printf(",");
2112                 } else {
2113                         curlen += printf("%s", dl->name);
2114                         if (has_next)
2115                                 curlen += printf(",");
2116                 }
2117                 dl++;
2118                 first = 0;
2119         }
2120         printf("\n");
2121 #endif
2122 }
2123
2124 /*
2125  * Following options aren't printed by usage().
2126  * --append-terse - Equivalent to --output-format=terse, see f6a7df53.
2127  * --latency-log - Deprecated option.
2128  */
2129 static void usage(const char *name)
2130 {
2131         printf("%s\n", fio_version_string);
2132         printf("%s [options] [job options] <job file(s)>\n", name);
2133         printf("  --debug=options\tEnable debug logging. May be one/more of:\n");
2134         show_debug_categories();
2135         printf("  --parse-only\t\tParse options only, don't start any IO\n");
2136         printf("  --output\t\tWrite output to file\n");
2137         printf("  --bandwidth-log\tGenerate aggregate bandwidth logs\n");
2138         printf("  --minimal\t\tMinimal (terse) output\n");
2139         printf("  --output-format=type\tOutput format (terse,json,json+,normal)\n");
2140         printf("  --terse-version=type\tSet terse version output format"
2141                 " (default 3, or 2 or 4)\n");
2142         printf("  --version\t\tPrint version info and exit\n");
2143         printf("  --help\t\tPrint this page\n");
2144         printf("  --cpuclock-test\tPerform test/validation of CPU clock\n");
2145         printf("  --crctest=[type]\tTest speed of checksum functions\n");
2146         printf("  --cmdhelp=cmd\t\tPrint command help, \"all\" for all of"
2147                 " them\n");
2148         printf("  --enghelp=engine\tPrint ioengine help, or list"
2149                 " available ioengines\n");
2150         printf("  --enghelp=engine,cmd\tPrint help for an ioengine"
2151                 " cmd\n");
2152         printf("  --showcmd\t\tTurn a job file into command line options\n");
2153         printf("  --eta=when\t\tWhen ETA estimate should be printed\n");
2154         printf("            \t\tMay be \"always\", \"never\" or \"auto\"\n");
2155         printf("  --eta-newline=time\tForce a new line for every 'time'");
2156         printf(" period passed\n");
2157         printf("  --status-interval=t\tForce full status dump every");
2158         printf(" 't' period passed\n");
2159         printf("  --readonly\t\tTurn on safety read-only checks, preventing"
2160                 " writes\n");
2161         printf("  --section=name\tOnly run specified section in job file,"
2162                 " multiple sections can be specified\n");
2163         printf("  --alloc-size=kb\tSet smalloc pool to this size in kb"
2164                 " (def 16384)\n");
2165         printf("  --warnings-fatal\tFio parser warnings are fatal\n");
2166         printf("  --max-jobs=nr\t\tMaximum number of threads/processes to support\n");
2167         printf("  --server=args\t\tStart a backend fio server\n");
2168         printf("  --daemonize=pidfile\tBackground fio server, write pid to file\n");
2169         printf("  --client=hostname\tTalk to remote backend(s) fio server at hostname\n");
2170         printf("  --remote-config=file\tTell fio server to load this local job file\n");
2171         printf("  --idle-prof=option\tReport cpu idleness on a system or percpu basis\n"
2172                 "\t\t\t(option=system,percpu) or run unit work\n"
2173                 "\t\t\tcalibration only (option=calibrate)\n");
2174 #ifdef CONFIG_ZLIB
2175         printf("  --inflate-log=log\tInflate and output compressed log\n");
2176 #endif
2177         printf("  --trigger-file=file\tExecute trigger cmd when file exists\n");
2178         printf("  --trigger-timeout=t\tExecute trigger at this time\n");
2179         printf("  --trigger=cmd\t\tSet this command as local trigger\n");
2180         printf("  --trigger-remote=cmd\tSet this command as remote trigger\n");
2181         printf("  --aux-path=path\tUse this path for fio state generated files\n");
2182         printf("\nFio was written by Jens Axboe <axboe@kernel.dk>\n");
2183 }
2184
2185 #ifdef FIO_INC_DEBUG
2186 const struct debug_level debug_levels[] = {
2187         { .name = "process",
2188           .help = "Process creation/exit logging",
2189           .shift = FD_PROCESS,
2190         },
2191         { .name = "file",
2192           .help = "File related action logging",
2193           .shift = FD_FILE,
2194         },
2195         { .name = "io",
2196           .help = "IO and IO engine action logging (offsets, queue, completions, etc)",
2197           .shift = FD_IO,
2198         },
2199         { .name = "mem",
2200           .help = "Memory allocation/freeing logging",
2201           .shift = FD_MEM,
2202         },
2203         { .name = "blktrace",
2204           .help = "blktrace action logging",
2205           .shift = FD_BLKTRACE,
2206         },
2207         { .name = "verify",
2208           .help = "IO verification action logging",
2209           .shift = FD_VERIFY,
2210         },
2211         { .name = "random",
2212           .help = "Random generation logging",
2213           .shift = FD_RANDOM,
2214         },
2215         { .name = "parse",
2216           .help = "Parser logging",
2217           .shift = FD_PARSE,
2218         },
2219         { .name = "diskutil",
2220           .help = "Disk utility logging actions",
2221           .shift = FD_DISKUTIL,
2222         },
2223         { .name = "job",
2224           .help = "Logging related to creating/destroying jobs",
2225           .shift = FD_JOB,
2226         },
2227         { .name = "mutex",
2228           .help = "Mutex logging",
2229           .shift = FD_MUTEX
2230         },
2231         { .name = "profile",
2232           .help = "Logging related to profiles",
2233           .shift = FD_PROFILE,
2234         },
2235         { .name = "time",
2236           .help = "Logging related to time keeping functions",
2237           .shift = FD_TIME,
2238         },
2239         { .name = "net",
2240           .help = "Network logging",
2241           .shift = FD_NET,
2242         },
2243         { .name = "rate",
2244           .help = "Rate logging",
2245           .shift = FD_RATE,
2246         },
2247         { .name = "compress",
2248           .help = "Log compression logging",
2249           .shift = FD_COMPRESS,
2250         },
2251         { .name = "steadystate",
2252           .help = "Steady state detection logging",
2253           .shift = FD_STEADYSTATE,
2254         },
2255         { .name = "helperthread",
2256           .help = "Helper thread logging",
2257           .shift = FD_HELPERTHREAD,
2258         },
2259         { .name = NULL, },
2260 };
2261
2262 static int set_debug(const char *string)
2263 {
2264         const struct debug_level *dl;
2265         char *p = (char *) string;
2266         char *opt;
2267         int i;
2268
2269         if (!string)
2270                 return 0;
2271
2272         if (!strcmp(string, "?") || !strcmp(string, "help")) {
2273                 log_info("fio: dumping debug options:");
2274                 for (i = 0; debug_levels[i].name; i++) {
2275                         dl = &debug_levels[i];
2276                         log_info("%s,", dl->name);
2277                 }
2278                 log_info("all\n");
2279                 return 1;
2280         }
2281
2282         while ((opt = strsep(&p, ",")) != NULL) {
2283                 int found = 0;
2284
2285                 if (!strncmp(opt, "all", 3)) {
2286                         log_info("fio: set all debug options\n");
2287                         fio_debug = ~0UL;
2288                         continue;
2289                 }
2290
2291                 for (i = 0; debug_levels[i].name; i++) {
2292                         dl = &debug_levels[i];
2293                         found = !strncmp(opt, dl->name, strlen(dl->name));
2294                         if (!found)
2295                                 continue;
2296
2297                         if (dl->shift == FD_JOB) {
2298                                 opt = strchr(opt, ':');
2299                                 if (!opt) {
2300                                         log_err("fio: missing job number\n");
2301                                         break;
2302                                 }
2303                                 opt++;
2304                                 fio_debug_jobno = atoi(opt);
2305                                 log_info("fio: set debug jobno %d\n",
2306                                                         fio_debug_jobno);
2307                         } else {
2308                                 log_info("fio: set debug option %s\n", opt);
2309                                 fio_debug |= (1UL << dl->shift);
2310                         }
2311                         break;
2312                 }
2313
2314                 if (!found)
2315                         log_err("fio: debug mask %s not found\n", opt);
2316         }
2317         return 0;
2318 }
2319 #else
2320 static int set_debug(const char *string)
2321 {
2322         log_err("fio: debug tracing not included in build\n");
2323         return 1;
2324 }
2325 #endif
2326
2327 static void fio_options_fill_optstring(void)
2328 {
2329         char *ostr = cmd_optstr;
2330         int i, c;
2331
2332         c = i = 0;
2333         while (l_opts[i].name) {
2334                 ostr[c++] = l_opts[i].val;
2335                 if (l_opts[i].has_arg == required_argument)
2336                         ostr[c++] = ':';
2337                 else if (l_opts[i].has_arg == optional_argument) {
2338                         ostr[c++] = ':';
2339                         ostr[c++] = ':';
2340                 }
2341                 i++;
2342         }
2343         ostr[c] = '\0';
2344 }
2345
2346 static int client_flag_set(char c)
2347 {
2348         int i;
2349
2350         i = 0;
2351         while (l_opts[i].name) {
2352                 int val = l_opts[i].val;
2353
2354                 if (c == (val & 0xff))
2355                         return (val & FIO_CLIENT_FLAG);
2356
2357                 i++;
2358         }
2359
2360         return 0;
2361 }
2362
2363 static void parse_cmd_client(void *client, char *opt)
2364 {
2365         fio_client_add_cmd_option(client, opt);
2366 }
2367
2368 static void show_closest_option(const char *name)
2369 {
2370         int best_option, best_distance;
2371         int i, distance;
2372
2373         while (*name == '-')
2374                 name++;
2375
2376         best_option = -1;
2377         best_distance = INT_MAX;
2378         i = 0;
2379         while (l_opts[i].name) {
2380                 distance = string_distance(name, l_opts[i].name);
2381                 if (distance < best_distance) {
2382                         best_distance = distance;
2383                         best_option = i;
2384                 }
2385                 i++;
2386         }
2387
2388         if (best_option != -1 && string_distance_ok(name, best_distance))
2389                 log_err("Did you mean %s?\n", l_opts[best_option].name);
2390 }
2391
2392 static int parse_output_format(const char *optarg)
2393 {
2394         char *p, *orig, *opt;
2395         int ret = 0;
2396
2397         p = orig = strdup(optarg);
2398
2399         output_format = 0;
2400
2401         while ((opt = strsep(&p, ",")) != NULL) {
2402                 if (!strcmp(opt, "minimal") ||
2403                     !strcmp(opt, "terse") ||
2404                     !strcmp(opt, "csv"))
2405                         output_format |= FIO_OUTPUT_TERSE;
2406                 else if (!strcmp(opt, "json"))
2407                         output_format |= FIO_OUTPUT_JSON;
2408                 else if (!strcmp(opt, "json+"))
2409                         output_format |= (FIO_OUTPUT_JSON | FIO_OUTPUT_JSON_PLUS);
2410                 else if (!strcmp(opt, "normal"))
2411                         output_format |= FIO_OUTPUT_NORMAL;
2412                 else {
2413                         log_err("fio: invalid output format %s\n", opt);
2414                         ret = 1;
2415                         break;
2416                 }
2417         }
2418
2419         free(orig);
2420         return ret;
2421 }
2422
2423 int parse_cmd_line(int argc, char *argv[], int client_type)
2424 {
2425         struct thread_data *td = NULL;
2426         int c, ini_idx = 0, lidx, ret = 0, do_exit = 0, exit_val = 0;
2427         char *ostr = cmd_optstr;
2428         char *pid_file = NULL;
2429         void *cur_client = NULL;
2430         int backend = 0;
2431
2432         /*
2433          * Reset optind handling, since we may call this multiple times
2434          * for the backend.
2435          */
2436         optind = 1;
2437
2438         while ((c = getopt_long_only(argc, argv, ostr, l_opts, &lidx)) != -1) {
2439                 if ((c & FIO_CLIENT_FLAG) || client_flag_set(c)) {
2440                         parse_cmd_client(cur_client, argv[optind - 1]);
2441                         c &= ~FIO_CLIENT_FLAG;
2442                 }
2443
2444                 switch (c) {
2445                 case 'a':
2446                         smalloc_pool_size = atoi(optarg);
2447                         smalloc_pool_size <<= 10;
2448                         sinit();
2449                         break;
2450                 case 'l':
2451                         log_err("fio: --latency-log is deprecated. Use per-job latency log options.\n");
2452                         do_exit++;
2453                         exit_val = 1;
2454                         break;
2455                 case 'b':
2456                         write_bw_log = 1;
2457                         break;
2458                 case 'o': {
2459                         FILE *tmp;
2460
2461                         if (f_out && f_out != stdout)
2462                                 fclose(f_out);
2463
2464                         tmp = fopen(optarg, "w+");
2465                         if (!tmp) {
2466                                 log_err("fio: output file open error: %s\n", strerror(errno));
2467                                 exit_val = 1;
2468                                 do_exit++;
2469                                 break;
2470                         }
2471                         f_err = f_out = tmp;
2472                         break;
2473                         }
2474                 case 'm':
2475                         output_format = FIO_OUTPUT_TERSE;
2476                         break;
2477                 case 'F':
2478                         if (parse_output_format(optarg)) {
2479                                 log_err("fio: failed parsing output-format\n");
2480                                 exit_val = 1;
2481                                 do_exit++;
2482                                 break;
2483                         }
2484                         break;
2485                 case 'f':
2486                         output_format |= FIO_OUTPUT_TERSE;
2487                         break;
2488                 case 'h':
2489                         did_arg = true;
2490                         if (!cur_client) {
2491                                 usage(argv[0]);
2492                                 do_exit++;
2493                         }
2494                         break;
2495                 case 'c':
2496                         did_arg = true;
2497                         if (!cur_client) {
2498                                 fio_show_option_help(optarg);
2499                                 do_exit++;
2500                         }
2501                         break;
2502                 case 'i':
2503                         did_arg = true;
2504                         if (!cur_client) {
2505                                 fio_show_ioengine_help(optarg);
2506                                 do_exit++;
2507                         }
2508                         break;
2509                 case 's':
2510                         did_arg = true;
2511                         dump_cmdline = 1;
2512                         break;
2513                 case 'r':
2514                         read_only = 1;
2515                         break;
2516                 case 'v':
2517                         did_arg = true;
2518                         if (!cur_client) {
2519                                 log_info("%s\n", fio_version_string);
2520                                 do_exit++;
2521                         }
2522                         break;
2523                 case 'V':
2524                         terse_version = atoi(optarg);
2525                         if (!(terse_version >= 2 && terse_version <= 5)) {
2526                                 log_err("fio: bad terse version format\n");
2527                                 exit_val = 1;
2528                                 do_exit++;
2529                         }
2530                         break;
2531                 case 'e':
2532                         if (!strcmp("always", optarg))
2533                                 eta_print = FIO_ETA_ALWAYS;
2534                         else if (!strcmp("never", optarg))
2535                                 eta_print = FIO_ETA_NEVER;
2536                         break;
2537                 case 'E': {
2538                         long long t = 0;
2539
2540                         if (check_str_time(optarg, &t, 1)) {
2541                                 log_err("fio: failed parsing eta time %s\n", optarg);
2542                                 exit_val = 1;
2543                                 do_exit++;
2544                                 break;
2545                         }
2546                         eta_new_line = t / 1000;
2547                         if (!eta_new_line) {
2548                                 log_err("fio: eta new line time too short\n");
2549                                 exit_val = 1;
2550                                 do_exit++;
2551                         }
2552                         break;
2553                         }
2554                 case 'O': {
2555                         long long t = 0;
2556
2557                         if (check_str_time(optarg, &t, 1)) {
2558                                 log_err("fio: failed parsing eta interval %s\n", optarg);
2559                                 exit_val = 1;
2560                                 do_exit++;
2561                                 break;
2562                         }
2563                         eta_interval_msec = t / 1000;
2564                         if (eta_interval_msec < DISK_UTIL_MSEC) {
2565                                 log_err("fio: eta interval time too short (%umsec min)\n", DISK_UTIL_MSEC);
2566                                 exit_val = 1;
2567                                 do_exit++;
2568                         }
2569                         break;
2570                         }
2571                 case 'd':
2572                         if (set_debug(optarg))
2573                                 do_exit++;
2574                         break;
2575                 case 'P':
2576                         did_arg = true;
2577                         parse_only = 1;
2578                         break;
2579                 case 'x': {
2580                         size_t new_size;
2581
2582                         if (!strcmp(optarg, "global")) {
2583                                 log_err("fio: can't use global as only "
2584                                         "section\n");
2585                                 do_exit++;
2586                                 exit_val = 1;
2587                                 break;
2588                         }
2589                         new_size = (nr_job_sections + 1) * sizeof(char *);
2590                         job_sections = realloc(job_sections, new_size);
2591                         job_sections[nr_job_sections] = strdup(optarg);
2592                         nr_job_sections++;
2593                         break;
2594                         }
2595 #ifdef CONFIG_ZLIB
2596                 case 'X':
2597                         exit_val = iolog_file_inflate(optarg);
2598                         did_arg = true;
2599                         do_exit++;
2600                         break;
2601 #endif
2602                 case 'p':
2603                         did_arg = true;
2604                         if (exec_profile)
2605                                 free(exec_profile);
2606                         exec_profile = strdup(optarg);
2607                         break;
2608                 case FIO_GETOPT_JOB: {
2609                         const char *opt = l_opts[lidx].name;
2610                         char *val = optarg;
2611
2612                         if (!strncmp(opt, "name", 4) && td) {
2613                                 ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
2614                                 if (ret)
2615                                         goto out_free;
2616                                 td = NULL;
2617                                 did_arg = true;
2618                         }
2619                         if (!td) {
2620                                 int is_section = !strncmp(opt, "name", 4);
2621                                 int global = 0;
2622
2623                                 if (!is_section || !strncmp(val, "global", 6))
2624                                         global = 1;
2625
2626                                 if (is_section && skip_this_section(val))
2627                                         continue;
2628
2629                                 td = get_new_job(global, &def_thread, true, NULL);
2630                                 if (!td || ioengine_load(td)) {
2631                                         if (td) {
2632                                                 put_job(td);
2633                                                 td = NULL;
2634                                         }
2635                                         do_exit++;
2636                                         exit_val = 1;
2637                                         break;
2638                                 }
2639                                 fio_options_set_ioengine_opts(l_opts, td);
2640                         }
2641
2642                         if ((!val || !strlen(val)) &&
2643                             l_opts[lidx].has_arg == required_argument) {
2644                                 log_err("fio: option %s requires an argument\n", opt);
2645                                 ret = 1;
2646                         } else
2647                                 ret = fio_cmd_option_parse(td, opt, val);
2648
2649                         if (ret) {
2650                                 if (td) {
2651                                         put_job(td);
2652                                         td = NULL;
2653                                 }
2654                                 do_exit++;
2655                                 exit_val = 1;
2656                         }
2657
2658                         if (!ret && !strcmp(opt, "ioengine")) {
2659                                 if (ioengine_load(td)) {
2660                                         put_job(td);
2661                                         td = NULL;
2662                                         do_exit++;
2663                                         exit_val = 1;
2664                                         break;
2665                                 }
2666                                 fio_options_set_ioengine_opts(l_opts, td);
2667                         }
2668                         break;
2669                 }
2670                 case FIO_GETOPT_IOENGINE: {
2671                         const char *opt = l_opts[lidx].name;
2672                         char *val = optarg;
2673
2674                         if (!td)
2675                                 break;
2676
2677                         ret = fio_cmd_ioengine_option_parse(td, opt, val);
2678                         break;
2679                 }
2680                 case 'w':
2681                         warnings_fatal = 1;
2682                         break;
2683                 case 'j':
2684                         max_jobs = atoi(optarg);
2685                         if (!max_jobs || max_jobs > REAL_MAX_JOBS) {
2686                                 log_err("fio: invalid max jobs: %d\n", max_jobs);
2687                                 do_exit++;
2688                                 exit_val = 1;
2689                         }
2690                         break;
2691                 case 'S':
2692                         did_arg = true;
2693 #ifndef CONFIG_NO_SHM
2694                         if (nr_clients) {
2695                                 log_err("fio: can't be both client and server\n");
2696                                 do_exit++;
2697                                 exit_val = 1;
2698                                 break;
2699                         }
2700                         if (optarg)
2701                                 fio_server_set_arg(optarg);
2702                         is_backend = 1;
2703                         backend = 1;
2704 #else
2705                         log_err("fio: client/server requires SHM support\n");
2706                         do_exit++;
2707                         exit_val = 1;
2708 #endif
2709                         break;
2710                 case 'D':
2711                         if (pid_file)
2712                                 free(pid_file);
2713                         pid_file = strdup(optarg);
2714                         break;
2715                 case 'I':
2716                         if ((ret = fio_idle_prof_parse_opt(optarg))) {
2717                                 /* exit on error and calibration only */
2718                                 did_arg = true;
2719                                 do_exit++;
2720                                 if (ret == -1)
2721                                         exit_val = 1;
2722                         }
2723                         break;
2724                 case 'C':
2725                         did_arg = true;
2726                         if (is_backend) {
2727                                 log_err("fio: can't be both client and server\n");
2728                                 do_exit++;
2729                                 exit_val = 1;
2730                                 break;
2731                         }
2732                         /* if --client parameter contains a pathname */
2733                         if (0 == access(optarg, R_OK)) {
2734                                 /* file contains a list of host addrs or names */
2735                                 char hostaddr[PATH_MAX] = {0};
2736                                 char formatstr[8];
2737                                 FILE * hostf = fopen(optarg, "r");
2738                                 if (!hostf) {
2739                                         log_err("fio: could not open client list file %s for read\n", optarg);
2740                                         do_exit++;
2741                                         exit_val = 1;
2742                                         break;
2743                                 }
2744                                 sprintf(formatstr, "%%%ds", PATH_MAX - 1);
2745                                 /*
2746                                  * read at most PATH_MAX-1 chars from each
2747                                  * record in this file
2748                                  */
2749                                 while (fscanf(hostf, formatstr, hostaddr) == 1) {
2750                                         /* expect EVERY host in file to be valid */
2751                                         if (fio_client_add(&fio_client_ops, hostaddr, &cur_client)) {
2752                                                 log_err("fio: failed adding client %s from file %s\n", hostaddr, optarg);
2753                                                 do_exit++;
2754                                                 exit_val = 1;
2755                                                 break;
2756                                         }
2757                                 }
2758                                 fclose(hostf);
2759                                 break; /* no possibility of job file for "this client only" */
2760                         }
2761                         if (fio_client_add(&fio_client_ops, optarg, &cur_client)) {
2762                                 log_err("fio: failed adding client %s\n", optarg);
2763                                 do_exit++;
2764                                 exit_val = 1;
2765                                 break;
2766                         }
2767                         /*
2768                          * If the next argument exists and isn't an option,
2769                          * assume it's a job file for this client only.
2770                          */
2771                         while (optind < argc) {
2772                                 if (!strncmp(argv[optind], "--", 2) ||
2773                                     !strncmp(argv[optind], "-", 1))
2774                                         break;
2775
2776                                 if (fio_client_add_ini_file(cur_client, argv[optind], false))
2777                                         break;
2778                                 optind++;
2779                         }
2780                         break;
2781                 case 'R':
2782                         did_arg = true;
2783                         if (fio_client_add_ini_file(cur_client, optarg, true)) {
2784                                 do_exit++;
2785                                 exit_val = 1;
2786                         }
2787                         break;
2788                 case 'T':
2789                         did_arg = true;
2790                         do_exit++;
2791                         exit_val = fio_monotonic_clocktest(1);
2792                         break;
2793                 case 'G':
2794                         did_arg = true;
2795                         do_exit++;
2796                         exit_val = fio_crctest(optarg);
2797                         break;
2798                 case 'M':
2799                         did_arg = true;
2800                         do_exit++;
2801                         exit_val = fio_memcpy_test(optarg);
2802                         break;
2803                 case 'L': {
2804                         long long val;
2805
2806                         if (check_str_time(optarg, &val, 1)) {
2807                                 log_err("fio: failed parsing time %s\n", optarg);
2808                                 do_exit++;
2809                                 exit_val = 1;
2810                                 break;
2811                         }
2812                         if (val < 1000) {
2813                                 log_err("fio: status interval too small\n");
2814                                 do_exit++;
2815                                 exit_val = 1;
2816                         }
2817                         status_interval = val / 1000;
2818                         break;
2819                         }
2820                 case 'W':
2821                         if (trigger_file)
2822                                 free(trigger_file);
2823                         trigger_file = strdup(optarg);
2824                         break;
2825                 case 'H':
2826                         if (trigger_cmd)
2827                                 free(trigger_cmd);
2828                         trigger_cmd = strdup(optarg);
2829                         break;
2830                 case 'J':
2831                         if (trigger_remote_cmd)
2832                                 free(trigger_remote_cmd);
2833                         trigger_remote_cmd = strdup(optarg);
2834                         break;
2835                 case 'K':
2836                         if (aux_path)
2837                                 free(aux_path);
2838                         aux_path = strdup(optarg);
2839                         break;
2840                 case 'B':
2841                         if (check_str_time(optarg, &trigger_timeout, 1)) {
2842                                 log_err("fio: failed parsing time %s\n", optarg);
2843                                 do_exit++;
2844                                 exit_val = 1;
2845                         }
2846                         trigger_timeout /= 1000000;
2847                         break;
2848                 case '?':
2849                         log_err("%s: unrecognized option '%s'\n", argv[0],
2850                                                         argv[optind - 1]);
2851                         show_closest_option(argv[optind - 1]);
2852                 default:
2853                         do_exit++;
2854                         exit_val = 1;
2855                         break;
2856                 }
2857                 if (do_exit)
2858                         break;
2859         }
2860
2861         if (do_exit && !(is_backend || nr_clients))
2862                 exit(exit_val);
2863
2864         if (nr_clients && fio_clients_connect())
2865                 exit(1);
2866
2867         if (is_backend && backend)
2868                 return fio_start_server(pid_file);
2869         else if (pid_file)
2870                 free(pid_file);
2871
2872         if (td) {
2873                 if (!ret) {
2874                         ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
2875                         if (ret)
2876                                 exit(1);
2877                 }
2878         }
2879
2880         while (!ret && optind < argc) {
2881                 ini_idx++;
2882                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
2883                 ini_file[ini_idx - 1] = strdup(argv[optind]);
2884                 optind++;
2885         }
2886
2887 out_free:
2888         return ini_idx;
2889 }
2890
2891 int fio_init_options(void)
2892 {
2893         f_out = stdout;
2894         f_err = stderr;
2895
2896         fio_options_fill_optstring();
2897         fio_options_dup_and_init(l_opts);
2898
2899         atexit(free_shm);
2900
2901         if (fill_def_thread())
2902                 return 1;
2903
2904         return 0;
2905 }
2906
2907 extern int fio_check_options(struct thread_options *);
2908
2909 int parse_options(int argc, char *argv[])
2910 {
2911         const int type = FIO_CLIENT_TYPE_CLI;
2912         int job_files, i;
2913
2914         if (fio_init_options())
2915                 return 1;
2916         if (fio_test_cconv(&def_thread.o))
2917                 log_err("fio: failed internal cconv test\n");
2918
2919         job_files = parse_cmd_line(argc, argv, type);
2920
2921         if (job_files > 0) {
2922                 for (i = 0; i < job_files; i++) {
2923                         if (i && fill_def_thread())
2924                                 return 1;
2925                         if (nr_clients) {
2926                                 if (fio_clients_send_ini(ini_file[i]))
2927                                         return 1;
2928                                 free(ini_file[i]);
2929                         } else if (!is_backend) {
2930                                 if (parse_jobs_ini(ini_file[i], 0, i, type))
2931                                         return 1;
2932                                 free(ini_file[i]);
2933                         }
2934                 }
2935         } else if (nr_clients) {
2936                 if (fill_def_thread())
2937                         return 1;
2938                 if (fio_clients_send_ini(NULL))
2939                         return 1;
2940         }
2941
2942         free(ini_file);
2943         fio_options_free(&def_thread);
2944         filesetup_mem_free();
2945
2946         if (!thread_number) {
2947                 if (parse_dryrun())
2948                         return 0;
2949                 if (exec_profile)
2950                         return 0;
2951                 if (is_backend || nr_clients)
2952                         return 0;
2953                 if (did_arg)
2954                         return 0;
2955
2956                 log_err("No job(s) defined\n\n");
2957                 usage(argv[0]);
2958                 return 1;
2959         }
2960
2961         if (output_format & FIO_OUTPUT_NORMAL)
2962                 log_info("%s\n", fio_version_string);
2963
2964         return 0;
2965 }
2966
2967 void options_default_fill(struct thread_options *o)
2968 {
2969         memcpy(o, &def_thread.o, sizeof(*o));
2970 }
2971
2972 struct thread_data *get_global_options(void)
2973 {
2974         return &def_thread;
2975 }