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