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