Ensure we inherit global latency/bw log settings
[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
28 #include "lib/getopt.h"
29 #include "lib/strcasestr.h"
30
31 const char fio_version_string[] = FIO_VERSION;
32
33 #define FIO_RANDSEED            (0xb1899bedUL)
34
35 static char **ini_file;
36 static int max_jobs = FIO_MAX_JOBS;
37 static int dump_cmdline;
38 static int def_timeout;
39 static int parse_only;
40
41 static struct thread_data def_thread;
42 struct thread_data *threads = NULL;
43
44 int exitall_on_terminate = 0;
45 int output_format = FIO_OUTPUT_NORMAL;
46 int append_terse_output = 0;
47 int eta_print = FIO_ETA_AUTO;
48 int eta_new_line = 0;
49 FILE *f_out = NULL;
50 FILE *f_err = NULL;
51 char **job_sections = NULL;
52 int nr_job_sections = 0;
53 char *exec_profile = NULL;
54 int warnings_fatal = 0;
55 int terse_version = 3;
56 int is_backend = 0;
57 int nr_clients = 0;
58 int log_syslog = 0;
59
60 int write_bw_log = 0;
61 int read_only = 0;
62 int status_interval = 0;
63
64 static int write_lat_log;
65
66 static int prev_group_jobs;
67
68 unsigned long fio_debug = 0;
69 unsigned int fio_debug_jobno = -1;
70 unsigned int *fio_debug_jobp = NULL;
71
72 static char cmd_optstr[256];
73 static int did_arg;
74
75 #define FIO_CLIENT_FLAG         (1 << 16)
76
77 /*
78  * Command line options. These will contain the above, plus a few
79  * extra that only pertain to fio itself and not jobs.
80  */
81 static struct option l_opts[FIO_NR_OPTIONS] = {
82         {
83                 .name           = (char *) "output",
84                 .has_arg        = required_argument,
85                 .val            = 'o' | FIO_CLIENT_FLAG,
86         },
87         {
88                 .name           = (char *) "timeout",
89                 .has_arg        = required_argument,
90                 .val            = 't' | FIO_CLIENT_FLAG,
91         },
92         {
93                 .name           = (char *) "latency-log",
94                 .has_arg        = required_argument,
95                 .val            = 'l' | FIO_CLIENT_FLAG,
96         },
97         {
98                 .name           = (char *) "bandwidth-log",
99                 .has_arg        = required_argument,
100                 .val            = 'b' | FIO_CLIENT_FLAG,
101         },
102         {
103                 .name           = (char *) "minimal",
104                 .has_arg        = no_argument,
105                 .val            = 'm' | FIO_CLIENT_FLAG,
106         },
107         {
108                 .name           = (char *) "output-format",
109                 .has_arg        = optional_argument,
110                 .val            = 'F' | FIO_CLIENT_FLAG,
111         },
112         {
113                 .name           = (char *) "append-terse",
114                 .has_arg        = optional_argument,
115                 .val            = 'f',
116         },
117         {
118                 .name           = (char *) "version",
119                 .has_arg        = no_argument,
120                 .val            = 'v' | FIO_CLIENT_FLAG,
121         },
122         {
123                 .name           = (char *) "help",
124                 .has_arg        = no_argument,
125                 .val            = 'h' | FIO_CLIENT_FLAG,
126         },
127         {
128                 .name           = (char *) "cmdhelp",
129                 .has_arg        = optional_argument,
130                 .val            = 'c' | FIO_CLIENT_FLAG,
131         },
132         {
133                 .name           = (char *) "enghelp",
134                 .has_arg        = optional_argument,
135                 .val            = 'i' | FIO_CLIENT_FLAG,
136         },
137         {
138                 .name           = (char *) "showcmd",
139                 .has_arg        = no_argument,
140                 .val            = 's' | FIO_CLIENT_FLAG,
141         },
142         {
143                 .name           = (char *) "readonly",
144                 .has_arg        = no_argument,
145                 .val            = 'r' | FIO_CLIENT_FLAG,
146         },
147         {
148                 .name           = (char *) "eta",
149                 .has_arg        = required_argument,
150                 .val            = 'e' | FIO_CLIENT_FLAG,
151         },
152         {
153                 .name           = (char *) "eta-newline",
154                 .has_arg        = required_argument,
155                 .val            = 'E' | FIO_CLIENT_FLAG,
156         },
157         {
158                 .name           = (char *) "debug",
159                 .has_arg        = required_argument,
160                 .val            = 'd' | FIO_CLIENT_FLAG,
161         },
162         {
163                 .name           = (char *) "parse-only",
164                 .has_arg        = no_argument,
165                 .val            = 'P' | FIO_CLIENT_FLAG,
166         },
167         {
168                 .name           = (char *) "section",
169                 .has_arg        = required_argument,
170                 .val            = 'x' | FIO_CLIENT_FLAG,
171         },
172         {
173                 .name           = (char *) "alloc-size",
174                 .has_arg        = required_argument,
175                 .val            = 'a' | FIO_CLIENT_FLAG,
176         },
177         {
178                 .name           = (char *) "profile",
179                 .has_arg        = required_argument,
180                 .val            = 'p' | FIO_CLIENT_FLAG,
181         },
182         {
183                 .name           = (char *) "warnings-fatal",
184                 .has_arg        = no_argument,
185                 .val            = 'w' | FIO_CLIENT_FLAG,
186         },
187         {
188                 .name           = (char *) "max-jobs",
189                 .has_arg        = required_argument,
190                 .val            = 'j' | FIO_CLIENT_FLAG,
191         },
192         {
193                 .name           = (char *) "terse-version",
194                 .has_arg        = required_argument,
195                 .val            = 'V' | FIO_CLIENT_FLAG,
196         },
197         {
198                 .name           = (char *) "server",
199                 .has_arg        = optional_argument,
200                 .val            = 'S',
201         },
202         {       .name           = (char *) "daemonize",
203                 .has_arg        = required_argument,
204                 .val            = 'D',
205         },
206         {
207                 .name           = (char *) "client",
208                 .has_arg        = required_argument,
209                 .val            = 'C',
210         },
211         {
212                 .name           = (char *) "cpuclock-test",
213                 .has_arg        = no_argument,
214                 .val            = 'T',
215         },
216         {
217                 .name           = (char *) "crctest",
218                 .has_arg        = optional_argument,
219                 .val            = 'G',
220         },
221         {
222                 .name           = (char *) "idle-prof",
223                 .has_arg        = required_argument,
224                 .val            = 'I',
225         },
226         {
227                 .name           = (char *) "status-interval",
228                 .has_arg        = required_argument,
229                 .val            = 'L',
230         },
231         {
232                 .name           = NULL,
233         },
234 };
235
236 void free_threads_shm(void)
237 {
238         struct shmid_ds sbuf;
239
240         if (threads) {
241                 void *tp = threads;
242
243                 threads = NULL;
244                 shmdt(tp);
245                 shmctl(shm_id, IPC_RMID, &sbuf);
246                 shm_id = -1;
247         }
248 }
249
250 void free_shm(void)
251 {
252         if (threads) {
253                 file_hash_exit();
254                 flow_exit();
255                 fio_debug_jobp = NULL;
256                 free_threads_shm();
257         }
258
259         options_free(fio_options, &def_thread);
260         scleanup();
261 }
262
263 /*
264  * The thread area is shared between the main process and the job
265  * threads/processes. So setup a shared memory segment that will hold
266  * all the job info. We use the end of the region for keeping track of
267  * open files across jobs, for file sharing.
268  */
269 static int setup_thread_area(void)
270 {
271         void *hash;
272
273         if (threads)
274                 return 0;
275
276         /*
277          * 1024 is too much on some machines, scale max_jobs if
278          * we get a failure that looks like too large a shm segment
279          */
280         do {
281                 size_t size = max_jobs * sizeof(struct thread_data);
282
283                 size += file_hash_size;
284                 size += sizeof(unsigned int);
285
286                 shm_id = shmget(0, size, IPC_CREAT | 0600);
287                 if (shm_id != -1)
288                         break;
289                 if (errno != EINVAL && errno != ENOMEM && errno != ENOSPC) {
290                         perror("shmget");
291                         break;
292                 }
293
294                 max_jobs >>= 1;
295         } while (max_jobs);
296
297         if (shm_id == -1)
298                 return 1;
299
300         threads = shmat(shm_id, NULL, 0);
301         if (threads == (void *) -1) {
302                 perror("shmat");
303                 return 1;
304         }
305
306         memset(threads, 0, max_jobs * sizeof(struct thread_data));
307         hash = (void *) threads + max_jobs * sizeof(struct thread_data);
308         fio_debug_jobp = (void *) hash + file_hash_size;
309         *fio_debug_jobp = -1;
310         file_hash_init(hash);
311
312         flow_init();
313
314         return 0;
315 }
316
317 /*
318  * Return a free job structure.
319  */
320 static struct thread_data *get_new_job(int global, struct thread_data *parent,
321                                        int preserve_eo)
322 {
323         struct thread_data *td;
324
325         if (global)
326                 return &def_thread;
327         if (setup_thread_area()) {
328                 log_err("error: failed to setup shm segment\n");
329                 return NULL;
330         }
331         if (thread_number >= max_jobs) {
332                 log_err("error: maximum number of jobs (%d) reached.\n",
333                                 max_jobs);
334                 return NULL;
335         }
336
337         td = &threads[thread_number++];
338         *td = *parent;
339
340         td->io_ops = NULL;
341         if (!preserve_eo)
342                 td->eo = NULL;
343
344         td->o.uid = td->o.gid = -1U;
345
346         dup_files(td, parent);
347         fio_options_mem_dupe(td);
348
349         profile_add_hooks(td);
350
351         td->thread_number = thread_number;
352
353         if (!parent || !parent->o.group_reporting)
354                 stat_number++;
355
356         return td;
357 }
358
359 static void put_job(struct thread_data *td)
360 {
361         if (td == &def_thread)
362                 return;
363
364         profile_td_exit(td);
365         flow_exit_job(td);
366
367         if (td->error)
368                 log_info("fio: %s\n", td->verror);
369
370         fio_options_free(td);
371         if (td->io_ops)
372                 free_ioengine(td);
373
374         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
375         thread_number--;
376 }
377
378 static int __setup_rate(struct thread_data *td, enum fio_ddir ddir)
379 {
380         unsigned int bs = td->o.min_bs[ddir];
381
382         assert(ddir_rw(ddir));
383
384         if (td->o.rate[ddir])
385                 td->rate_bps[ddir] = td->o.rate[ddir];
386         else
387                 td->rate_bps[ddir] = td->o.rate_iops[ddir] * bs;
388
389         if (!td->rate_bps[ddir]) {
390                 log_err("rate lower than supported\n");
391                 return -1;
392         }
393
394         td->rate_pending_usleep[ddir] = 0;
395         return 0;
396 }
397
398 static int setup_rate(struct thread_data *td)
399 {
400         int ret = 0;
401
402         if (td->o.rate[DDIR_READ] || td->o.rate_iops[DDIR_READ])
403                 ret = __setup_rate(td, DDIR_READ);
404         if (td->o.rate[DDIR_WRITE] || td->o.rate_iops[DDIR_WRITE])
405                 ret |= __setup_rate(td, DDIR_WRITE);
406         if (td->o.rate[DDIR_TRIM] || td->o.rate_iops[DDIR_TRIM])
407                 ret |= __setup_rate(td, DDIR_TRIM);
408
409         return ret;
410 }
411
412 static int fixed_block_size(struct thread_options *o)
413 {
414         return o->min_bs[DDIR_READ] == o->max_bs[DDIR_READ] &&
415                 o->min_bs[DDIR_WRITE] == o->max_bs[DDIR_WRITE] &&
416                 o->min_bs[DDIR_TRIM] == o->max_bs[DDIR_TRIM] &&
417                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_WRITE] &&
418                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_TRIM];
419 }
420
421
422 static unsigned long long get_rand_start_delay(struct thread_data *td)
423 {
424         unsigned long long delayrange;
425         unsigned long r;
426
427         delayrange = td->o.start_delay_high - td->o.start_delay;
428
429         if (td->o.use_os_rand) {
430                 r = os_random_long(&td->delay_state);
431                 delayrange = (unsigned long long) ((double) delayrange * (r / (OS_RAND_MAX + 1.0)));
432         } else {
433                 r = __rand(&td->__delay_state);
434                 delayrange = (unsigned long long) ((double) delayrange * (r / (FRAND_MAX + 1.0)));
435         }
436
437         delayrange += td->o.start_delay;
438         return delayrange;
439 }
440
441 /*
442  * Lazy way of fixing up options that depend on each other. We could also
443  * define option callback handlers, but this is easier.
444  */
445 static int fixup_options(struct thread_data *td)
446 {
447         struct thread_options *o = &td->o;
448         int ret = 0;
449
450 #ifndef FIO_HAVE_PSHARED_MUTEX
451         if (!o->use_thread) {
452                 log_info("fio: this platform does not support process shared"
453                          " mutexes, forcing use of threads. Use the 'thread'"
454                          " option to get rid of this warning.\n");
455                 o->use_thread = 1;
456                 ret = warnings_fatal;
457         }
458 #endif
459
460         if (o->write_iolog_file && o->read_iolog_file) {
461                 log_err("fio: read iolog overrides write_iolog\n");
462                 free(o->write_iolog_file);
463                 o->write_iolog_file = NULL;
464                 ret = warnings_fatal;
465         }
466
467         /*
468          * only really works with 1 file
469          */
470         if (o->zone_size && o->open_files > 1)
471                 o->zone_size = 0;
472
473         /*
474          * If zone_range isn't specified, backward compatibility dictates it
475          * should be made equal to zone_size.
476          */
477         if (o->zone_size && !o->zone_range)
478                 o->zone_range = o->zone_size;
479
480         /*
481          * Reads can do overwrites, we always need to pre-create the file
482          */
483         if (td_read(td) || td_rw(td))
484                 o->overwrite = 1;
485
486         if (!o->min_bs[DDIR_READ])
487                 o->min_bs[DDIR_READ] = o->bs[DDIR_READ];
488         if (!o->max_bs[DDIR_READ])
489                 o->max_bs[DDIR_READ] = o->bs[DDIR_READ];
490         if (!o->min_bs[DDIR_WRITE])
491                 o->min_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
492         if (!o->max_bs[DDIR_WRITE])
493                 o->max_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
494         if (!o->min_bs[DDIR_TRIM])
495                 o->min_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
496         if (!o->max_bs[DDIR_TRIM])
497                 o->max_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
498
499
500         o->rw_min_bs = min(o->min_bs[DDIR_READ], o->min_bs[DDIR_WRITE]);
501         o->rw_min_bs = min(o->min_bs[DDIR_TRIM], o->rw_min_bs);
502
503         /*
504          * For random IO, allow blockalign offset other than min_bs.
505          */
506         if (!o->ba[DDIR_READ] || !td_random(td))
507                 o->ba[DDIR_READ] = o->min_bs[DDIR_READ];
508         if (!o->ba[DDIR_WRITE] || !td_random(td))
509                 o->ba[DDIR_WRITE] = o->min_bs[DDIR_WRITE];
510         if (!o->ba[DDIR_TRIM] || !td_random(td))
511                 o->ba[DDIR_TRIM] = o->min_bs[DDIR_TRIM];
512
513         if ((o->ba[DDIR_READ] != o->min_bs[DDIR_READ] ||
514             o->ba[DDIR_WRITE] != o->min_bs[DDIR_WRITE] ||
515             o->ba[DDIR_TRIM] != o->min_bs[DDIR_TRIM]) &&
516             !o->norandommap) {
517                 log_err("fio: Any use of blockalign= turns off randommap\n");
518                 o->norandommap = 1;
519                 ret = warnings_fatal;
520         }
521
522         if (!o->file_size_high)
523                 o->file_size_high = o->file_size_low;
524
525         if (o->start_delay_high)
526                 o->start_delay = get_rand_start_delay(td);
527
528         if (o->norandommap && o->verify != VERIFY_NONE
529             && !fixed_block_size(o))  {
530                 log_err("fio: norandommap given for variable block sizes, "
531                         "verify disabled\n");
532                 o->verify = VERIFY_NONE;
533                 ret = warnings_fatal;
534         }
535         if (o->bs_unaligned && (o->odirect || td->io_ops->flags & FIO_RAWIO))
536                 log_err("fio: bs_unaligned may not work with raw io\n");
537
538         /*
539          * thinktime_spin must be less than thinktime
540          */
541         if (o->thinktime_spin > o->thinktime)
542                 o->thinktime_spin = o->thinktime;
543
544         /*
545          * The low water mark cannot be bigger than the iodepth
546          */
547         if (o->iodepth_low > o->iodepth || !o->iodepth_low)
548                 o->iodepth_low = o->iodepth;
549
550         /*
551          * If batch number isn't set, default to the same as iodepth
552          */
553         if (o->iodepth_batch > o->iodepth || !o->iodepth_batch)
554                 o->iodepth_batch = o->iodepth;
555
556         if (o->nr_files > td->files_index)
557                 o->nr_files = td->files_index;
558
559         if (o->open_files > o->nr_files || !o->open_files)
560                 o->open_files = o->nr_files;
561
562         if (((o->rate[DDIR_READ] + o->rate[DDIR_WRITE] + o->rate[DDIR_TRIM]) &&
563             (o->rate_iops[DDIR_READ] + o->rate_iops[DDIR_WRITE] + o->rate_iops[DDIR_TRIM])) ||
564             ((o->ratemin[DDIR_READ] + o->ratemin[DDIR_WRITE] + o->ratemin[DDIR_TRIM]) &&
565             (o->rate_iops_min[DDIR_READ] + o->rate_iops_min[DDIR_WRITE] + o->rate_iops_min[DDIR_TRIM]))) {
566                 log_err("fio: rate and rate_iops are mutually exclusive\n");
567                 ret = 1;
568         }
569         if ((o->rate[DDIR_READ] < o->ratemin[DDIR_READ]) ||
570             (o->rate[DDIR_WRITE] < o->ratemin[DDIR_WRITE]) ||
571             (o->rate[DDIR_TRIM] < o->ratemin[DDIR_TRIM]) ||
572             (o->rate_iops[DDIR_READ] < o->rate_iops_min[DDIR_READ]) ||
573             (o->rate_iops[DDIR_WRITE] < o->rate_iops_min[DDIR_WRITE]) ||
574             (o->rate_iops[DDIR_TRIM] < o->rate_iops_min[DDIR_TRIM])) {
575                 log_err("fio: minimum rate exceeds rate\n");
576                 ret = 1;
577         }
578
579         if (!o->timeout && o->time_based) {
580                 log_err("fio: time_based requires a runtime/timeout setting\n");
581                 o->time_based = 0;
582                 ret = warnings_fatal;
583         }
584
585         if (o->fill_device && !o->size)
586                 o->size = -1ULL;
587
588         if (o->verify != VERIFY_NONE) {
589                 if (td_write(td) && o->do_verify && o->numjobs > 1) {
590                         log_info("Multiple writers may overwrite blocks that "
591                                 "belong to other jobs. This can cause "
592                                 "verification failures.\n");
593                         ret = warnings_fatal;
594                 }
595
596                 o->refill_buffers = 1;
597                 if (o->max_bs[DDIR_WRITE] != o->min_bs[DDIR_WRITE] &&
598                     !o->verify_interval)
599                         o->verify_interval = o->min_bs[DDIR_WRITE];
600         }
601
602         if (o->pre_read) {
603                 o->invalidate_cache = 0;
604                 if (td->io_ops->flags & FIO_PIPEIO) {
605                         log_info("fio: cannot pre-read files with an IO engine"
606                                  " that isn't seekable. Pre-read disabled.\n");
607                         ret = warnings_fatal;
608                 }
609         }
610
611         if (!o->unit_base) {
612                 if (td->io_ops->flags & FIO_BIT_BASED)
613                         o->unit_base = 1;
614                 else
615                         o->unit_base = 8;
616         }
617
618 #ifndef CONFIG_FDATASYNC
619         if (o->fdatasync_blocks) {
620                 log_info("fio: this platform does not support fdatasync()"
621                          " falling back to using fsync().  Use the 'fsync'"
622                          " option instead of 'fdatasync' to get rid of"
623                          " this warning\n");
624                 o->fsync_blocks = o->fdatasync_blocks;
625                 o->fdatasync_blocks = 0;
626                 ret = warnings_fatal;
627         }
628 #endif
629
630 #ifdef WIN32
631         /*
632          * Windows doesn't support O_DIRECT or O_SYNC with the _open interface,
633          * so fail if we're passed those flags
634          */
635         if ((td->io_ops->flags & FIO_SYNCIO) && (td->o.odirect || td->o.sync_io)) {
636                 log_err("fio: Windows does not support direct or non-buffered io with"
637                                 " the synchronous ioengines. Use the 'windowsaio' ioengine"
638                                 " with 'direct=1' and 'iodepth=1' instead.\n");
639                 ret = 1;
640         }
641 #endif
642
643         /*
644          * For fully compressible data, just zero them at init time.
645          * It's faster than repeatedly filling it.
646          */
647         if (td->o.compress_percentage == 100) {
648                 td->o.zero_buffers = 1;
649                 td->o.compress_percentage = 0;
650         }
651
652         /*
653          * Using a non-uniform random distribution excludes usage of
654          * a random map
655          */
656         if (td->o.random_distribution != FIO_RAND_DIST_RANDOM)
657                 td->o.norandommap = 1;
658
659         /*
660          * If size is set but less than the min block size, complain
661          */
662         if (o->size && o->size < td_min_bs(td)) {
663                 log_err("fio: size too small, must be larger than the IO size: %llu\n", (unsigned long long) o->size);
664                 ret = 1;
665         }
666
667         /*
668          * O_ATOMIC implies O_DIRECT
669          */
670         if (td->o.oatomic)
671                 td->o.odirect = 1;
672
673         /*
674          * If randseed is set, that overrides randrepeat
675          */
676         if (td->o.rand_seed)
677                 td->o.rand_repeatable = 0;
678
679         if ((td->io_ops->flags & FIO_NOEXTEND) && td->o.file_append) {
680                 log_err("fio: can't append/extent with IO engine %s\n", td->io_ops->name);
681                 ret = 1;
682         }
683
684         return ret;
685 }
686
687 /*
688  * This function leaks the buffer
689  */
690 char *fio_uint_to_kmg(unsigned int val)
691 {
692         char *buf = malloc(32);
693         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
694         char *p = post;
695
696         do {
697                 if (val & 1023)
698                         break;
699
700                 val >>= 10;
701                 p++;
702         } while (*p);
703
704         snprintf(buf, 32, "%u%c", val, *p);
705         return buf;
706 }
707
708 /* External engines are specified by "external:name.o") */
709 static const char *get_engine_name(const char *str)
710 {
711         char *p = strstr(str, ":");
712
713         if (!p)
714                 return str;
715
716         p++;
717         strip_blank_front(&p);
718         strip_blank_end(p);
719         return p;
720 }
721
722 static int exists_and_not_file(const char *filename)
723 {
724         struct stat sb;
725
726         if (lstat(filename, &sb) == -1)
727                 return 0;
728
729         /* \\.\ is the device namespace in Windows, where every file
730          * is a device node */
731         if (S_ISREG(sb.st_mode) && strncmp(filename, "\\\\.\\", 4) != 0)
732                 return 0;
733
734         return 1;
735 }
736
737 static void td_fill_rand_seeds_os(struct thread_data *td)
738 {
739         os_random_seed(td->rand_seeds[FIO_RAND_BS_OFF], &td->bsrange_state);
740         os_random_seed(td->rand_seeds[FIO_RAND_VER_OFF], &td->verify_state);
741         os_random_seed(td->rand_seeds[FIO_RAND_MIX_OFF], &td->rwmix_state);
742
743         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
744                 os_random_seed(td->rand_seeds[FIO_RAND_FILE_OFF], &td->next_file_state);
745
746         os_random_seed(td->rand_seeds[FIO_RAND_FILE_SIZE_OFF], &td->file_size_state);
747         os_random_seed(td->rand_seeds[FIO_RAND_TRIM_OFF], &td->trim_state);
748         os_random_seed(td->rand_seeds[FIO_RAND_START_DELAY], &td->delay_state);
749
750         if (!td_random(td))
751                 return;
752
753         if (td->o.rand_repeatable)
754                 td->rand_seeds[FIO_RAND_BLOCK_OFF] = FIO_RANDSEED * td->thread_number;
755
756         os_random_seed(td->rand_seeds[FIO_RAND_BLOCK_OFF], &td->random_state);
757
758         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_READ_OFF], &td->seq_rand_state[DDIR_READ]);
759         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_WRITE_OFF], &td->seq_rand_state[DDIR_WRITE]);
760         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_TRIM_OFF], &td->seq_rand_state[DDIR_TRIM]);
761 }
762
763 static void td_fill_rand_seeds_internal(struct thread_data *td)
764 {
765         init_rand_seed(&td->__bsrange_state, td->rand_seeds[FIO_RAND_BS_OFF]);
766         init_rand_seed(&td->__verify_state, td->rand_seeds[FIO_RAND_VER_OFF]);
767         init_rand_seed(&td->__rwmix_state, td->rand_seeds[FIO_RAND_MIX_OFF]);
768
769         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
770                 init_rand_seed(&td->__next_file_state, td->rand_seeds[FIO_RAND_FILE_OFF]);
771
772         init_rand_seed(&td->__file_size_state, td->rand_seeds[FIO_RAND_FILE_SIZE_OFF]);
773         init_rand_seed(&td->__trim_state, td->rand_seeds[FIO_RAND_TRIM_OFF]);
774         init_rand_seed(&td->__delay_state, td->rand_seeds[FIO_RAND_START_DELAY]);
775
776         if (!td_random(td))
777                 return;
778
779         if (td->o.rand_repeatable)
780                 td->rand_seeds[FIO_RAND_BLOCK_OFF] = FIO_RANDSEED * td->thread_number;
781
782         init_rand_seed(&td->__random_state, td->rand_seeds[FIO_RAND_BLOCK_OFF]);
783         init_rand_seed(&td->__seq_rand_state[DDIR_READ], td->rand_seeds[FIO_RAND_SEQ_RAND_READ_OFF]);
784         init_rand_seed(&td->__seq_rand_state[DDIR_WRITE], td->rand_seeds[FIO_RAND_SEQ_RAND_WRITE_OFF]);
785         init_rand_seed(&td->__seq_rand_state[DDIR_TRIM], td->rand_seeds[FIO_RAND_SEQ_RAND_TRIM_OFF]);
786 }
787
788 void td_fill_rand_seeds(struct thread_data *td)
789 {
790         if (td->o.allrand_repeatable) {
791                 for (int i = 0; i < FIO_RAND_NR_OFFS; i++)
792                         td->rand_seeds[i] = FIO_RANDSEED * td->thread_number
793                                 + i;
794         }
795
796         if (td->o.use_os_rand)
797                 td_fill_rand_seeds_os(td);
798         else
799                 td_fill_rand_seeds_internal(td);
800
801         init_rand_seed(&td->buf_state, td->rand_seeds[FIO_RAND_BUF_OFF]);
802 }
803
804 /*
805  * Initializes the ioengine configured for a job, if it has not been done so
806  * already.
807  */
808 int ioengine_load(struct thread_data *td)
809 {
810         const char *engine;
811
812         /*
813          * Engine has already been loaded.
814          */
815         if (td->io_ops)
816                 return 0;
817         if (!td->o.ioengine) {
818                 log_err("fio: internal fault, no IO engine specified\n");
819                 return 1;
820         }
821
822         engine = get_engine_name(td->o.ioengine);
823         td->io_ops = load_ioengine(td, engine);
824         if (!td->io_ops) {
825                 log_err("fio: failed to load engine %s\n", engine);
826                 return 1;
827         }
828
829         if (td->io_ops->option_struct_size && td->io_ops->options) {
830                 /*
831                  * In cases where td->eo is set, clone it for a child thread.
832                  * This requires that the parent thread has the same ioengine,
833                  * but that requirement must be enforced by the code which
834                  * cloned the thread.
835                  */
836                 void *origeo = td->eo;
837                 /*
838                  * Otherwise use the default thread options.
839                  */
840                 if (!origeo && td != &def_thread && def_thread.eo &&
841                     def_thread.io_ops->options == td->io_ops->options)
842                         origeo = def_thread.eo;
843
844                 options_init(td->io_ops->options);
845                 td->eo = malloc(td->io_ops->option_struct_size);
846                 /*
847                  * Use the default thread as an option template if this uses the
848                  * same options structure and there are non-default options
849                  * used.
850                  */
851                 if (origeo) {
852                         memcpy(td->eo, origeo, td->io_ops->option_struct_size);
853                         options_mem_dupe(td->eo, td->io_ops->options);
854                 } else {
855                         memset(td->eo, 0, td->io_ops->option_struct_size);
856                         fill_default_options(td->eo, td->io_ops->options);
857                 }
858                 *(struct thread_data **)td->eo = td;
859         }
860
861         return 0;
862 }
863
864 static void init_flags(struct thread_data *td)
865 {
866         struct thread_options *o = &td->o;
867
868         if (o->verify_backlog)
869                 td->flags |= TD_F_VER_BACKLOG;
870         if (o->trim_backlog)
871                 td->flags |= TD_F_TRIM_BACKLOG;
872         if (o->read_iolog_file)
873                 td->flags |= TD_F_READ_IOLOG;
874         if (o->refill_buffers)
875                 td->flags |= TD_F_REFILL_BUFFERS;
876         if (o->scramble_buffers)
877                 td->flags |= TD_F_SCRAMBLE_BUFFERS;
878         if (o->verify != VERIFY_NONE)
879                 td->flags |= TD_F_VER_NONE;
880 }
881
882 static int setup_random_seeds(struct thread_data *td)
883 {
884         unsigned long seed;
885         unsigned int i;
886
887         if (!td->o.rand_repeatable && !td->o.rand_seed)
888                 return init_random_state(td, td->rand_seeds, sizeof(td->rand_seeds));
889
890         if (!td->o.rand_seed)
891                 seed = 0x89;
892         else
893                 seed = td->o.rand_seed;
894
895         for (i = 0; i < 4; i++)
896                 seed *= 0x9e370001UL;
897
898         for (i = 0; i < FIO_RAND_NR_OFFS; i++) {
899                 td->rand_seeds[i] = seed;
900                 seed *= 0x9e370001UL;
901         }
902
903         td_fill_rand_seeds(td);
904         return 0;
905 }
906
907 enum {
908         FPRE_NONE = 0,
909         FPRE_JOBNAME,
910         FPRE_JOBNUM,
911         FPRE_FILENUM
912 };
913
914 static struct fpre_keyword {
915         const char *keyword;
916         size_t strlen;
917         int key;
918 } fpre_keywords[] = {
919         { .keyword = "$jobname",        .key = FPRE_JOBNAME, },
920         { .keyword = "$jobnum",         .key = FPRE_JOBNUM, },
921         { .keyword = "$filenum",        .key = FPRE_FILENUM, },
922         { .keyword = NULL, },
923         };
924
925 static char *make_filename(char *buf, struct thread_options *o,
926                            const char *jobname, int jobnum, int filenum)
927 {
928         struct fpre_keyword *f;
929         char copy[PATH_MAX];
930
931         if (!o->filename_format || !strlen(o->filename_format)) {
932                 sprintf(buf, "%s.%d.%d", jobname, jobnum, filenum);
933                 return NULL;
934         }
935
936         for (f = &fpre_keywords[0]; f->keyword; f++)
937                 f->strlen = strlen(f->keyword);
938
939         strcpy(buf, o->filename_format);
940         memset(copy, 0, sizeof(copy));
941         for (f = &fpre_keywords[0]; f->keyword; f++) {
942                 do {
943                         size_t pre_len, post_start = 0;
944                         char *str, *dst = copy;
945
946                         str = strcasestr(buf, f->keyword);
947                         if (!str)
948                                 break;
949
950                         pre_len = str - buf;
951                         if (strlen(str) != f->strlen)
952                                 post_start = pre_len + f->strlen;
953
954                         if (pre_len) {
955                                 strncpy(dst, buf, pre_len);
956                                 dst += pre_len;
957                         }
958
959                         switch (f->key) {
960                         case FPRE_JOBNAME:
961                                 dst += sprintf(dst, "%s", jobname);
962                                 break;
963                         case FPRE_JOBNUM:
964                                 dst += sprintf(dst, "%d", jobnum);
965                                 break;
966                         case FPRE_FILENUM:
967                                 dst += sprintf(dst, "%d", filenum);
968                                 break;
969                         default:
970                                 assert(0);
971                                 break;
972                         }
973
974                         if (post_start)
975                                 strcpy(dst, buf + post_start);
976
977                         strcpy(buf, copy);
978                 } while (1);
979         }
980
981         return buf;
982 }
983
984 int parse_dryrun(void)
985 {
986         return dump_cmdline || parse_only;
987 }
988
989 /*
990  * Adds a job to the list of things todo. Sanitizes the various options
991  * to make sure we don't have conflicts, and initializes various
992  * members of td.
993  */
994 static int add_job(struct thread_data *td, const char *jobname, int job_add_num,
995                    int recursed, int client_type)
996 {
997         unsigned int i;
998         char fname[PATH_MAX];
999         int numjobs, file_alloced;
1000         struct thread_options *o = &td->o;
1001
1002         /*
1003          * the def_thread is just for options, it's not a real job
1004          */
1005         if (td == &def_thread)
1006                 return 0;
1007
1008         init_flags(td);
1009
1010         /*
1011          * if we are just dumping the output command line, don't add the job
1012          */
1013         if (parse_dryrun()) {
1014                 put_job(td);
1015                 return 0;
1016         }
1017
1018         td->client_type = client_type;
1019
1020         if (profile_td_init(td))
1021                 goto err;
1022
1023         if (ioengine_load(td))
1024                 goto err;
1025
1026         if (o->odirect)
1027                 td->io_ops->flags |= FIO_RAWIO;
1028
1029         file_alloced = 0;
1030         if (!o->filename && !td->files_index && !o->read_iolog_file) {
1031                 file_alloced = 1;
1032
1033                 if (o->nr_files == 1 && exists_and_not_file(jobname))
1034                         add_file(td, jobname, job_add_num, 0);
1035                 else {
1036                         for (i = 0; i < o->nr_files; i++)
1037                                 add_file(td, make_filename(fname, o, jobname, job_add_num, i), job_add_num, 0);
1038                 }
1039         }
1040
1041         if (fixup_options(td))
1042                 goto err;
1043
1044         flow_init_job(td);
1045
1046         /*
1047          * IO engines only need this for option callbacks, and the address may
1048          * change in subprocesses.
1049          */
1050         if (td->eo)
1051                 *(struct thread_data **)td->eo = NULL;
1052
1053         if (td->io_ops->flags & FIO_DISKLESSIO) {
1054                 struct fio_file *f;
1055
1056                 for_each_file(td, f, i)
1057                         f->real_file_size = -1ULL;
1058         }
1059
1060         td->mutex = fio_mutex_init(FIO_MUTEX_LOCKED);
1061
1062         td->ts.clat_percentiles = o->clat_percentiles;
1063         td->ts.percentile_precision = o->percentile_precision;
1064         memcpy(td->ts.percentile_list, o->percentile_list, sizeof(o->percentile_list));
1065
1066         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1067                 td->ts.clat_stat[i].min_val = ULONG_MAX;
1068                 td->ts.slat_stat[i].min_val = ULONG_MAX;
1069                 td->ts.lat_stat[i].min_val = ULONG_MAX;
1070                 td->ts.bw_stat[i].min_val = ULONG_MAX;
1071         }
1072         td->ddir_seq_nr = o->ddir_seq_nr;
1073
1074         if ((o->stonewall || o->new_group) && prev_group_jobs) {
1075                 prev_group_jobs = 0;
1076                 groupid++;
1077         }
1078
1079         td->groupid = groupid;
1080         prev_group_jobs++;
1081
1082         if (setup_random_seeds(td)) {
1083                 td_verror(td, errno, "init_random_state");
1084                 goto err;
1085         }
1086
1087         if (setup_rate(td))
1088                 goto err;
1089
1090         if (o->lat_log_file || write_lat_log) {
1091                 setup_log(&td->lat_log, o->log_avg_msec, IO_LOG_TYPE_LAT);
1092                 setup_log(&td->slat_log, o->log_avg_msec, IO_LOG_TYPE_SLAT);
1093                 setup_log(&td->clat_log, o->log_avg_msec, IO_LOG_TYPE_CLAT);
1094         }
1095         if (o->bw_log_file || write_bw_log)
1096                 setup_log(&td->bw_log, o->log_avg_msec, IO_LOG_TYPE_BW);
1097         if (o->iops_log_file)
1098                 setup_log(&td->iops_log, o->log_avg_msec, IO_LOG_TYPE_IOPS);
1099
1100         if (!o->name)
1101                 o->name = strdup(jobname);
1102
1103         if (output_format == FIO_OUTPUT_NORMAL) {
1104                 if (!job_add_num) {
1105                         if (is_backend && !recursed)
1106                                 fio_server_send_add_job(td);
1107
1108                         if (!(td->io_ops->flags & FIO_NOIO)) {
1109                                 char *c1, *c2, *c3, *c4;
1110                                 char *c5 = NULL, *c6 = NULL;
1111
1112                                 c1 = fio_uint_to_kmg(o->min_bs[DDIR_READ]);
1113                                 c2 = fio_uint_to_kmg(o->max_bs[DDIR_READ]);
1114                                 c3 = fio_uint_to_kmg(o->min_bs[DDIR_WRITE]);
1115                                 c4 = fio_uint_to_kmg(o->max_bs[DDIR_WRITE]);
1116
1117                                 if (!o->bs_is_seq_rand) {
1118                                         c5 = fio_uint_to_kmg(o->min_bs[DDIR_TRIM]);
1119                                         c6 = fio_uint_to_kmg(o->max_bs[DDIR_TRIM]);
1120                                 }
1121
1122                                 log_info("%s: (g=%d): rw=%s, ", td->o.name,
1123                                                         td->groupid,
1124                                                         ddir_str(o->td_ddir));
1125
1126                                 if (o->bs_is_seq_rand)
1127                                         log_info("bs(seq/rand)=%s-%s/%s-%s, ",
1128                                                         c1, c2, c3, c4);
1129                                 else
1130                                         log_info("bs=%s-%s/%s-%s/%s-%s, ",
1131                                                         c1, c2, c3, c4, c5, c6);
1132
1133                                 log_info("ioengine=%s, iodepth=%u\n",
1134                                                 td->io_ops->name, o->iodepth);
1135
1136                                 free(c1);
1137                                 free(c2);
1138                                 free(c3);
1139                                 free(c4);
1140                                 free(c5);
1141                                 free(c6);
1142                         }
1143                 } else if (job_add_num == 1)
1144                         log_info("...\n");
1145         }
1146
1147         /*
1148          * recurse add identical jobs, clear numjobs and stonewall options
1149          * as they don't apply to sub-jobs
1150          */
1151         numjobs = o->numjobs;
1152         while (--numjobs) {
1153                 struct thread_data *td_new = get_new_job(0, td, 1);
1154
1155                 if (!td_new)
1156                         goto err;
1157
1158                 td_new->o.numjobs = 1;
1159                 td_new->o.stonewall = 0;
1160                 td_new->o.new_group = 0;
1161
1162                 if (file_alloced) {
1163                         if (td_new->files) {
1164                                 struct fio_file *f;
1165                                 for_each_file(td_new, f, i) {
1166                                         if (f->file_name)
1167                                                 sfree(f->file_name);
1168                                         sfree(f);
1169                                 }
1170                                 free(td_new->files);
1171                                 td_new->files = NULL;
1172                         }
1173                         td_new->files_index = 0;
1174                         td_new->files_size = 0;
1175                         if (td_new->o.filename) {
1176                                 free(td_new->o.filename);
1177                                 td_new->o.filename = NULL;
1178                         }
1179                 }
1180
1181                 if (add_job(td_new, jobname, numjobs, 1, client_type))
1182                         goto err;
1183         }
1184
1185         return 0;
1186 err:
1187         put_job(td);
1188         return -1;
1189 }
1190
1191 /*
1192  * Parse as if 'o' was a command line
1193  */
1194 void add_job_opts(const char **o, int client_type)
1195 {
1196         struct thread_data *td, *td_parent;
1197         int i, in_global = 1;
1198         char jobname[32];
1199
1200         i = 0;
1201         td_parent = td = NULL;
1202         while (o[i]) {
1203                 if (!strncmp(o[i], "name", 4)) {
1204                         in_global = 0;
1205                         if (td)
1206                                 add_job(td, jobname, 0, 0, client_type);
1207                         td = NULL;
1208                         sprintf(jobname, "%s", o[i] + 5);
1209                 }
1210                 if (in_global && !td_parent)
1211                         td_parent = get_new_job(1, &def_thread, 0);
1212                 else if (!in_global && !td) {
1213                         if (!td_parent)
1214                                 td_parent = &def_thread;
1215                         td = get_new_job(0, td_parent, 0);
1216                 }
1217                 if (in_global)
1218                         fio_options_parse(td_parent, (char **) &o[i], 1, 0);
1219                 else
1220                         fio_options_parse(td, (char **) &o[i], 1, 0);
1221                 i++;
1222         }
1223
1224         if (td)
1225                 add_job(td, jobname, 0, 0, client_type);
1226 }
1227
1228 static int skip_this_section(const char *name)
1229 {
1230         int i;
1231
1232         if (!nr_job_sections)
1233                 return 0;
1234         if (!strncmp(name, "global", 6))
1235                 return 0;
1236
1237         for (i = 0; i < nr_job_sections; i++)
1238                 if (!strcmp(job_sections[i], name))
1239                         return 0;
1240
1241         return 1;
1242 }
1243
1244 static int is_empty_or_comment(char *line)
1245 {
1246         unsigned int i;
1247
1248         for (i = 0; i < strlen(line); i++) {
1249                 if (line[i] == ';')
1250                         return 1;
1251                 if (line[i] == '#')
1252                         return 1;
1253                 if (!isspace((int) line[i]) && !iscntrl((int) line[i]))
1254                         return 0;
1255         }
1256
1257         return 1;
1258 }
1259
1260 /*
1261  * This is our [ini] type file parser.
1262  */
1263 int parse_jobs_ini(char *file, int is_buf, int stonewall_flag, int type)
1264 {
1265         unsigned int global;
1266         struct thread_data *td;
1267         char *string, *name;
1268         FILE *f;
1269         char *p;
1270         int ret = 0, stonewall;
1271         int first_sect = 1;
1272         int skip_fgets = 0;
1273         int inside_skip = 0;
1274         char **opts;
1275         int i, alloc_opts, num_opts;
1276
1277         if (is_buf)
1278                 f = NULL;
1279         else {
1280                 if (!strcmp(file, "-"))
1281                         f = stdin;
1282                 else
1283                         f = fopen(file, "r");
1284
1285                 if (!f) {
1286                         perror("fopen job file");
1287                         return 1;
1288                 }
1289         }
1290
1291         string = malloc(4096);
1292
1293         /*
1294          * it's really 256 + small bit, 280 should suffice
1295          */
1296         name = malloc(280);
1297         memset(name, 0, 280);
1298
1299         alloc_opts = 8;
1300         opts = malloc(sizeof(char *) * alloc_opts);
1301         num_opts = 0;
1302
1303         stonewall = stonewall_flag;
1304         do {
1305                 /*
1306                  * if skip_fgets is set, we already have loaded a line we
1307                  * haven't handled.
1308                  */
1309                 if (!skip_fgets) {
1310                         if (is_buf)
1311                                 p = strsep(&file, "\n");
1312                         else
1313                                 p = fgets(string, 4096, f);
1314                         if (!p)
1315                                 break;
1316                 }
1317
1318                 skip_fgets = 0;
1319                 strip_blank_front(&p);
1320                 strip_blank_end(p);
1321
1322                 if (is_empty_or_comment(p))
1323                         continue;
1324                 if (sscanf(p, "[%255[^\n]]", name) != 1) {
1325                         if (inside_skip)
1326                                 continue;
1327                         log_err("fio: option <%s> outside of [] job section\n",
1328                                                                         p);
1329                         break;
1330                 }
1331
1332                 name[strlen(name) - 1] = '\0';
1333
1334                 if (skip_this_section(name)) {
1335                         inside_skip = 1;
1336                         continue;
1337                 } else
1338                         inside_skip = 0;
1339
1340                 global = !strncmp(name, "global", 6);
1341
1342                 if (dump_cmdline) {
1343                         if (first_sect)
1344                                 log_info("fio ");
1345                         if (!global)
1346                                 log_info("--name=%s ", name);
1347                         first_sect = 0;
1348                 }
1349
1350                 td = get_new_job(global, &def_thread, 0);
1351                 if (!td) {
1352                         ret = 1;
1353                         break;
1354                 }
1355
1356                 /*
1357                  * Separate multiple job files by a stonewall
1358                  */
1359                 if (!global && stonewall) {
1360                         td->o.stonewall = stonewall;
1361                         stonewall = 0;
1362                 }
1363
1364                 num_opts = 0;
1365                 memset(opts, 0, alloc_opts * sizeof(char *));
1366
1367                 while (1) {
1368                         if (is_buf)
1369                                 p = strsep(&file, "\n");
1370                         else
1371                                 p = fgets(string, 4096, f);
1372                         if (!p)
1373                                 break;
1374
1375                         if (is_empty_or_comment(p))
1376                                 continue;
1377
1378                         strip_blank_front(&p);
1379
1380                         /*
1381                          * new section, break out and make sure we don't
1382                          * fgets() a new line at the top.
1383                          */
1384                         if (p[0] == '[') {
1385                                 skip_fgets = 1;
1386                                 break;
1387                         }
1388
1389                         strip_blank_end(p);
1390
1391                         if (num_opts == alloc_opts) {
1392                                 alloc_opts <<= 1;
1393                                 opts = realloc(opts,
1394                                                 alloc_opts * sizeof(char *));
1395                         }
1396
1397                         opts[num_opts] = strdup(p);
1398                         num_opts++;
1399                 }
1400
1401                 ret = fio_options_parse(td, opts, num_opts, dump_cmdline);
1402                 if (!ret)
1403                         ret = add_job(td, name, 0, 0, type);
1404                 else {
1405                         log_err("fio: job %s dropped\n", name);
1406                         put_job(td);
1407                 }
1408
1409                 for (i = 0; i < num_opts; i++)
1410                         free(opts[i]);
1411                 num_opts = 0;
1412         } while (!ret);
1413
1414         if (dump_cmdline)
1415                 log_info("\n");
1416
1417         i = 0;
1418         while (i < nr_job_sections) {
1419                 free(job_sections[i]);
1420                 i++;
1421         }
1422
1423         for (i = 0; i < num_opts; i++)
1424                 free(opts[i]);
1425
1426         free(string);
1427         free(name);
1428         free(opts);
1429         if (!is_buf && f != stdin)
1430                 fclose(f);
1431         return ret;
1432 }
1433
1434 static int fill_def_thread(void)
1435 {
1436         memset(&def_thread, 0, sizeof(def_thread));
1437
1438         fio_getaffinity(getpid(), &def_thread.o.cpumask);
1439         def_thread.o.timeout = def_timeout;
1440         def_thread.o.error_dump = 1;
1441         /*
1442          * fill default options
1443          */
1444         fio_fill_default_options(&def_thread);
1445         return 0;
1446 }
1447
1448 static void usage(const char *name)
1449 {
1450         printf("%s\n", fio_version_string);
1451         printf("%s [options] [job options] <job file(s)>\n", name);
1452         printf("  --debug=options\tEnable debug logging. May be one/more of:\n"
1453                 "\t\t\tprocess,file,io,mem,blktrace,verify,random,parse,\n"
1454                 "\t\t\tdiskutil,job,mutex,profile,time,net,rate\n");
1455         printf("  --parse-only\t\tParse options only, don't start any IO\n");
1456         printf("  --output\t\tWrite output to file\n");
1457         printf("  --runtime\t\tRuntime in seconds\n");
1458         printf("  --latency-log\t\tGenerate per-job latency logs\n");
1459         printf("  --bandwidth-log\tGenerate per-job bandwidth logs\n");
1460         printf("  --minimal\t\tMinimal (terse) output\n");
1461         printf("  --output-format=x\tOutput format (terse,json,normal)\n");
1462         printf("  --terse-version=x\tSet terse version output format to 'x'\n");
1463         printf("  --version\t\tPrint version info and exit\n");
1464         printf("  --help\t\tPrint this page\n");
1465         printf("  --cpuclock-test\tPerform test/validation of CPU clock\n");
1466         printf("  --crctest\t\tTest speed of checksum functions\n");
1467         printf("  --cmdhelp=cmd\t\tPrint command help, \"all\" for all of"
1468                 " them\n");
1469         printf("  --enghelp=engine\tPrint ioengine help, or list"
1470                 " available ioengines\n");
1471         printf("  --enghelp=engine,cmd\tPrint help for an ioengine"
1472                 " cmd\n");
1473         printf("  --showcmd\t\tTurn a job file into command line options\n");
1474         printf("  --eta=when\t\tWhen ETA estimate should be printed\n");
1475         printf("            \t\tMay be \"always\", \"never\" or \"auto\"\n");
1476         printf("  --eta-newline=time\tForce a new line for every 'time'");
1477         printf(" period passed\n");
1478         printf("  --status-interval=t\tForce full status dump every");
1479         printf(" 't' period passed\n");
1480         printf("  --readonly\t\tTurn on safety read-only checks, preventing"
1481                 " writes\n");
1482         printf("  --section=name\tOnly run specified section in job file\n");
1483         printf("  --alloc-size=kb\tSet smalloc pool to this size in kb"
1484                 " (def 1024)\n");
1485         printf("  --warnings-fatal\tFio parser warnings are fatal\n");
1486         printf("  --max-jobs=nr\t\tMaximum number of threads/processes to support\n");
1487         printf("  --server=args\t\tStart a backend fio server\n");
1488         printf("  --daemonize=pidfile\tBackground fio server, write pid to file\n");
1489         printf("  --client=hostname\tTalk to remote backend fio server at hostname\n");
1490         printf("  --idle-prof=option\tReport cpu idleness on a system or percpu basis\n"
1491                 "\t\t\t(option=system,percpu) or run unit work\n"
1492                 "\t\t\tcalibration only (option=calibrate)\n");
1493         printf("\nFio was written by Jens Axboe <jens.axboe@oracle.com>");
1494         printf("\n                   Jens Axboe <jaxboe@fusionio.com>");
1495         printf("\n                   Jens Axboe <axboe@fb.com>\n");
1496 }
1497
1498 #ifdef FIO_INC_DEBUG
1499 struct debug_level debug_levels[] = {
1500         { .name = "process",
1501           .help = "Process creation/exit logging",
1502           .shift = FD_PROCESS,
1503         },
1504         { .name = "file",
1505           .help = "File related action logging",
1506           .shift = FD_FILE,
1507         },
1508         { .name = "io",
1509           .help = "IO and IO engine action logging (offsets, queue, completions, etc)",
1510           .shift = FD_IO,
1511         },
1512         { .name = "mem",
1513           .help = "Memory allocation/freeing logging",
1514           .shift = FD_MEM,
1515         },
1516         { .name = "blktrace",
1517           .help = "blktrace action logging",
1518           .shift = FD_BLKTRACE,
1519         },
1520         { .name = "verify",
1521           .help = "IO verification action logging",
1522           .shift = FD_VERIFY,
1523         },
1524         { .name = "random",
1525           .help = "Random generation logging",
1526           .shift = FD_RANDOM,
1527         },
1528         { .name = "parse",
1529           .help = "Parser logging",
1530           .shift = FD_PARSE,
1531         },
1532         { .name = "diskutil",
1533           .help = "Disk utility logging actions",
1534           .shift = FD_DISKUTIL,
1535         },
1536         { .name = "job",
1537           .help = "Logging related to creating/destroying jobs",
1538           .shift = FD_JOB,
1539         },
1540         { .name = "mutex",
1541           .help = "Mutex logging",
1542           .shift = FD_MUTEX
1543         },
1544         { .name = "profile",
1545           .help = "Logging related to profiles",
1546           .shift = FD_PROFILE,
1547         },
1548         { .name = "time",
1549           .help = "Logging related to time keeping functions",
1550           .shift = FD_TIME,
1551         },
1552         { .name = "net",
1553           .help = "Network logging",
1554           .shift = FD_NET,
1555         },
1556         { .name = "rate",
1557           .help = "Rate logging",
1558           .shift = FD_RATE,
1559         },
1560         { .name = NULL, },
1561 };
1562
1563 static int set_debug(const char *string)
1564 {
1565         struct debug_level *dl;
1566         char *p = (char *) string;
1567         char *opt;
1568         int i;
1569
1570         if (!strcmp(string, "?") || !strcmp(string, "help")) {
1571                 log_info("fio: dumping debug options:");
1572                 for (i = 0; debug_levels[i].name; i++) {
1573                         dl = &debug_levels[i];
1574                         log_info("%s,", dl->name);
1575                 }
1576                 log_info("all\n");
1577                 return 1;
1578         }
1579
1580         while ((opt = strsep(&p, ",")) != NULL) {
1581                 int found = 0;
1582
1583                 if (!strncmp(opt, "all", 3)) {
1584                         log_info("fio: set all debug options\n");
1585                         fio_debug = ~0UL;
1586                         continue;
1587                 }
1588
1589                 for (i = 0; debug_levels[i].name; i++) {
1590                         dl = &debug_levels[i];
1591                         found = !strncmp(opt, dl->name, strlen(dl->name));
1592                         if (!found)
1593                                 continue;
1594
1595                         if (dl->shift == FD_JOB) {
1596                                 opt = strchr(opt, ':');
1597                                 if (!opt) {
1598                                         log_err("fio: missing job number\n");
1599                                         break;
1600                                 }
1601                                 opt++;
1602                                 fio_debug_jobno = atoi(opt);
1603                                 log_info("fio: set debug jobno %d\n",
1604                                                         fio_debug_jobno);
1605                         } else {
1606                                 log_info("fio: set debug option %s\n", opt);
1607                                 fio_debug |= (1UL << dl->shift);
1608                         }
1609                         break;
1610                 }
1611
1612                 if (!found)
1613                         log_err("fio: debug mask %s not found\n", opt);
1614         }
1615         return 0;
1616 }
1617 #else
1618 static int set_debug(const char *string)
1619 {
1620         log_err("fio: debug tracing not included in build\n");
1621         return 1;
1622 }
1623 #endif
1624
1625 static void fio_options_fill_optstring(void)
1626 {
1627         char *ostr = cmd_optstr;
1628         int i, c;
1629
1630         c = i = 0;
1631         while (l_opts[i].name) {
1632                 ostr[c++] = l_opts[i].val;
1633                 if (l_opts[i].has_arg == required_argument)
1634                         ostr[c++] = ':';
1635                 else if (l_opts[i].has_arg == optional_argument) {
1636                         ostr[c++] = ':';
1637                         ostr[c++] = ':';
1638                 }
1639                 i++;
1640         }
1641         ostr[c] = '\0';
1642 }
1643
1644 static int client_flag_set(char c)
1645 {
1646         int i;
1647
1648         i = 0;
1649         while (l_opts[i].name) {
1650                 int val = l_opts[i].val;
1651
1652                 if (c == (val & 0xff))
1653                         return (val & FIO_CLIENT_FLAG);
1654
1655                 i++;
1656         }
1657
1658         return 0;
1659 }
1660
1661 void parse_cmd_client(void *client, char *opt)
1662 {
1663         fio_client_add_cmd_option(client, opt);
1664 }
1665
1666 extern int fio_crctest(const char *);
1667
1668 int parse_cmd_line(int argc, char *argv[], int client_type)
1669 {
1670         struct thread_data *td = NULL;
1671         int c, ini_idx = 0, lidx, ret = 0, do_exit = 0, exit_val = 0;
1672         char *ostr = cmd_optstr;
1673         void *pid_file = NULL;
1674         void *cur_client = NULL;
1675         int backend = 0;
1676
1677         /*
1678          * Reset optind handling, since we may call this multiple times
1679          * for the backend.
1680          */
1681         optind = 1;
1682
1683         while ((c = getopt_long_only(argc, argv, ostr, l_opts, &lidx)) != -1) {
1684                 did_arg = 1;
1685
1686                 if ((c & FIO_CLIENT_FLAG) || client_flag_set(c)) {
1687                         parse_cmd_client(cur_client, argv[optind - 1]);
1688                         c &= ~FIO_CLIENT_FLAG;
1689                 }
1690
1691                 switch (c) {
1692                 case 'a':
1693                         smalloc_pool_size = atoi(optarg);
1694                         break;
1695                 case 't':
1696                         def_timeout = atoi(optarg);
1697                         break;
1698                 case 'l':
1699                         write_lat_log = 1;
1700                         break;
1701                 case 'b':
1702                         write_bw_log = 1;
1703                         break;
1704                 case 'o':
1705                         f_out = fopen(optarg, "w+");
1706                         if (!f_out) {
1707                                 perror("fopen output");
1708                                 exit(1);
1709                         }
1710                         f_err = f_out;
1711                         break;
1712                 case 'm':
1713                         output_format = FIO_OUTPUT_TERSE;
1714                         break;
1715                 case 'F':
1716                         if (!optarg) {
1717                                 log_err("fio: missing --output-format argument\n");
1718                                 exit_val = 1;
1719                                 do_exit++;
1720                                 break;
1721                         }
1722                         if (!strcmp(optarg, "minimal") ||
1723                             !strcmp(optarg, "terse") ||
1724                             !strcmp(optarg, "csv"))
1725                                 output_format = FIO_OUTPUT_TERSE;
1726                         else if (!strcmp(optarg, "json"))
1727                                 output_format = FIO_OUTPUT_JSON;
1728                         else
1729                                 output_format = FIO_OUTPUT_NORMAL;
1730                         break;
1731                 case 'f':
1732                         append_terse_output = 1;
1733                         break;
1734                 case 'h':
1735                         if (!cur_client) {
1736                                 usage(argv[0]);
1737                                 do_exit++;
1738                         }
1739                         break;
1740                 case 'c':
1741                         if (!cur_client) {
1742                                 fio_show_option_help(optarg);
1743                                 do_exit++;
1744                         }
1745                         break;
1746                 case 'i':
1747                         if (!cur_client) {
1748                                 fio_show_ioengine_help(optarg);
1749                                 do_exit++;
1750                         }
1751                         break;
1752                 case 's':
1753                         dump_cmdline = 1;
1754                         break;
1755                 case 'r':
1756                         read_only = 1;
1757                         break;
1758                 case 'v':
1759                         if (!cur_client) {
1760                                 log_info("%s\n", fio_version_string);
1761                                 do_exit++;
1762                         }
1763                         break;
1764                 case 'V':
1765                         terse_version = atoi(optarg);
1766                         if (!(terse_version == 2 || terse_version == 3 ||
1767                              terse_version == 4)) {
1768                                 log_err("fio: bad terse version format\n");
1769                                 exit_val = 1;
1770                                 do_exit++;
1771                         }
1772                         break;
1773                 case 'e':
1774                         if (!strcmp("always", optarg))
1775                                 eta_print = FIO_ETA_ALWAYS;
1776                         else if (!strcmp("never", optarg))
1777                                 eta_print = FIO_ETA_NEVER;
1778                         break;
1779                 case 'E': {
1780                         long long t = 0;
1781
1782                         if (str_to_decimal(optarg, &t, 0, NULL, 1)) {
1783                                 log_err("fio: failed parsing eta time %s\n", optarg);
1784                                 exit_val = 1;
1785                                 do_exit++;
1786                         }
1787                         eta_new_line = t;
1788                         break;
1789                         }
1790                 case 'd':
1791                         if (set_debug(optarg))
1792                                 do_exit++;
1793                         break;
1794                 case 'P':
1795                         parse_only = 1;
1796                         break;
1797                 case 'x': {
1798                         size_t new_size;
1799
1800                         if (!strcmp(optarg, "global")) {
1801                                 log_err("fio: can't use global as only "
1802                                         "section\n");
1803                                 do_exit++;
1804                                 exit_val = 1;
1805                                 break;
1806                         }
1807                         new_size = (nr_job_sections + 1) * sizeof(char *);
1808                         job_sections = realloc(job_sections, new_size);
1809                         job_sections[nr_job_sections] = strdup(optarg);
1810                         nr_job_sections++;
1811                         break;
1812                         }
1813                 case 'p':
1814                         exec_profile = strdup(optarg);
1815                         break;
1816                 case FIO_GETOPT_JOB: {
1817                         const char *opt = l_opts[lidx].name;
1818                         char *val = optarg;
1819
1820                         if (!strncmp(opt, "name", 4) && td) {
1821                                 ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
1822                                 if (ret)
1823                                         return 0;
1824                                 td = NULL;
1825                         }
1826                         if (!td) {
1827                                 int is_section = !strncmp(opt, "name", 4);
1828                                 int global = 0;
1829
1830                                 if (!is_section || !strncmp(val, "global", 6))
1831                                         global = 1;
1832
1833                                 if (is_section && skip_this_section(val))
1834                                         continue;
1835
1836                                 td = get_new_job(global, &def_thread, 1);
1837                                 if (!td || ioengine_load(td))
1838                                         return 0;
1839                                 fio_options_set_ioengine_opts(l_opts, td);
1840                         }
1841
1842                         if ((!val || !strlen(val)) &&
1843                             l_opts[lidx].has_arg == required_argument) {
1844                                 log_err("fio: option %s requires an argument\n", opt);
1845                                 ret = 1;
1846                         } else
1847                                 ret = fio_cmd_option_parse(td, opt, val);
1848
1849                         if (ret) {
1850                                 if (td) {
1851                                         put_job(td);
1852                                         td = NULL;
1853                                 }
1854                                 do_exit++;
1855                         }
1856
1857                         if (!ret && !strcmp(opt, "ioengine")) {
1858                                 free_ioengine(td);
1859                                 if (ioengine_load(td))
1860                                         return 0;
1861                                 fio_options_set_ioengine_opts(l_opts, td);
1862                         }
1863                         break;
1864                 }
1865                 case FIO_GETOPT_IOENGINE: {
1866                         const char *opt = l_opts[lidx].name;
1867                         char *val = optarg;
1868                         ret = fio_cmd_ioengine_option_parse(td, opt, val);
1869                         break;
1870                 }
1871                 case 'w':
1872                         warnings_fatal = 1;
1873                         break;
1874                 case 'j':
1875                         max_jobs = atoi(optarg);
1876                         if (!max_jobs || max_jobs > REAL_MAX_JOBS) {
1877                                 log_err("fio: invalid max jobs: %d\n", max_jobs);
1878                                 do_exit++;
1879                                 exit_val = 1;
1880                         }
1881                         break;
1882                 case 'S':
1883                         if (nr_clients) {
1884                                 log_err("fio: can't be both client and server\n");
1885                                 do_exit++;
1886                                 exit_val = 1;
1887                                 break;
1888                         }
1889                         if (optarg)
1890                                 fio_server_set_arg(optarg);
1891                         is_backend = 1;
1892                         backend = 1;
1893                         break;
1894                 case 'D':
1895                         pid_file = strdup(optarg);
1896                         break;
1897                 case 'I':
1898                         if ((ret = fio_idle_prof_parse_opt(optarg))) {
1899                                 /* exit on error and calibration only */
1900                                 do_exit++;
1901                                 if (ret == -1) 
1902                                         exit_val = 1;
1903                         }
1904                         break;
1905                 case 'C':
1906                         if (is_backend) {
1907                                 log_err("fio: can't be both client and server\n");
1908                                 do_exit++;
1909                                 exit_val = 1;
1910                                 break;
1911                         }
1912                         if (fio_client_add(&fio_client_ops, optarg, &cur_client)) {
1913                                 log_err("fio: failed adding client %s\n", optarg);
1914                                 do_exit++;
1915                                 exit_val = 1;
1916                                 break;
1917                         }
1918                         /*
1919                          * If the next argument exists and isn't an option,
1920                          * assume it's a job file for this client only.
1921                          */
1922                         while (optind < argc) {
1923                                 if (!strncmp(argv[optind], "--", 2) ||
1924                                     !strncmp(argv[optind], "-", 1))
1925                                         break;
1926
1927                                 fio_client_add_ini_file(cur_client, argv[optind]);
1928                                 optind++;
1929                         }
1930                         break;
1931                 case 'T':
1932                         do_exit++;
1933                         exit_val = fio_monotonic_clocktest();
1934                         break;
1935                 case 'G':
1936                         do_exit++;
1937                         exit_val = fio_crctest(optarg);
1938                         break;
1939                 case 'L': {
1940                         long long val;
1941
1942                         if (check_str_time(optarg, &val, 0)) {
1943                                 log_err("fio: failed parsing time %s\n", optarg);
1944                                 do_exit++;
1945                                 exit_val = 1;
1946                                 break;
1947                         }
1948                         status_interval = val * 1000;
1949                         break;
1950                         }
1951                 case '?':
1952                         log_err("%s: unrecognized option '%s'\n", argv[0],
1953                                                         argv[optind - 1]);
1954                 default:
1955                         do_exit++;
1956                         exit_val = 1;
1957                         break;
1958                 }
1959                 if (do_exit)
1960                         break;
1961         }
1962
1963         if (do_exit && !(is_backend || nr_clients))
1964                 exit(exit_val);
1965
1966         if (nr_clients && fio_clients_connect()) {
1967                 do_exit++;
1968                 exit_val = 1;
1969                 return -1;
1970         }
1971
1972         if (is_backend && backend)
1973                 return fio_start_server(pid_file);
1974
1975         if (td) {
1976                 if (!ret)
1977                         ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
1978         }
1979
1980         while (!ret && optind < argc) {
1981                 ini_idx++;
1982                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
1983                 ini_file[ini_idx - 1] = strdup(argv[optind]);
1984                 optind++;
1985         }
1986
1987         return ini_idx;
1988 }
1989
1990 int fio_init_options(void)
1991 {
1992         f_out = stdout;
1993         f_err = stderr;
1994
1995         fio_options_fill_optstring();
1996         fio_options_dup_and_init(l_opts);
1997
1998         atexit(free_shm);
1999
2000         if (fill_def_thread())
2001                 return 1;
2002
2003         return 0;
2004 }
2005
2006 extern int fio_check_options(struct thread_options *);
2007
2008 int parse_options(int argc, char *argv[])
2009 {
2010         const int type = FIO_CLIENT_TYPE_CLI;
2011         int job_files, i;
2012
2013         if (fio_init_options())
2014                 return 1;
2015         if (fio_test_cconv(&def_thread.o))
2016                 log_err("fio: failed internal cconv test\n");
2017
2018         job_files = parse_cmd_line(argc, argv, type);
2019
2020         if (job_files > 0) {
2021                 for (i = 0; i < job_files; i++) {
2022                         if (fill_def_thread())
2023                                 return 1;
2024                         if (nr_clients) {
2025                                 if (fio_clients_send_ini(ini_file[i]))
2026                                         return 1;
2027                                 free(ini_file[i]);
2028                         } else if (!is_backend) {
2029                                 if (parse_jobs_ini(ini_file[i], 0, i, type))
2030                                         return 1;
2031                                 free(ini_file[i]);
2032                         }
2033                 }
2034         } else if (nr_clients) {
2035                 if (fill_def_thread())
2036                         return 1;
2037                 if (fio_clients_send_ini(NULL))
2038                         return 1;
2039         }
2040
2041         free(ini_file);
2042         fio_options_free(&def_thread);
2043         filesetup_mem_free();
2044
2045         if (!thread_number) {
2046                 if (parse_dryrun())
2047                         return 0;
2048                 if (exec_profile)
2049                         return 0;
2050                 if (is_backend || nr_clients)
2051                         return 0;
2052                 if (did_arg)
2053                         return 0;
2054
2055                 log_err("No jobs(s) defined\n\n");
2056
2057                 if (!did_arg) {
2058                         usage(argv[0]);
2059                         return 1;
2060                 }
2061
2062                 return 0;
2063         }
2064
2065         if (def_thread.o.gtod_offload) {
2066                 fio_gtod_init();
2067                 fio_gtod_offload = 1;
2068                 fio_gtod_cpu = def_thread.o.gtod_cpu;
2069         }
2070
2071         if (output_format == FIO_OUTPUT_NORMAL)
2072                 log_info("%s\n", fio_version_string);
2073
2074         return 0;
2075 }
2076
2077 void options_default_fill(struct thread_options *o)
2078 {
2079         memcpy(o, &def_thread.o, sizeof(*o));
2080 }