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