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