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