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