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