bca8424a9e49348c05b99a272c9d96789b469559
[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 <getopt.h>
12 #include <assert.h>
13 #include <sys/ipc.h>
14 #include <sys/shm.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17
18 #include "fio.h"
19 #include "parse.h"
20
21 #define FIO_RANDSEED            (0xb1899bedUL)
22
23 #define td_var_offset(var)      ((size_t) &((struct thread_data *)0)->var)
24
25 static int str_mem_cb(void *, const char *);
26 static int str_lockmem_cb(void *, unsigned long *);
27 #ifdef FIO_HAVE_IOPRIO
28 static int str_prio_cb(void *, unsigned int *);
29 static int str_prioclass_cb(void *, unsigned int *);
30 #endif
31 static int str_exitall_cb(void);
32 static int str_cpumask_cb(void *, unsigned int *);
33
34 #define __stringify_1(x)        #x
35 #define __stringify(x)          __stringify_1(x)
36
37 /*
38  * Map of job/command line options
39  */
40 static struct fio_option options[] = {
41         {
42                 .name   = "description",
43                 .type   = FIO_OPT_STR_STORE,
44                 .off1   = td_var_offset(description),
45                 .help   = "Text job description",
46         },
47         {
48                 .name   = "name",
49                 .type   = FIO_OPT_STR_STORE,
50                 .off1   = td_var_offset(name),
51                 .help   = "Name of this job",
52         },
53         {
54                 .name   = "directory",
55                 .type   = FIO_OPT_STR_STORE,
56                 .off1   = td_var_offset(directory),
57                 .help   = "Directory to store files in",
58         },
59         {
60                 .name   = "filename",
61                 .type   = FIO_OPT_STR_STORE,
62                 .off1   = td_var_offset(filename),
63                 .help   = "Force the use of a specific file",
64         },
65         {
66                 .name   = "rw",
67                 .type   = FIO_OPT_STR,
68                 .off1   = td_var_offset(td_ddir),
69                 .help   = "IO direction",
70                 .def    = "read",
71                 .posval = {
72                           { .ival = "read", .oval = TD_DDIR_READ },
73                           { .ival = "write", .oval = TD_DDIR_WRITE },
74                           { .ival = "randread", .oval = TD_DDIR_RANDREAD },
75                           { .ival = "randwrite", .oval = TD_DDIR_RANDWRITE },
76                           { .ival = "rw", .oval = TD_DDIR_RW },
77                           { .ival = "randrw", .oval = TD_DDIR_RANDRW },
78                           },
79         },
80         {
81                 .name   = "ioengine",
82                 .type   = FIO_OPT_STR_STORE,
83                 .off1   = td_var_offset(ioengine),
84                 .help   = "IO engine to use",
85                 .def    = "sync",
86                 .posval = {
87                           { .ival = "sync", },
88 #ifdef FIO_HAVE_LIBAIO
89                           { .ival = "libaio", },
90 #endif
91 #ifdef FIO_HAVE_POSIXAIO
92                           { .ival = "posixaio", },
93 #endif
94                           { .ival = "mmap", },
95 #ifdef FIO_HAVE_SPLICE
96                           { .ival = "splice", },
97 #endif
98 #ifdef FIO_HAVE_SGIO
99                           { .ival = "sg", },
100 #endif
101                           { .ival = "null", }, { .ival = "net", },
102 #ifdef FIO_HAVE_SYSLET
103                           { .ival = "syslet-rw", },
104 #endif
105                           { .ival = "cpuio", },
106                           { .ival = "external", },
107                           },
108         },
109         {
110                 .name   = "iodepth",
111                 .type   = FIO_OPT_INT,
112                 .off1   = td_var_offset(iodepth),
113                 .help   = "Amount of IO buffers to keep in flight",
114                 .def    = "1",
115         },
116         {
117                 .name   = "iodepth_batch",
118                 .type   = FIO_OPT_INT,
119                 .off1   = td_var_offset(iodepth_batch),
120                 .help   = "Number of IO to submit in one go",
121         },
122         {
123                 .name   = "iodepth_low",
124                 .type   = FIO_OPT_INT,
125                 .off1   = td_var_offset(iodepth_low),
126                 .help   = "Low water mark for queuing depth",
127         },
128         {
129                 .name   = "size",
130                 .type   = FIO_OPT_STR_VAL,
131                 .off1   = td_var_offset(total_file_size),
132                 .help   = "Size of device or file",
133         },
134         {
135                 .name   = "bs",
136                 .type   = FIO_OPT_STR_VAL_INT,
137                 .off1   = td_var_offset(bs[DDIR_READ]),
138                 .off2   = td_var_offset(bs[DDIR_WRITE]),
139                 .help   = "Block size unit",
140                 .def    = "4k",
141         },
142         {
143                 .name   = "bsrange",
144                 .type   = FIO_OPT_RANGE,
145                 .off1   = td_var_offset(min_bs[DDIR_READ]),
146                 .off2   = td_var_offset(max_bs[DDIR_READ]),
147                 .off3   = td_var_offset(min_bs[DDIR_WRITE]),
148                 .off4   = td_var_offset(max_bs[DDIR_WRITE]),
149                 .help   = "Set block size range (in more detail than bs)",
150         },
151         {
152                 .name   = "bs_unaligned",
153                 .type   = FIO_OPT_STR_SET,
154                 .off1   = td_var_offset(bs_unaligned),
155                 .help   = "Don't sector align IO buffer sizes",
156         },
157         {
158                 .name   = "offset",
159                 .type   = FIO_OPT_STR_VAL,
160                 .off1   = td_var_offset(start_offset),
161                 .help   = "Start IO from this offset",
162                 .def    = "0",
163         },
164         {
165                 .name   = "randrepeat",
166                 .type   = FIO_OPT_BOOL,
167                 .off1   = td_var_offset(rand_repeatable),
168                 .help   = "Use repeatable random IO pattern",
169                 .def    = "1",
170         },
171         {
172                 .name   = "norandommap",
173                 .type   = FIO_OPT_STR_SET,
174                 .off1   = td_var_offset(norandommap),
175                 .help   = "Accept potential duplicate random blocks",
176         },
177         {
178                 .name   = "nrfiles",
179                 .type   = FIO_OPT_INT,
180                 .off1   = td_var_offset(nr_files),
181                 .help   = "Split job workload between this number of files",
182                 .def    = "1",
183         },
184         {
185                 .name   = "openfiles",
186                 .type   = FIO_OPT_INT,
187                 .off1   = td_var_offset(open_files),
188                 .help   = "Number of files to keep open at the same time",
189         },
190         {
191                 .name   = "file_service_type",
192                 .type   = FIO_OPT_STR,
193                 .off1   = td_var_offset(file_service_type),
194                 .help   = "How to select which file to service next",
195                 .def    = "roundrobin",
196                 .posval = {
197                           { .ival = "random", .oval = FIO_FSERVICE_RANDOM },
198                           { .ival = "roundrobin", .oval = FIO_FSERVICE_RR },
199                           },
200         },
201         {
202                 .name   = "fsync",
203                 .type   = FIO_OPT_INT,
204                 .off1   = td_var_offset(fsync_blocks),
205                 .help   = "Issue fsync for writes every given number of blocks",
206                 .def    = "0",
207         },
208         {
209                 .name   = "direct",
210                 .type   = FIO_OPT_BOOL,
211                 .off1   = td_var_offset(odirect),
212                 .help   = "Use O_DIRECT IO (negates buffered)",
213                 .def    = "0",
214         },
215         {
216                 .name   = "buffered",
217                 .type   = FIO_OPT_BOOL,
218                 .off1   = td_var_offset(odirect),
219                 .neg    = 1,
220                 .help   = "Use buffered IO (negates direct)",
221                 .def    = "1",
222         },
223         {
224                 .name   = "overwrite",
225                 .type   = FIO_OPT_BOOL,
226                 .off1   = td_var_offset(overwrite),
227                 .help   = "When writing, set whether to overwrite current data",
228                 .def    = "0",
229         },
230         {
231                 .name   = "loops",
232                 .type   = FIO_OPT_INT,
233                 .off1   = td_var_offset(loops),
234                 .help   = "Number of times to run the job",
235                 .def    = "1",
236         },
237         {
238                 .name   = "numjobs",
239                 .type   = FIO_OPT_INT,
240                 .off1   = td_var_offset(numjobs),
241                 .help   = "Duplicate this job this many times",
242                 .def    = "1",
243         },
244         {
245                 .name   = "startdelay",
246                 .type   = FIO_OPT_INT,
247                 .off1   = td_var_offset(start_delay),
248                 .help   = "Only start job when this period has passed",
249                 .def    = "0",
250         },
251         {
252                 .name   = "runtime",
253                 .alias  = "timeout",
254                 .type   = FIO_OPT_STR_VAL_TIME,
255                 .off1   = td_var_offset(timeout),
256                 .help   = "Stop workload when this amount of time has passed",
257                 .def    = "0",
258         },
259         {
260                 .name   = "mem",
261                 .type   = FIO_OPT_STR,
262                 .cb     = str_mem_cb,
263                 .off1   = td_var_offset(mem_type),
264                 .help   = "Backing type for IO buffers",
265                 .def    = "malloc",
266                 .posval = {
267                           { .ival = "malloc", .oval = MEM_MALLOC },
268                           { .ival = "shm", .oval = MEM_SHM },
269 #ifdef FIO_HAVE_HUGETLB
270                           { .ival = "shmhuge", .oval = MEM_SHMHUGE },
271 #endif
272                           { .ival = "mmap", .oval = MEM_MMAP },
273 #ifdef FIO_HAVE_HUGETLB
274                           { .ival = "mmaphuge", .oval = MEM_MMAPHUGE },
275 #endif
276                           },
277         },
278         {
279                 .name   = "verify",
280                 .type   = FIO_OPT_STR,
281                 .off1   = td_var_offset(verify),
282                 .help   = "Verify sum function",
283                 .def    = "0",
284                 .posval = {
285                           { .ival = "0", .oval = VERIFY_NONE },
286                           { .ival = "crc32", .oval = VERIFY_CRC32 },
287                           { .ival = "md5", .oval = VERIFY_MD5 },
288                           },
289         },
290         {
291                 .name   = "write_iolog",
292                 .type   = FIO_OPT_STR_STORE,
293                 .off1   = td_var_offset(write_iolog_file),
294                 .help   = "Store IO pattern to file",
295         },
296         {
297                 .name   = "read_iolog",
298                 .type   = FIO_OPT_STR_STORE,
299                 .off1   = td_var_offset(read_iolog_file),
300                 .help   = "Playback IO pattern from file",
301         },
302         {
303                 .name   = "exec_prerun",
304                 .type   = FIO_OPT_STR_STORE,
305                 .off1   = td_var_offset(exec_prerun),
306                 .help   = "Execute this file prior to running job",
307         },
308         {
309                 .name   = "exec_postrun",
310                 .type   = FIO_OPT_STR_STORE,
311                 .off1   = td_var_offset(exec_postrun),
312                 .help   = "Execute this file after running job",
313         },
314 #ifdef FIO_HAVE_IOSCHED_SWITCH
315         {
316                 .name   = "ioscheduler",
317                 .type   = FIO_OPT_STR_STORE,
318                 .off1   = td_var_offset(ioscheduler),
319                 .help   = "Use this IO scheduler on the backing device",
320         },
321 #endif
322         {
323                 .name   = "zonesize",
324                 .type   = FIO_OPT_STR_VAL,
325                 .off1   = td_var_offset(zone_size),
326                 .help   = "Give size of an IO zone",
327                 .def    = "0",
328         },
329         {
330                 .name   = "zoneskip",
331                 .type   = FIO_OPT_STR_VAL,
332                 .off1   = td_var_offset(zone_skip),
333                 .help   = "Space between IO zones",
334                 .def    = "0",
335         },
336         {
337                 .name   = "lockmem",
338                 .type   = FIO_OPT_STR_VAL,
339                 .cb     = str_lockmem_cb,
340                 .help   = "Lock down this amount of memory",
341                 .def    = "0",
342         },
343         {
344                 .name   = "rwmixcycle",
345                 .type   = FIO_OPT_INT,
346                 .off1   = td_var_offset(rwmixcycle),
347                 .help   = "Cycle period for mixed read/write workloads (msec)",
348                 .def    = "500",
349         },
350         {
351                 .name   = "rwmixread",
352                 .type   = FIO_OPT_INT,
353                 .off1   = td_var_offset(rwmixread),
354                 .maxval = 100,
355                 .help   = "Percentage of mixed workload that is reads",
356                 .def    = "50",
357         },
358         {
359                 .name   = "rwmixwrite",
360                 .type   = FIO_OPT_INT,
361                 .off1   = td_var_offset(rwmixwrite),
362                 .maxval = 100,
363                 .help   = "Percentage of mixed workload that is writes",
364                 .def    = "50",
365         },
366         {
367                 .name   = "nice",
368                 .type   = FIO_OPT_INT,
369                 .off1   = td_var_offset(nice),
370                 .help   = "Set job CPU nice value",
371                 .minval = -19,
372                 .maxval = 20,
373                 .def    = "0",
374         },
375 #ifdef FIO_HAVE_IOPRIO
376         {
377                 .name   = "prio",
378                 .type   = FIO_OPT_INT,
379                 .cb     = str_prio_cb,
380                 .help   = "Set job IO priority value",
381                 .minval = 0,
382                 .maxval = 7,
383         },
384         {
385                 .name   = "prioclass",
386                 .type   = FIO_OPT_INT,
387                 .cb     = str_prioclass_cb,
388                 .help   = "Set job IO priority class",
389                 .minval = 0,
390                 .maxval = 3,
391         },
392 #endif
393         {
394                 .name   = "thinktime",
395                 .type   = FIO_OPT_INT,
396                 .off1   = td_var_offset(thinktime),
397                 .help   = "Idle time between IO buffers (usec)",
398                 .def    = "0",
399         },
400         {
401                 .name   = "thinktime_spin",
402                 .type   = FIO_OPT_INT,
403                 .off1   = td_var_offset(thinktime_spin),
404                 .help   = "Start think time by spinning this amount (usec)",
405                 .def    = "0",
406         },
407         {
408                 .name   = "thinktime_blocks",
409                 .type   = FIO_OPT_INT,
410                 .off1   = td_var_offset(thinktime_blocks),
411                 .help   = "IO buffer period between 'thinktime'",
412                 .def    = "1",
413         },
414         {
415                 .name   = "rate",
416                 .type   = FIO_OPT_INT,
417                 .off1   = td_var_offset(rate),
418                 .help   = "Set bandwidth rate",
419         },
420         {
421                 .name   = "ratemin",
422                 .type   = FIO_OPT_INT,
423                 .off1   = td_var_offset(ratemin),
424                 .help   = "The bottom limit accepted",
425         },
426         {
427                 .name   = "ratecycle",
428                 .type   = FIO_OPT_INT,
429                 .off1   = td_var_offset(ratecycle),
430                 .help   = "Window average for rate limits (msec)",
431                 .def    = "1000",
432         },
433         {
434                 .name   = "invalidate",
435                 .type   = FIO_OPT_BOOL,
436                 .off1   = td_var_offset(invalidate_cache),
437                 .help   = "Invalidate buffer/page cache prior to running job",
438                 .def    = "1",
439         },
440         {
441                 .name   = "sync",
442                 .type   = FIO_OPT_BOOL,
443                 .off1   = td_var_offset(sync_io),
444                 .help   = "Use O_SYNC for buffered writes",
445                 .def    = "0",
446         },
447         {
448                 .name   = "bwavgtime",
449                 .type   = FIO_OPT_INT,
450                 .off1   = td_var_offset(bw_avg_time),
451                 .help   = "Time window over which to calculate bandwidth (msec)",
452                 .def    = "500",
453         },
454         {
455                 .name   = "create_serialize",
456                 .type   = FIO_OPT_BOOL,
457                 .off1   = td_var_offset(create_serialize),
458                 .help   = "Serialize creating of job files",
459                 .def    = "1",
460         },
461         {
462                 .name   = "create_fsync",
463                 .type   = FIO_OPT_BOOL,
464                 .off1   = td_var_offset(create_fsync),
465                 .help   = "Fsync file after creation",
466                 .def    = "1",
467         },
468         {
469                 .name   = "cpuload",
470                 .type   = FIO_OPT_INT,
471                 .off1   = td_var_offset(cpuload),
472                 .help   = "Use this percentage of CPU",
473         },
474         {
475                 .name   = "cpuchunks",
476                 .type   = FIO_OPT_INT,
477                 .off1   = td_var_offset(cpucycle),
478                 .help   = "Length of the CPU burn cycles (usecs)",
479                 .def    = "50000",
480         },
481 #ifdef FIO_HAVE_CPU_AFFINITY
482         {
483                 .name   = "cpumask",
484                 .type   = FIO_OPT_INT,
485                 .cb     = str_cpumask_cb,
486                 .help   = "CPU affinity mask",
487         },
488 #endif
489         {
490                 .name   = "end_fsync",
491                 .type   = FIO_OPT_BOOL,
492                 .off1   = td_var_offset(end_fsync),
493                 .help   = "Include fsync at the end of job",
494                 .def    = "0",
495         },
496         {
497                 .name   = "unlink",
498                 .type   = FIO_OPT_BOOL,
499                 .off1   = td_var_offset(unlink),
500                 .help   = "Unlink created files after job has completed",
501                 .def    = "0",
502         },
503         {
504                 .name   = "exitall",
505                 .type   = FIO_OPT_STR_SET,
506                 .cb     = str_exitall_cb,
507                 .help   = "Terminate all jobs when one exits",
508         },
509         {
510                 .name   = "stonewall",
511                 .type   = FIO_OPT_STR_SET,
512                 .off1   = td_var_offset(stonewall),
513                 .help   = "Insert a hard barrier between this job and previous",
514         },
515         {
516                 .name   = "thread",
517                 .type   = FIO_OPT_STR_SET,
518                 .off1   = td_var_offset(use_thread),
519                 .help   = "Use threads instead of forks",
520         },
521         {
522                 .name   = "write_bw_log",
523                 .type   = FIO_OPT_STR_SET,
524                 .off1   = td_var_offset(write_bw_log),
525                 .help   = "Write log of bandwidth during run",
526         },
527         {
528                 .name   = "write_lat_log",
529                 .type   = FIO_OPT_STR_SET,
530                 .off1   = td_var_offset(write_lat_log),
531                 .help   = "Write log of latency during run",
532         },
533         {
534                 .name   = "hugepage-size",
535                 .type   = FIO_OPT_STR_VAL,
536                 .off1   = td_var_offset(hugepage_size),
537                 .help   = "When using hugepages, specify size of each page",
538                 .def    = __stringify(FIO_HUGE_PAGE),
539         },
540         {
541                 .name   = "group_reporting",
542                 .type   = FIO_OPT_STR_SET,
543                 .off1   = td_var_offset(group_reporting),
544                 .help   = "Do reporting on a per-group basis",
545         },
546         {
547                 .name = NULL,
548         },
549 };
550
551 #define FIO_JOB_OPTS    (sizeof(options) / sizeof(struct fio_option))
552 #define FIO_CMD_OPTS    (16)
553 #define FIO_GETOPT_JOB  (0x89988998)
554
555 /*
556  * Command line options. These will contain the above, plus a few
557  * extra that only pertain to fio itself and not jobs.
558  */
559 static struct option long_options[FIO_JOB_OPTS + FIO_CMD_OPTS] = {
560         {
561                 .name           = "output",
562                 .has_arg        = required_argument,
563                 .val            = 'o',
564         },
565         {
566                 .name           = "timeout",
567                 .has_arg        = required_argument,
568                 .val            = 't',
569         },
570         {
571                 .name           = "latency-log",
572                 .has_arg        = required_argument,
573                 .val            = 'l',
574         },
575         {
576                 .name           = "bandwidth-log",
577                 .has_arg        = required_argument,
578                 .val            = 'b',
579         },
580         {
581                 .name           = "minimal",
582                 .has_arg        = optional_argument,
583                 .val            = 'm',
584         },
585         {
586                 .name           = "version",
587                 .has_arg        = no_argument,
588                 .val            = 'v',
589         },
590         {
591                 .name           = "help",
592                 .has_arg        = no_argument,
593                 .val            = 'h',
594         },
595         {
596                 .name           = "cmdhelp",
597                 .has_arg        = optional_argument,
598                 .val            = 'c',
599         },
600         {
601                 .name           = NULL,
602         },
603 };
604
605 static int def_timeout = 0;
606
607 static char fio_version_string[] = "fio 1.13";
608
609 static char **ini_file;
610 static int max_jobs = MAX_JOBS;
611
612 struct thread_data def_thread;
613 struct thread_data *threads = NULL;
614
615 int exitall_on_terminate = 0;
616 int terse_output = 0;
617 unsigned long long mlock_size = 0;
618 FILE *f_out = NULL;
619 FILE *f_err = NULL;
620
621 static int write_lat_log = 0;
622 int write_bw_log = 0;
623
624 FILE *get_f_out()
625 {
626         return f_out;
627 }
628
629 FILE *get_f_err()
630 {
631         return f_err;
632 }
633
634 /*
635  * Return a free job structure.
636  */
637 static struct thread_data *get_new_job(int global, struct thread_data *parent)
638 {
639         struct thread_data *td;
640
641         if (global)
642                 return &def_thread;
643         if (thread_number >= max_jobs)
644                 return NULL;
645
646         td = &threads[thread_number++];
647         *td = *parent;
648
649         td->thread_number = thread_number;
650         return td;
651 }
652
653 static void put_job(struct thread_data *td)
654 {
655         if (td == &def_thread)
656                 return;
657
658         if (td->error)
659                 fprintf(f_out, "fio: %s\n", td->verror);
660
661         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
662         thread_number--;
663 }
664
665 /*
666  * Lazy way of fixing up options that depend on each other. We could also
667  * define option callback handlers, but this is easier.
668  */
669 static void fixup_options(struct thread_data *td)
670 {
671         if (!td->rwmixread && td->rwmixwrite)
672                 td->rwmixread = 100 - td->rwmixwrite;
673
674         if (td->write_iolog_file && td->read_iolog_file) {
675                 log_err("fio: read iolog overrides write_iolog\n");
676                 free(td->write_iolog_file);
677                 td->write_iolog_file = NULL;
678         }
679
680         if (td->io_ops->flags & FIO_SYNCIO)
681                 td->iodepth = 1;
682         else {
683                 if (!td->iodepth)
684                         td->iodepth = td->open_files;
685         }
686
687         /*
688          * only really works for sequential io for now, and with 1 file
689          */
690         if (td->zone_size && td_random(td) && td->open_files == 1)
691                 td->zone_size = 0;
692
693         /*
694          * Reads can do overwrites, we always need to pre-create the file
695          */
696         if (td_read(td) || td_rw(td))
697                 td->overwrite = 1;
698
699         if (!td->min_bs[DDIR_READ])
700                 td->min_bs[DDIR_READ]= td->bs[DDIR_READ];
701         if (!td->max_bs[DDIR_READ])
702                 td->max_bs[DDIR_READ] = td->bs[DDIR_READ];
703         if (!td->min_bs[DDIR_WRITE])
704                 td->min_bs[DDIR_WRITE]= td->bs[DDIR_WRITE];
705         if (!td->max_bs[DDIR_WRITE])
706                 td->max_bs[DDIR_WRITE] = td->bs[DDIR_WRITE];
707
708         td->rw_min_bs = min(td->min_bs[DDIR_READ], td->min_bs[DDIR_WRITE]);
709
710         if (td_read(td) && !td_rw(td))
711                 td->verify = 0;
712
713         if (td->norandommap && td->verify != VERIFY_NONE) {
714                 log_err("fio: norandommap given, verify disabled\n");
715                 td->verify = VERIFY_NONE;
716         }
717         if (td->bs_unaligned && (td->odirect || td->io_ops->flags & FIO_RAWIO))
718                 log_err("fio: bs_unaligned may not work with raw io\n");
719
720         /*
721          * O_DIRECT and char doesn't mix, clear that flag if necessary.
722          */
723         if (td->filetype == FIO_TYPE_CHAR && td->odirect)
724                 td->odirect = 0;
725
726         /*
727          * thinktime_spin must be less than thinktime
728          */
729         if (td->thinktime_spin > td->thinktime)
730                 td->thinktime_spin = td->thinktime;
731
732         /*
733          * The low water mark cannot be bigger than the iodepth
734          */
735         if (td->iodepth_low > td->iodepth || !td->iodepth_low) {
736                 /*
737                  * syslet work around - if the workload is sequential,
738                  * we want to let the queue drain all the way down to
739                  * avoid seeking between async threads
740                  */
741                 if (!strcmp(td->io_ops->name, "syslet-rw") && !td_random(td))
742                         td->iodepth_low = 1;
743                 else
744                         td->iodepth_low = td->iodepth;
745         }
746
747         /*
748          * If batch number isn't set, default to the same as iodepth
749          */
750         if (td->iodepth_batch > td->iodepth || !td->iodepth_batch)
751                 td->iodepth_batch = td->iodepth;
752
753         if (td->open_files > td->nr_files || !td->open_files)
754                 td->open_files = td->nr_files;
755 }
756
757 /*
758  * This function leaks the buffer
759  */
760 static char *to_kmg(unsigned int val)
761 {
762         char *buf = malloc(32);
763         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
764         char *p = post;
765
766         do {
767                 if (val & 1023)
768                         break;
769
770                 val >>= 10;
771                 p++;
772         } while (*p);
773
774         snprintf(buf, 31, "%u%c", val, *p);
775         return buf;
776 }
777
778 /* External engines are specified by "external:name.o") */
779 static const char *get_engine_name(const char *str)
780 {
781         char *p = strstr(str, ":");
782
783         if (!p)
784                 return str;
785
786         p++;
787         strip_blank_front(&p);
788         strip_blank_end(p);
789         return p;
790 }
791
792 /*
793  * Adds a job to the list of things todo. Sanitizes the various options
794  * to make sure we don't have conflicts, and initializes various
795  * members of td.
796  */
797 static int add_job(struct thread_data *td, const char *jobname, int job_add_num)
798 {
799         const char *ddir_str[] = { NULL, "read", "write", "rw", NULL,
800                                    "randread", "randwrite", "randrw" };
801         struct stat sb;
802         int numjobs, i;
803         struct fio_file *f;
804         const char *engine;
805
806         /*
807          * the def_thread is just for options, it's not a real job
808          */
809         if (td == &def_thread)
810                 return 0;
811
812         engine = get_engine_name(td->ioengine);
813         td->io_ops = load_ioengine(td, engine);
814         if (!td->io_ops) {
815                 log_err("fio: failed to load engine %s\n", engine);
816                 return 1;
817         }
818
819         if (td->odirect)
820                 td->io_ops->flags |= FIO_RAWIO;
821
822         if (!td->filename)
823                 td->filename = strdup(jobname);
824
825         td->filetype = FIO_TYPE_FILE;
826         if (!lstat(td->filename, &sb)) {
827                 if (S_ISBLK(sb.st_mode))
828                         td->filetype = FIO_TYPE_BD;
829                 else if (S_ISCHR(sb.st_mode))
830                         td->filetype = FIO_TYPE_CHAR;
831         }
832
833         fixup_options(td);
834
835         if (td->filename)
836                 td->nr_uniq_files = 1;
837         else
838                 td->nr_uniq_files = td->open_files;
839
840         if (td->filetype == FIO_TYPE_FILE || td->filename) {
841                 char tmp[PATH_MAX];
842                 int len = 0;
843
844                 if (td->directory && td->directory[0] != '\0') {
845                         if (lstat(td->directory, &sb) < 0) {
846                                 log_err("fio: %s is not a directory\n", td->directory);
847                                 td_verror(td, errno, "lstat");
848                                 return 1;
849                         }
850                         if (!S_ISDIR(sb.st_mode)) {
851                                 log_err("fio: %s is not a directory\n", td->directory);
852                                 return 1;
853                         }
854                         len = sprintf(tmp, "%s/", td->directory);
855                 }
856
857                 td->files = malloc(sizeof(struct fio_file) * td->open_files);
858
859                 for_each_file(td, f, i) {
860                         memset(f, 0, sizeof(*f));
861                         f->fd = -1;
862
863                         if (td->filename)
864                                 sprintf(tmp + len, "%s", td->filename);
865                         else
866                                 sprintf(tmp + len, "%s.%d.%d", jobname, td->thread_number, i);
867                         f->file_name = strdup(tmp);
868                 }
869         } else {
870                 td->open_files = td->nr_files = 1;
871                 td->files = malloc(sizeof(struct fio_file));
872                 f = &td->files[0];
873
874                 memset(f, 0, sizeof(*f));
875                 f->fd = -1;
876                 f->file_name = strdup(jobname);
877         }
878
879         for_each_file(td, f, i) {
880                 f->file_size = td->total_file_size / td->nr_files;
881                 f->file_offset = td->start_offset;
882         }
883                 
884         td->mutex = fio_sem_init(0);
885
886         td->ts.clat_stat[0].min_val = td->ts.clat_stat[1].min_val = ULONG_MAX;
887         td->ts.slat_stat[0].min_val = td->ts.slat_stat[1].min_val = ULONG_MAX;
888         td->ts.bw_stat[0].min_val = td->ts.bw_stat[1].min_val = ULONG_MAX;
889
890         if (td->stonewall && td->thread_number > 1)
891                 groupid++;
892
893         td->groupid = groupid;
894
895         if (setup_rate(td))
896                 goto err;
897
898         if (td->write_lat_log) {
899                 setup_log(&td->ts.slat_log);
900                 setup_log(&td->ts.clat_log);
901         }
902         if (td->write_bw_log)
903                 setup_log(&td->ts.bw_log);
904
905         if (!td->name)
906                 td->name = strdup(jobname);
907
908         if (!terse_output) {
909                 if (!job_add_num) {
910                         if (!strcmp(td->io_ops->name, "cpuio"))
911                                 fprintf(f_out, "%s: ioengine=cpu, cpuload=%u, cpucycle=%u\n", td->name, td->cpuload, td->cpucycle);
912                         else {
913                                 char *c1, *c2, *c3, *c4;
914
915                                 c1 = to_kmg(td->min_bs[DDIR_READ]);
916                                 c2 = to_kmg(td->max_bs[DDIR_READ]);
917                                 c3 = to_kmg(td->min_bs[DDIR_WRITE]);
918                                 c4 = to_kmg(td->max_bs[DDIR_WRITE]);
919
920                                 fprintf(f_out, "%s: (g=%d): rw=%s, bs=%s-%s/%s-%s, ioengine=%s, iodepth=%u\n", td->name, td->groupid, ddir_str[td->td_ddir], c1, c2, c3, c4, td->io_ops->name, td->iodepth);
921
922                                 free(c1);
923                                 free(c2);
924                                 free(c3);
925                                 free(c4);
926                         }
927                 } else if (job_add_num == 1)
928                         fprintf(f_out, "...\n");
929         }
930
931         /*
932          * recurse add identical jobs, clear numjobs and stonewall options
933          * as they don't apply to sub-jobs
934          */
935         numjobs = td->numjobs;
936         while (--numjobs) {
937                 struct thread_data *td_new = get_new_job(0, td);
938
939                 if (!td_new)
940                         goto err;
941
942                 td_new->numjobs = 1;
943                 td_new->stonewall = 0;
944                 job_add_num = numjobs - 1;
945
946                 if (add_job(td_new, jobname, job_add_num))
947                         goto err;
948         }
949         return 0;
950 err:
951         put_job(td);
952         return -1;
953 }
954
955 /*
956  * Initialize the various random states we need (random io, block size ranges,
957  * read/write mix, etc).
958  */
959 int init_random_state(struct thread_data *td)
960 {
961         unsigned long seeds[5];
962         int fd, num_maps, blocks, i;
963         struct fio_file *f;
964
965         if (td->io_ops->flags & FIO_DISKLESSIO)
966                 return 0;
967
968         fd = open("/dev/urandom", O_RDONLY);
969         if (fd == -1) {
970                 td_verror(td, errno, "open");
971                 return 1;
972         }
973
974         if (read(fd, seeds, sizeof(seeds)) < (int) sizeof(seeds)) {
975                 td_verror(td, EIO, "read");
976                 close(fd);
977                 return 1;
978         }
979
980         close(fd);
981
982         os_random_seed(seeds[0], &td->bsrange_state);
983         os_random_seed(seeds[1], &td->verify_state);
984         os_random_seed(seeds[2], &td->rwmix_state);
985
986         if (td->file_service_type == FIO_FSERVICE_RANDOM)
987                 os_random_seed(seeds[3], &td->next_file_state);
988
989         if (!td_random(td))
990                 return 0;
991
992         if (td->rand_repeatable)
993                 seeds[4] = FIO_RANDSEED * td->thread_number;
994
995         if (!td->norandommap) {
996                 for_each_file(td, f, i) {
997                         blocks = (f->real_file_size + td->rw_min_bs - 1) / td->rw_min_bs;
998                         num_maps = (blocks + BLOCKS_PER_MAP-1)/ BLOCKS_PER_MAP;
999                         f->file_map = malloc(num_maps * sizeof(long));
1000                         if (!f->file_map) {
1001                                 log_err("fio: failed allocating random map. If running a large number of jobs, try the 'norandommap' option\n");
1002                                 return 1;
1003                         }
1004                         f->num_maps = num_maps;
1005                         memset(f->file_map, 0, num_maps * sizeof(long));
1006                 }
1007         }
1008
1009         os_random_seed(seeds[4], &td->random_state);
1010         return 0;
1011 }
1012
1013 static void fill_cpu_mask(os_cpu_mask_t cpumask, int cpu)
1014 {
1015 #ifdef FIO_HAVE_CPU_AFFINITY
1016         unsigned int i;
1017
1018         CPU_ZERO(&cpumask);
1019
1020         for (i = 0; i < sizeof(int) * 8; i++) {
1021                 if ((1 << i) & cpu)
1022                         CPU_SET(i, &cpumask);
1023         }
1024 #endif
1025 }
1026
1027 static int is_empty_or_comment(char *line)
1028 {
1029         unsigned int i;
1030
1031         for (i = 0; i < strlen(line); i++) {
1032                 if (line[i] == ';')
1033                         return 1;
1034                 if (line[i] == '#')
1035                         return 1;
1036                 if (!isspace(line[i]) && !iscntrl(line[i]))
1037                         return 0;
1038         }
1039
1040         return 1;
1041 }
1042
1043 /*
1044  * Check if mmap/mmaphuge has a :/foo/bar/file at the end. If so, return that.
1045  */
1046 static char *get_mmap_file(const char *str)
1047 {
1048         char *p = strstr(str, ":");
1049
1050         if (!p)
1051                 return NULL;
1052
1053         p++;
1054         strip_blank_front(&p);
1055         strip_blank_end(p);
1056         return strdup(p);
1057 }
1058
1059 static int str_mem_cb(void *data, const char *mem)
1060 {
1061         struct thread_data *td = data;
1062
1063         if (td->mem_type == MEM_MMAPHUGE || td->mem_type == MEM_MMAP) {
1064                 td->mmapfile = get_mmap_file(mem);
1065                 if (td->mem_type == MEM_MMAPHUGE && !td->mmapfile) {
1066                         log_err("fio: mmaphuge:/path/to/file\n");
1067                         return 1;
1068                 }
1069         }
1070
1071         return 0;
1072 }
1073
1074 static int str_lockmem_cb(void fio_unused *data, unsigned long *val)
1075 {
1076         mlock_size = *val;
1077         return 0;
1078 }
1079
1080 #ifdef FIO_HAVE_IOPRIO
1081 static int str_prioclass_cb(void *data, unsigned int *val)
1082 {
1083         struct thread_data *td = data;
1084
1085         td->ioprio |= *val << IOPRIO_CLASS_SHIFT;
1086         return 0;
1087 }
1088
1089 static int str_prio_cb(void *data, unsigned int *val)
1090 {
1091         struct thread_data *td = data;
1092
1093         td->ioprio |= *val;
1094         return 0;
1095 }
1096 #endif
1097
1098 static int str_exitall_cb(void)
1099 {
1100         exitall_on_terminate = 1;
1101         return 0;
1102 }
1103
1104 static int str_cpumask_cb(void *data, unsigned int *val)
1105 {
1106         struct thread_data *td = data;
1107
1108         fill_cpu_mask(td->cpumask, *val);
1109         return 0;
1110 }
1111
1112 /*
1113  * This is our [ini] type file parser.
1114  */
1115 static int parse_jobs_ini(char *file, int stonewall_flag)
1116 {
1117         unsigned int global;
1118         struct thread_data *td;
1119         char *string, *name;
1120         fpos_t off;
1121         FILE *f;
1122         char *p;
1123         int ret = 0, stonewall;
1124
1125         f = fopen(file, "r");
1126         if (!f) {
1127                 perror("fopen job file");
1128                 return 1;
1129         }
1130
1131         string = malloc(4096);
1132         name = malloc(256);
1133         memset(name, 0, 256);
1134
1135         stonewall = stonewall_flag;
1136         do {
1137                 p = fgets(string, 4095, f);
1138                 if (!p)
1139                         break;
1140                 if (is_empty_or_comment(p))
1141                         continue;
1142                 if (sscanf(p, "[%255s]", name) != 1)
1143                         continue;
1144
1145                 global = !strncmp(name, "global", 6);
1146
1147                 name[strlen(name) - 1] = '\0';
1148
1149                 td = get_new_job(global, &def_thread);
1150                 if (!td) {
1151                         ret = 1;
1152                         break;
1153                 }
1154
1155                 /*
1156                  * Seperate multiple job files by a stonewall
1157                  */
1158                 if (!global && stonewall) {
1159                         td->stonewall = stonewall;
1160                         stonewall = 0;
1161                 }
1162
1163                 fgetpos(f, &off);
1164                 while ((p = fgets(string, 4096, f)) != NULL) {
1165                         if (is_empty_or_comment(p))
1166                                 continue;
1167
1168                         strip_blank_front(&p);
1169
1170                         if (p[0] == '[')
1171                                 break;
1172
1173                         strip_blank_end(p);
1174
1175                         fgetpos(f, &off);
1176
1177                         /*
1178                          * Don't break here, continue parsing options so we
1179                          * dump all the bad ones. Makes trial/error fixups
1180                          * easier on the user.
1181                          */
1182                         ret |= parse_option(p, options, td);
1183                 }
1184
1185                 if (!ret) {
1186                         fsetpos(f, &off);
1187                         ret = add_job(td, name, 0);
1188                 } else {
1189                         log_err("fio: job %s dropped\n", name);
1190                         put_job(td);
1191                 }
1192         } while (!ret);
1193
1194         free(string);
1195         free(name);
1196         fclose(f);
1197         return ret;
1198 }
1199
1200 static int fill_def_thread(void)
1201 {
1202         memset(&def_thread, 0, sizeof(def_thread));
1203
1204         if (fio_getaffinity(getpid(), &def_thread.cpumask) == -1) {
1205                 perror("sched_getaffinity");
1206                 return 1;
1207         }
1208
1209         /*
1210          * fill default options
1211          */
1212         fill_default_options(&def_thread, options);
1213
1214         def_thread.timeout = def_timeout;
1215         def_thread.write_bw_log = write_bw_log;
1216         def_thread.write_lat_log = write_lat_log;
1217
1218 #ifdef FIO_HAVE_DISK_UTIL
1219         def_thread.do_disk_util = 1;
1220 #endif
1221
1222         return 0;
1223 }
1224
1225 static void usage(void)
1226 {
1227         printf("%s\n", fio_version_string);
1228         printf("\t--output\tWrite output to file\n");
1229         printf("\t--timeout\tRuntime in seconds\n");
1230         printf("\t--latency-log\tGenerate per-job latency logs\n");
1231         printf("\t--bandwidth-log\tGenerate per-job bandwidth logs\n");
1232         printf("\t--minimal\tMinimal (terse) output\n");
1233         printf("\t--version\tPrint version info and exit\n");
1234         printf("\t--help\t\tPrint this page\n");
1235         printf("\t--cmdhelp=cmd\tPrint command help, \"all\" for all of them\n");
1236 }
1237
1238 static int parse_cmd_line(int argc, char *argv[])
1239 {
1240         struct thread_data *td = NULL;
1241         int c, ini_idx = 0, lidx, ret, dont_add_job = 0;
1242
1243         while ((c = getopt_long_only(argc, argv, "", long_options, &lidx)) != -1) {
1244                 switch (c) {
1245                 case 't':
1246                         def_timeout = atoi(optarg);
1247                         break;
1248                 case 'l':
1249                         write_lat_log = 1;
1250                         break;
1251                 case 'w':
1252                         write_bw_log = 1;
1253                         break;
1254                 case 'o':
1255                         f_out = fopen(optarg, "w+");
1256                         if (!f_out) {
1257                                 perror("fopen output");
1258                                 exit(1);
1259                         }
1260                         f_err = f_out;
1261                         break;
1262                 case 'm':
1263                         terse_output = 1;
1264                         break;
1265                 case 'h':
1266                         usage();
1267                         exit(0);
1268                 case 'c':
1269                         ret = show_cmd_help(options, optarg);
1270                         exit(ret);
1271                 case 'v':
1272                         printf("%s\n", fio_version_string);
1273                         exit(0);
1274                 case FIO_GETOPT_JOB: {
1275                         const char *opt = long_options[lidx].name;
1276                         char *val = optarg;
1277
1278                         if (!strncmp(opt, "name", 4) && td) {
1279                                 ret = add_job(td, td->name ?: "fio", 0);
1280                                 if (ret) {
1281                                         put_job(td);
1282                                         return 0;
1283                                 }
1284                                 td = NULL;
1285                         }
1286                         if (!td) {
1287                                 int global = !strncmp(val, "global", 6);
1288
1289                                 td = get_new_job(global, &def_thread);
1290                                 if (!td)
1291                                         return 0;
1292                         }
1293
1294                         ret = parse_cmd_option(opt, val, options, td);
1295                         if (ret)
1296                                 dont_add_job = 1;
1297                         break;
1298                 }
1299                 default:
1300                         break;
1301                 }
1302         }
1303
1304         if (td) {
1305                 if (dont_add_job)
1306                         put_job(td);
1307                 else {
1308                         ret = add_job(td, td->name ?: "fio", 0);
1309                         if (ret)
1310                                 put_job(td);
1311                 }
1312         }
1313
1314         while (optind < argc) {
1315                 ini_idx++;
1316                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
1317                 ini_file[ini_idx - 1] = strdup(argv[optind]);
1318                 optind++;
1319         }
1320
1321         return ini_idx;
1322 }
1323
1324 static void free_shm(void)
1325 {
1326         struct shmid_ds sbuf;
1327
1328         if (threads) {
1329                 shmdt((void *) threads);
1330                 threads = NULL;
1331                 shmctl(shm_id, IPC_RMID, &sbuf);
1332         }
1333 }
1334
1335 /*
1336  * The thread area is shared between the main process and the job
1337  * threads/processes. So setup a shared memory segment that will hold
1338  * all the job info.
1339  */
1340 static int setup_thread_area(void)
1341 {
1342         /*
1343          * 1024 is too much on some machines, scale max_jobs if
1344          * we get a failure that looks like too large a shm segment
1345          */
1346         do {
1347                 size_t size = max_jobs * sizeof(struct thread_data);
1348
1349                 shm_id = shmget(0, size, IPC_CREAT | 0600);
1350                 if (shm_id != -1)
1351                         break;
1352                 if (errno != EINVAL) {
1353                         perror("shmget");
1354                         break;
1355                 }
1356
1357                 max_jobs >>= 1;
1358         } while (max_jobs);
1359
1360         if (shm_id == -1)
1361                 return 1;
1362
1363         threads = shmat(shm_id, NULL, 0);
1364         if (threads == (void *) -1) {
1365                 perror("shmat");
1366                 return 1;
1367         }
1368
1369         atexit(free_shm);
1370         return 0;
1371 }
1372
1373 /*
1374  * Copy the fio options into the long options map, so we mirror
1375  * job and cmd line options.
1376  */
1377 static void dupe_job_options(void)
1378 {
1379         struct fio_option *o;
1380         unsigned int i;
1381
1382         i = 0;
1383         while (long_options[i].name)
1384                 i++;
1385
1386         o = &options[0];
1387         while (o->name) {
1388                 long_options[i].name = o->name;
1389                 long_options[i].val = FIO_GETOPT_JOB;
1390                 if (o->type == FIO_OPT_STR_SET)
1391                         long_options[i].has_arg = no_argument;
1392                 else
1393                         long_options[i].has_arg = required_argument;
1394
1395                 i++;
1396                 o++;
1397                 assert(i < FIO_JOB_OPTS + FIO_CMD_OPTS);
1398         }
1399 }
1400
1401 int parse_options(int argc, char *argv[])
1402 {
1403         int job_files, i;
1404
1405         f_out = stdout;
1406         f_err = stderr;
1407
1408         options_init(options);
1409
1410         dupe_job_options();
1411
1412         if (setup_thread_area())
1413                 return 1;
1414         if (fill_def_thread())
1415                 return 1;
1416
1417         job_files = parse_cmd_line(argc, argv);
1418
1419         for (i = 0; i < job_files; i++) {
1420                 if (fill_def_thread())
1421                         return 1;
1422                 if (parse_jobs_ini(ini_file[i], i))
1423                         return 1;
1424                 free(ini_file[i]);
1425         }
1426
1427         free(ini_file);
1428
1429         if (!thread_number) {
1430                 log_err("No jobs defined(s)\n");
1431                 return 1;
1432         }
1433
1434         return 0;
1435 }