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