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