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