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