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