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