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