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