cgroup cleanups
[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 <sys/ipc.h>
13 #include <sys/shm.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16
17 #include "fio.h"
18 #include "parse.h"
19 #include "smalloc.h"
20 #include "filehash.h"
21 #include "verify.h"
22
23 static char fio_version_string[] = "fio 1.35";
24
25 #define FIO_RANDSEED            (0xb1899bedUL)
26
27 static char **ini_file;
28 static int max_jobs = MAX_JOBS;
29 static int dump_cmdline;
30
31 static struct thread_data def_thread;
32 struct thread_data *threads = NULL;
33
34 int exitall_on_terminate = 0;
35 int terse_output = 0;
36 int eta_print;
37 unsigned long long mlock_size = 0;
38 FILE *f_out = NULL;
39 FILE *f_err = NULL;
40 char *job_section = NULL;
41
42 int write_bw_log = 0;
43 int read_only = 0;
44
45 static int def_timeout;
46 static int write_lat_log;
47
48 static int prev_group_jobs;
49
50 unsigned long fio_debug = 0;
51 unsigned int fio_debug_jobno = -1;
52 unsigned int *fio_debug_jobp = NULL;
53
54 /*
55  * Command line options. These will contain the above, plus a few
56  * extra that only pertain to fio itself and not jobs.
57  */
58 static struct option l_opts[FIO_NR_OPTIONS] = {
59         {
60                 .name           = "output",
61                 .has_arg        = required_argument,
62                 .val            = 'o',
63         },
64         {
65                 .name           = "timeout",
66                 .has_arg        = required_argument,
67                 .val            = 't',
68         },
69         {
70                 .name           = "latency-log",
71                 .has_arg        = required_argument,
72                 .val            = 'l',
73         },
74         {
75                 .name           = "bandwidth-log",
76                 .has_arg        = required_argument,
77                 .val            = 'b',
78         },
79         {
80                 .name           = "minimal",
81                 .has_arg        = optional_argument,
82                 .val            = 'm',
83         },
84         {
85                 .name           = "version",
86                 .has_arg        = no_argument,
87                 .val            = 'v',
88         },
89         {
90                 .name           = "help",
91                 .has_arg        = no_argument,
92                 .val            = 'h',
93         },
94         {
95                 .name           = "cmdhelp",
96                 .has_arg        = optional_argument,
97                 .val            = 'c',
98         },
99         {
100                 .name           = "showcmd",
101                 .has_arg        = no_argument,
102                 .val            = 's',
103         },
104         {
105                 .name           = "readonly",
106                 .has_arg        = no_argument,
107                 .val            = 'r',
108         },
109         {
110                 .name           = "eta",
111                 .has_arg        = required_argument,
112                 .val            = 'e',
113         },
114         {
115                 .name           = "debug",
116                 .has_arg        = required_argument,
117                 .val            = 'd',
118         },
119         {
120                 .name           = "section",
121                 .has_arg        = required_argument,
122                 .val            = 'x',
123         },
124         {
125                 .name           = "alloc-size",
126                 .has_arg        = required_argument,
127                 .val            = 'a',
128         },
129         {
130                 .name           = "profile",
131                 .has_arg        = required_argument,
132                 .val            = 'p',
133         },
134         {
135                 .name           = NULL,
136         },
137 };
138
139 static const char *tiobench_opts[] = {
140         "buffered=0", "size=4*1024*$mb_memory", "bs=4k", "timeout=600",
141         "numjobs=4", "group_reporting", "thread", "overwrite=1",
142         "filename=.fio.tio.1:.fio.tio.2:.fio.tio.3:.fio.tio.4",
143         "name=seqwrite", "rw=write", "end_fsync=1",
144         "name=randwrite", "stonewall", "rw=randwrite", "end_fsync=1",
145         "name=seqread", "stonewall", "rw=read",
146         "name=randread", "stonewall", "rw=randread", NULL,
147 };
148
149 static const char **fio_prof_strings[PROFILE_END] = {
150         NULL,
151         tiobench_opts,
152 };
153
154 static const char *profiles[PROFILE_END] = {
155         "none",
156         "tiobench",
157 };
158
159 FILE *get_f_out()
160 {
161         return f_out;
162 }
163
164 FILE *get_f_err()
165 {
166         return f_err;
167 }
168
169 /*
170  * Return a free job structure.
171  */
172 static struct thread_data *get_new_job(int global, struct thread_data *parent)
173 {
174         struct thread_data *td;
175
176         if (global)
177                 return &def_thread;
178         if (thread_number >= max_jobs)
179                 return NULL;
180
181         td = &threads[thread_number++];
182         *td = *parent;
183
184         dup_files(td, parent);
185         options_mem_dupe(td);
186
187         td->thread_number = thread_number;
188         return td;
189 }
190
191 static void put_job(struct thread_data *td)
192 {
193         if (td == &def_thread)
194                 return;
195
196         if (td->error)
197                 log_info("fio: %s\n", td->verror);
198
199         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
200         thread_number--;
201 }
202
203 static int __setup_rate(struct thread_data *td, enum fio_ddir ddir)
204 {
205         unsigned int bs = td->o.min_bs[ddir];
206         unsigned long long rate;
207         unsigned long ios_per_msec;
208
209         if (td->o.rate[ddir]) {
210                 rate = td->o.rate[ddir];
211                 ios_per_msec = (rate * 1000LL) / bs;
212         } else
213                 ios_per_msec = td->o.rate_iops[ddir] * 1000UL;
214
215         if (!ios_per_msec) {
216                 log_err("rate lower than supported\n");
217                 return -1;
218         }
219
220         td->rate_usec_cycle[ddir] = 1000000000ULL / ios_per_msec;
221         td->rate_pending_usleep[ddir] = 0;
222         return 0;
223 }
224
225 static int setup_rate(struct thread_data *td)
226 {
227         int ret = 0;
228
229         if (td->o.rate[DDIR_READ] || td->o.rate_iops[DDIR_READ])
230                 ret = __setup_rate(td, DDIR_READ);
231         if (td->o.rate[DDIR_WRITE] || td->o.rate_iops[DDIR_WRITE])
232                 ret |= __setup_rate(td, DDIR_WRITE);
233
234         return ret;
235 }
236
237 static int fixed_block_size(struct thread_options *o)
238 {
239         return o->min_bs[DDIR_READ] == o->max_bs[DDIR_READ] &&
240                 o->min_bs[DDIR_WRITE] == o->max_bs[DDIR_WRITE] &&
241                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_WRITE];
242 }
243
244 /*
245  * Lazy way of fixing up options that depend on each other. We could also
246  * define option callback handlers, but this is easier.
247  */
248 static int fixup_options(struct thread_data *td)
249 {
250         struct thread_options *o = &td->o;
251
252 #ifndef FIO_HAVE_PSHARED_MUTEX
253         if (!td->o.use_thread) {
254                 log_info("fio: this platform does not support process shared"
255                          " mutexes, forcing use of threads. Use the 'thread'"
256                          " option to get rid of this warning.\n");
257                 td->o.use_thread = 1;
258         }
259 #endif
260
261         if (o->write_iolog_file && o->read_iolog_file) {
262                 log_err("fio: read iolog overrides write_iolog\n");
263                 free(o->write_iolog_file);
264                 o->write_iolog_file = NULL;
265         }
266
267         /*
268          * only really works for sequential io for now, and with 1 file
269          */
270         if (o->zone_size && td_random(td) && o->open_files == 1)
271                 o->zone_size = 0;
272
273         /*
274          * Reads can do overwrites, we always need to pre-create the file
275          */
276         if (td_read(td) || td_rw(td))
277                 o->overwrite = 1;
278
279         if (!o->min_bs[DDIR_READ])
280                 o->min_bs[DDIR_READ] = o->bs[DDIR_READ];
281         if (!o->max_bs[DDIR_READ])
282                 o->max_bs[DDIR_READ] = o->bs[DDIR_READ];
283         if (!o->min_bs[DDIR_WRITE])
284                 o->min_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
285         if (!o->max_bs[DDIR_WRITE])
286                 o->max_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
287
288         o->rw_min_bs = min(o->min_bs[DDIR_READ], o->min_bs[DDIR_WRITE]);
289
290         /*
291          * For random IO, allow blockalign offset other than min_bs.
292          */
293         if (!o->ba[DDIR_READ] || !td_random(td))
294                 o->ba[DDIR_READ] = o->min_bs[DDIR_READ];
295         if (!o->ba[DDIR_WRITE] || !td_random(td))
296                 o->ba[DDIR_WRITE] = o->min_bs[DDIR_WRITE];
297
298         if ((o->ba[DDIR_READ] != o->min_bs[DDIR_READ] ||
299             o->ba[DDIR_WRITE] != o->min_bs[DDIR_WRITE]) &&
300             !td->o.norandommap) {
301                 log_err("fio: Any use of blockalign= turns off randommap\n");
302                 td->o.norandommap = 1;
303         }
304
305         if (!o->file_size_high)
306                 o->file_size_high = o->file_size_low;
307
308         if (o->norandommap && o->verify != VERIFY_NONE
309             && !fixed_block_size(o))  {
310                 log_err("fio: norandommap given for variable block sizes, "
311                         "verify disabled\n");
312                 o->verify = VERIFY_NONE;
313         }
314         if (o->bs_unaligned && (o->odirect || td->io_ops->flags & FIO_RAWIO))
315                 log_err("fio: bs_unaligned may not work with raw io\n");
316
317         /*
318          * thinktime_spin must be less than thinktime
319          */
320         if (o->thinktime_spin > o->thinktime)
321                 o->thinktime_spin = o->thinktime;
322
323         /*
324          * The low water mark cannot be bigger than the iodepth
325          */
326         if (o->iodepth_low > o->iodepth || !o->iodepth_low) {
327                 /*
328                  * syslet work around - if the workload is sequential,
329                  * we want to let the queue drain all the way down to
330                  * avoid seeking between async threads
331                  */
332                 if (!strcmp(td->io_ops->name, "syslet-rw") && !td_random(td))
333                         o->iodepth_low = 1;
334                 else
335                         o->iodepth_low = o->iodepth;
336         }
337
338         /*
339          * If batch number isn't set, default to the same as iodepth
340          */
341         if (o->iodepth_batch > o->iodepth || !o->iodepth_batch)
342                 o->iodepth_batch = o->iodepth;
343
344         if (o->nr_files > td->files_index)
345                 o->nr_files = td->files_index;
346
347         if (o->open_files > o->nr_files || !o->open_files)
348                 o->open_files = o->nr_files;
349
350         if (((o->rate[0] + o->rate[1]) && (o->rate_iops[0] + o->rate_iops[1]))||
351             ((o->ratemin[0] + o->ratemin[1]) && (o->rate_iops_min[0] +
352                 o->rate_iops_min[1]))) {
353                 log_err("fio: rate and rate_iops are mutually exclusive\n");
354                 return 1;
355         }
356         if ((o->rate[0] < o->ratemin[0]) || (o->rate[1] < o->ratemin[1]) ||
357             (o->rate_iops[0] < o->rate_iops_min[0]) ||
358             (o->rate_iops[1] < o->rate_iops_min[1])) {
359                 log_err("fio: minimum rate exceeds rate\n");
360                 return 1;
361         }
362
363         if (!o->timeout && o->time_based) {
364                 log_err("fio: time_based requires a runtime/timeout setting\n");
365                 o->time_based = 0;
366         }
367
368         if (o->fill_device && !o->size)
369                 o->size = -1ULL;
370
371         if (td_rw(td) && td->o.verify != VERIFY_NONE)
372                 log_info("fio: mixed read/write workload with verify. May not "
373                  "work as expected, unless you pre-populated the file\n");
374
375         if (td->o.verify != VERIFY_NONE)
376                 td->o.refill_buffers = 1;
377
378         if (td->o.pre_read) {
379                 td->o.invalidate_cache = 0;
380                 if (td->io_ops->flags & FIO_PIPEIO)
381                         log_info("fio: cannot pre-read files with an IO engine"
382                                  " that isn't seekable. Pre-read disabled.\n");
383         }
384
385         return 0;
386 }
387
388 /*
389  * This function leaks the buffer
390  */
391 static char *to_kmg(unsigned int val)
392 {
393         char *buf = malloc(32);
394         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
395         char *p = post;
396
397         do {
398                 if (val & 1023)
399                         break;
400
401                 val >>= 10;
402                 p++;
403         } while (*p);
404
405         snprintf(buf, 31, "%u%c", val, *p);
406         return buf;
407 }
408
409 /* External engines are specified by "external:name.o") */
410 static const char *get_engine_name(const char *str)
411 {
412         char *p = strstr(str, ":");
413
414         if (!p)
415                 return str;
416
417         p++;
418         strip_blank_front(&p);
419         strip_blank_end(p);
420         return p;
421 }
422
423 static int exists_and_not_file(const char *filename)
424 {
425         struct stat sb;
426
427         if (lstat(filename, &sb) == -1)
428                 return 0;
429
430         if (S_ISREG(sb.st_mode))
431                 return 0;
432
433         return 1;
434 }
435
436 void td_fill_rand_seeds(struct thread_data *td)
437 {
438         os_random_seed(td->rand_seeds[0], &td->bsrange_state);
439         os_random_seed(td->rand_seeds[1], &td->verify_state);
440         os_random_seed(td->rand_seeds[2], &td->rwmix_state);
441
442         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
443                 os_random_seed(td->rand_seeds[3], &td->next_file_state);
444
445         os_random_seed(td->rand_seeds[5], &td->file_size_state);
446
447         if (!td_random(td))
448                 return;
449
450         if (td->o.rand_repeatable)
451                 td->rand_seeds[4] = FIO_RANDSEED * td->thread_number;
452
453         os_random_seed(td->rand_seeds[4], &td->random_state);
454 }
455
456 /*
457  * Initialize the various random states we need (random io, block size ranges,
458  * read/write mix, etc).
459  */
460 static int init_random_state(struct thread_data *td)
461 {
462         int fd;
463
464         fd = open("/dev/urandom", O_RDONLY);
465         if (fd == -1) {
466                 td_verror(td, errno, "open");
467                 return 1;
468         }
469
470         if (read(fd, td->rand_seeds, sizeof(td->rand_seeds)) <
471             (int) sizeof(td->rand_seeds)) {
472                 td_verror(td, EIO, "read");
473                 close(fd);
474                 return 1;
475         }
476
477         close(fd);
478         td_fill_rand_seeds(td);
479         return 0;
480 }
481
482 /*
483  * Adds a job to the list of things todo. Sanitizes the various options
484  * to make sure we don't have conflicts, and initializes various
485  * members of td.
486  */
487 static int add_job(struct thread_data *td, const char *jobname, int job_add_num)
488 {
489         const char *ddir_str[] = { NULL, "read", "write", "rw", NULL,
490                                    "randread", "randwrite", "randrw" };
491         unsigned int i;
492         const char *engine;
493         char fname[PATH_MAX];
494         int numjobs, file_alloced;
495
496         /*
497          * the def_thread is just for options, it's not a real job
498          */
499         if (td == &def_thread)
500                 return 0;
501
502         /*
503          * if we are just dumping the output command line, don't add the job
504          */
505         if (dump_cmdline) {
506                 put_job(td);
507                 return 0;
508         }
509
510         engine = get_engine_name(td->o.ioengine);
511         td->io_ops = load_ioengine(td, engine);
512         if (!td->io_ops) {
513                 log_err("fio: failed to load engine %s\n", engine);
514                 goto err;
515         }
516
517         if (td->o.use_thread)
518                 nr_thread++;
519         else
520                 nr_process++;
521
522         if (td->o.odirect)
523                 td->io_ops->flags |= FIO_RAWIO;
524
525         file_alloced = 0;
526         if (!td->o.filename && !td->files_index && !td->o.read_iolog_file) {
527                 file_alloced = 1;
528
529                 if (td->o.nr_files == 1 && exists_and_not_file(jobname))
530                         add_file(td, jobname);
531                 else {
532                         for (i = 0; i < td->o.nr_files; i++) {
533                                 sprintf(fname, "%s.%d.%d", jobname,
534                                                         td->thread_number, i);
535                                 add_file(td, fname);
536                         }
537                 }
538         }
539
540         if (fixup_options(td))
541                 goto err;
542
543         if (td->io_ops->flags & FIO_DISKLESSIO) {
544                 struct fio_file *f;
545
546                 for_each_file(td, f, i)
547                         f->real_file_size = -1ULL;
548         }
549
550         td->mutex = fio_mutex_init(0);
551
552         td->ts.clat_stat[0].min_val = td->ts.clat_stat[1].min_val = ULONG_MAX;
553         td->ts.slat_stat[0].min_val = td->ts.slat_stat[1].min_val = ULONG_MAX;
554         td->ts.bw_stat[0].min_val = td->ts.bw_stat[1].min_val = ULONG_MAX;
555         td->ddir_nr = td->o.ddir_nr;
556
557         if ((td->o.stonewall || td->o.new_group) && prev_group_jobs) {
558                 prev_group_jobs = 0;
559                 groupid++;
560         }
561
562         td->groupid = groupid;
563         prev_group_jobs++;
564
565         if (init_random_state(td))
566                 goto err;
567
568         if (setup_rate(td))
569                 goto err;
570
571         if (td->o.write_lat_log) {
572                 setup_log(&td->ts.slat_log);
573                 setup_log(&td->ts.clat_log);
574         }
575         if (td->o.write_bw_log)
576                 setup_log(&td->ts.bw_log);
577
578         if (!td->o.name)
579                 td->o.name = strdup(jobname);
580
581         if (!terse_output) {
582                 if (!job_add_num) {
583                         if (!strcmp(td->io_ops->name, "cpuio")) {
584                                 log_info("%s: ioengine=cpu, cpuload=%u,"
585                                          " cpucycle=%u\n", td->o.name,
586                                                         td->o.cpuload,
587                                                         td->o.cpucycle);
588                         } else {
589                                 char *c1, *c2, *c3, *c4;
590
591                                 c1 = to_kmg(td->o.min_bs[DDIR_READ]);
592                                 c2 = to_kmg(td->o.max_bs[DDIR_READ]);
593                                 c3 = to_kmg(td->o.min_bs[DDIR_WRITE]);
594                                 c4 = to_kmg(td->o.max_bs[DDIR_WRITE]);
595
596                                 log_info("%s: (g=%d): rw=%s, bs=%s-%s/%s-%s,"
597                                          " ioengine=%s, iodepth=%u\n",
598                                                 td->o.name, td->groupid,
599                                                 ddir_str[td->o.td_ddir],
600                                                 c1, c2, c3, c4,
601                                                 td->io_ops->name,
602                                                 td->o.iodepth);
603
604                                 free(c1);
605                                 free(c2);
606                                 free(c3);
607                                 free(c4);
608                         }
609                 } else if (job_add_num == 1)
610                         log_info("...\n");
611         }
612
613         /*
614          * recurse add identical jobs, clear numjobs and stonewall options
615          * as they don't apply to sub-jobs
616          */
617         numjobs = td->o.numjobs;
618         while (--numjobs) {
619                 struct thread_data *td_new = get_new_job(0, td);
620
621                 if (!td_new)
622                         goto err;
623
624                 td_new->o.numjobs = 1;
625                 td_new->o.stonewall = 0;
626                 td_new->o.new_group = 0;
627
628                 if (file_alloced) {
629                         td_new->o.filename = NULL;
630                         td_new->files_index = 0;
631                         td_new->files_size = 0;
632                         td_new->files = NULL;
633                 }
634
635                 job_add_num = numjobs - 1;
636
637                 if (add_job(td_new, jobname, job_add_num))
638                         goto err;
639         }
640
641         return 0;
642 err:
643         put_job(td);
644         return -1;
645 }
646
647 static int skip_this_section(const char *name)
648 {
649         if (!job_section)
650                 return 0;
651         if (!strncmp(name, "global", 6))
652                 return 0;
653
654         return strcmp(job_section, name);
655 }
656
657 static int is_empty_or_comment(char *line)
658 {
659         unsigned int i;
660
661         for (i = 0; i < strlen(line); i++) {
662                 if (line[i] == ';')
663                         return 1;
664                 if (line[i] == '#')
665                         return 1;
666                 if (!isspace(line[i]) && !iscntrl(line[i]))
667                         return 0;
668         }
669
670         return 1;
671 }
672
673 /*
674  * This is our [ini] type file parser.
675  */
676 static int parse_jobs_ini(char *file, int stonewall_flag)
677 {
678         unsigned int global;
679         struct thread_data *td;
680         char *string, *name;
681         FILE *f;
682         char *p;
683         int ret = 0, stonewall;
684         int first_sect = 1;
685         int skip_fgets = 0;
686         int inside_skip = 0;
687         char **opts;
688         int i, alloc_opts, num_opts;
689
690         if (!strcmp(file, "-"))
691                 f = stdin;
692         else
693                 f = fopen(file, "r");
694
695         if (!f) {
696                 perror("fopen job file");
697                 return 1;
698         }
699
700         string = malloc(4096);
701
702         /*
703          * it's really 256 + small bit, 280 should suffice
704          */
705         name = malloc(280);
706         memset(name, 0, 280);
707
708         alloc_opts = 8;
709         opts = malloc(sizeof(char *) * alloc_opts);
710         num_opts = 0;
711
712         stonewall = stonewall_flag;
713         do {
714                 /*
715                  * if skip_fgets is set, we already have loaded a line we
716                  * haven't handled.
717                  */
718                 if (!skip_fgets) {
719                         p = fgets(string, 4095, f);
720                         if (!p)
721                                 break;
722                 }
723
724                 skip_fgets = 0;
725                 strip_blank_front(&p);
726                 strip_blank_end(p);
727
728                 if (is_empty_or_comment(p))
729                         continue;
730                 if (sscanf(p, "[%255s]", name) != 1) {
731                         if (inside_skip)
732                                 continue;
733                         log_err("fio: option <%s> outside of [] job section\n",
734                                                                         p);
735                         break;
736                 }
737
738                 if (skip_this_section(name)) {
739                         inside_skip = 1;
740                         continue;
741                 } else
742                         inside_skip = 0;
743
744                 global = !strncmp(name, "global", 6);
745
746                 name[strlen(name) - 1] = '\0';
747
748                 if (dump_cmdline) {
749                         if (first_sect)
750                                 log_info("fio ");
751                         if (!global)
752                                 log_info("--name=%s ", name);
753                         first_sect = 0;
754                 }
755
756                 td = get_new_job(global, &def_thread);
757                 if (!td) {
758                         ret = 1;
759                         break;
760                 }
761
762                 /*
763                  * Seperate multiple job files by a stonewall
764                  */
765                 if (!global && stonewall) {
766                         td->o.stonewall = stonewall;
767                         stonewall = 0;
768                 }
769
770                 num_opts = 0;
771                 memset(opts, 0, alloc_opts * sizeof(char *));
772
773                 while ((p = fgets(string, 4096, f)) != NULL) {
774                         if (is_empty_or_comment(p))
775                                 continue;
776
777                         strip_blank_front(&p);
778
779                         /*
780                          * new section, break out and make sure we don't
781                          * fgets() a new line at the top.
782                          */
783                         if (p[0] == '[') {
784                                 skip_fgets = 1;
785                                 break;
786                         }
787
788                         strip_blank_end(p);
789
790                         if (num_opts == alloc_opts) {
791                                 alloc_opts <<= 1;
792                                 opts = realloc(opts,
793                                                 alloc_opts * sizeof(char *));
794                         }
795
796                         opts[num_opts] = strdup(p);
797                         num_opts++;
798                 }
799
800                 ret = fio_options_parse(td, opts, num_opts);
801                 if (!ret) {
802                         if (dump_cmdline)
803                                 for (i = 0; i < num_opts; i++)
804                                         log_info("--%s ", opts[i]);
805
806                         ret = add_job(td, name, 0);
807                 } else {
808                         log_err("fio: job %s dropped\n", name);
809                         put_job(td);
810                 }
811
812                 for (i = 0; i < num_opts; i++)
813                         free(opts[i]);
814                 num_opts = 0;
815         } while (!ret);
816
817         if (dump_cmdline)
818                 log_info("\n");
819
820         for (i = 0; i < num_opts; i++)
821                 free(opts[i]);
822
823         free(string);
824         free(name);
825         free(opts);
826         if (f != stdin)
827                 fclose(f);
828         return ret;
829 }
830
831 static int fill_def_thread(void)
832 {
833         memset(&def_thread, 0, sizeof(def_thread));
834
835         fio_getaffinity(getpid(), &def_thread.o.cpumask);
836
837         /*
838          * fill default options
839          */
840         fio_fill_default_options(&def_thread);
841
842         def_thread.o.timeout = def_timeout;
843         def_thread.o.write_bw_log = write_bw_log;
844         def_thread.o.write_lat_log = write_lat_log;
845
846         return 0;
847 }
848
849 static void free_shm(void)
850 {
851         struct shmid_ds sbuf;
852
853         if (threads) {
854                 void *tp = threads;
855
856                 threads = NULL;
857                 file_hash_exit();
858                 fio_debug_jobp = NULL;
859                 shmdt(tp);
860                 shmctl(shm_id, IPC_RMID, &sbuf);
861         }
862
863         scleanup();
864 }
865
866 /*
867  * The thread area is shared between the main process and the job
868  * threads/processes. So setup a shared memory segment that will hold
869  * all the job info. We use the end of the region for keeping track of
870  * open files across jobs, for file sharing.
871  */
872 static int setup_thread_area(void)
873 {
874         void *hash;
875
876         /*
877          * 1024 is too much on some machines, scale max_jobs if
878          * we get a failure that looks like too large a shm segment
879          */
880         do {
881                 size_t size = max_jobs * sizeof(struct thread_data);
882
883                 size += file_hash_size;
884                 size += sizeof(unsigned int);
885
886                 shm_id = shmget(0, size, IPC_CREAT | 0600);
887                 if (shm_id != -1)
888                         break;
889                 if (errno != EINVAL) {
890                         perror("shmget");
891                         break;
892                 }
893
894                 max_jobs >>= 1;
895         } while (max_jobs);
896
897         if (shm_id == -1)
898                 return 1;
899
900         threads = shmat(shm_id, NULL, 0);
901         if (threads == (void *) -1) {
902                 perror("shmat");
903                 return 1;
904         }
905
906         memset(threads, 0, max_jobs * sizeof(struct thread_data));
907         hash = (void *) threads + max_jobs * sizeof(struct thread_data);
908         fio_debug_jobp = (void *) hash + file_hash_size;
909         *fio_debug_jobp = -1;
910         file_hash_init(hash);
911         atexit(free_shm);
912         return 0;
913 }
914
915 static void usage(const char *name)
916 {
917         printf("%s\n", fio_version_string);
918         printf("%s [options] [job options] <job file(s)>\n", name);
919         printf("\t--debug=options\tEnable debug logging\n");
920         printf("\t--output\tWrite output to file\n");
921         printf("\t--timeout\tRuntime in seconds\n");
922         printf("\t--latency-log\tGenerate per-job latency logs\n");
923         printf("\t--bandwidth-log\tGenerate per-job bandwidth logs\n");
924         printf("\t--minimal\tMinimal (terse) output\n");
925         printf("\t--version\tPrint version info and exit\n");
926         printf("\t--help\t\tPrint this page\n");
927         printf("\t--cmdhelp=cmd\tPrint command help, \"all\" for all of"
928                 " them\n");
929         printf("\t--showcmd\tTurn a job file into command line options\n");
930         printf("\t--eta=when\tWhen ETA estimate should be printed\n");
931         printf("\t          \tMay be \"always\", \"never\" or \"auto\"\n");
932         printf("\t--readonly\tTurn on safety read-only checks, preventing"
933                 " writes\n");
934         printf("\t--section=name\tOnly run specified section in job file\n");
935         printf("\t--alloc-size=kb\tSet smalloc pool to this size in kb"
936                 " (def 1024)\n");
937         printf("\nFio was written by Jens Axboe <jens.axboe@oracle.com>\n");
938 }
939
940 #ifdef FIO_INC_DEBUG
941 struct debug_level debug_levels[] = {
942         { .name = "process",    .shift = FD_PROCESS, },
943         { .name = "file",       .shift = FD_FILE, },
944         { .name = "io",         .shift = FD_IO, },
945         { .name = "mem",        .shift = FD_MEM, },
946         { .name = "blktrace",   .shift = FD_BLKTRACE },
947         { .name = "verify",     .shift = FD_VERIFY },
948         { .name = "random",     .shift = FD_RANDOM },
949         { .name = "parse",      .shift = FD_PARSE },
950         { .name = "diskutil",   .shift = FD_DISKUTIL },
951         { .name = "job",        .shift = FD_JOB },
952         { .name = "mutex",      .shift = FD_MUTEX },
953         { .name = NULL, },
954 };
955
956 static int set_debug(const char *string)
957 {
958         struct debug_level *dl;
959         char *p = (char *) string;
960         char *opt;
961         int i;
962
963         if (!strcmp(string, "?") || !strcmp(string, "help")) {
964                 int i;
965
966                 log_info("fio: dumping debug options:");
967                 for (i = 0; debug_levels[i].name; i++) {
968                         dl = &debug_levels[i];
969                         log_info("%s,", dl->name);
970                 }
971                 log_info("all\n");
972                 return 1;
973         }
974
975         while ((opt = strsep(&p, ",")) != NULL) {
976                 int found = 0;
977
978                 if (!strncmp(opt, "all", 3)) {
979                         log_info("fio: set all debug options\n");
980                         fio_debug = ~0UL;
981                         continue;
982                 }
983
984                 for (i = 0; debug_levels[i].name; i++) {
985                         dl = &debug_levels[i];
986                         found = !strncmp(opt, dl->name, strlen(dl->name));
987                         if (!found)
988                                 continue;
989
990                         if (dl->shift == FD_JOB) {
991                                 opt = strchr(opt, ':');
992                                 if (!opt) {
993                                         log_err("fio: missing job number\n");
994                                         break;
995                                 }
996                                 opt++;
997                                 fio_debug_jobno = atoi(opt);
998                                 log_info("fio: set debug jobno %d\n",
999                                                         fio_debug_jobno);
1000                         } else {
1001                                 log_info("fio: set debug option %s\n", opt);
1002                                 fio_debug |= (1UL << dl->shift);
1003                         }
1004                         break;
1005                 }
1006
1007                 if (!found)
1008                         log_err("fio: debug mask %s not found\n", opt);
1009         }
1010         return 0;
1011 }
1012 #else
1013 static int set_debug(const char *string)
1014 {
1015         log_err("fio: debug tracing not included in build\n");
1016         return 1;
1017 }
1018 #endif
1019
1020 static int load_profile(const char *profile)
1021 {
1022         struct thread_data *td, *td_parent;
1023         const char **o;
1024         int i, in_global = 1;
1025         char jobname[32];
1026
1027         dprint(FD_PARSE, "loading profile %s\n", profile);
1028
1029         for (i = 0; i < PROFILE_END; i++) {
1030                 if (!strcmp(profile, profiles[i]))
1031                         break;
1032         }
1033
1034         if (i == PROFILE_END) {
1035                 log_err("fio: unknown profile %s\n", profile);
1036                 return 1;
1037         }
1038
1039         o = fio_prof_strings[i];
1040         if (!o)
1041                 return 0;
1042
1043         i = 0;
1044         td_parent = td = NULL;
1045         while (o[i]) {
1046                 if (!strncmp(o[i], "name", 4)) {
1047                         in_global = 0;
1048                         if (td)
1049                                 add_job(td, jobname, 0);
1050                         td = NULL;
1051                         sprintf(jobname, "%s", o[i] + 5);
1052                 }
1053                 if (in_global && !td_parent)
1054                         td_parent = get_new_job(1, &def_thread);
1055                 else if (!in_global && !td) {
1056                         if (!td_parent)
1057                                 td_parent = &def_thread;
1058                         td = get_new_job(0, td_parent);
1059                 }
1060                 if (in_global)
1061                         fio_options_parse(td_parent, (char **) &o[i], 1);
1062                 else
1063                         fio_options_parse(td, (char **) &o[i], 1);
1064                 i++;
1065         }
1066         if (td)
1067                 add_job(td, jobname, 0);
1068         return 0;
1069 }
1070
1071 static int parse_cmd_line(int argc, char *argv[])
1072 {
1073         struct thread_data *td = NULL;
1074         int c, ini_idx = 0, lidx, ret = 0, do_exit = 0, exit_val = 0;
1075
1076         while ((c = getopt_long_only(argc, argv, "", l_opts, &lidx)) != -1) {
1077                 switch (c) {
1078                 case 'a':
1079                         smalloc_pool_size = atoi(optarg);
1080                         break;
1081                 case 't':
1082                         def_timeout = atoi(optarg);
1083                         break;
1084                 case 'l':
1085                         write_lat_log = 1;
1086                         break;
1087                 case 'w':
1088                         write_bw_log = 1;
1089                         break;
1090                 case 'o':
1091                         f_out = fopen(optarg, "w+");
1092                         if (!f_out) {
1093                                 perror("fopen output");
1094                                 exit(1);
1095                         }
1096                         f_err = f_out;
1097                         break;
1098                 case 'm':
1099                         terse_output = 1;
1100                         break;
1101                 case 'h':
1102                         usage(argv[0]);
1103                         exit(0);
1104                 case 'c':
1105                         exit(fio_show_option_help(optarg));
1106                 case 's':
1107                         dump_cmdline = 1;
1108                         break;
1109                 case 'r':
1110                         read_only = 1;
1111                         break;
1112                 case 'v':
1113                         printf("%s\n", fio_version_string);
1114                         exit(0);
1115                 case 'e':
1116                         if (!strcmp("always", optarg))
1117                                 eta_print = FIO_ETA_ALWAYS;
1118                         else if (!strcmp("never", optarg))
1119                                 eta_print = FIO_ETA_NEVER;
1120                         break;
1121                 case 'd':
1122                         if (set_debug(optarg))
1123                                 do_exit++;
1124                         break;
1125                 case 'x':
1126                         if (!strcmp(optarg, "global")) {
1127                                 log_err("fio: can't use global as only "
1128                                         "section\n");
1129                                 do_exit++;
1130                                 exit_val = 1;
1131                                 break;
1132                         }
1133                         if (job_section)
1134                                 free(job_section);
1135                         job_section = strdup(optarg);
1136                         break;
1137                 case 'p':
1138                         if (load_profile(optarg))
1139                                 do_exit++;
1140                         break;
1141                 case FIO_GETOPT_JOB: {
1142                         const char *opt = l_opts[lidx].name;
1143                         char *val = optarg;
1144
1145                         if (!strncmp(opt, "name", 4) && td) {
1146                                 ret = add_job(td, td->o.name ?: "fio", 0);
1147                                 if (ret) {
1148                                         put_job(td);
1149                                         return 0;
1150                                 }
1151                                 td = NULL;
1152                         }
1153                         if (!td) {
1154                                 int is_section = !strncmp(opt, "name", 4);
1155                                 int global = 0;
1156
1157                                 if (!is_section || !strncmp(val, "global", 6))
1158                                         global = 1;
1159
1160                                 if (is_section && skip_this_section(val))
1161                                         continue;
1162
1163                                 td = get_new_job(global, &def_thread);
1164                                 if (!td)
1165                                         return 0;
1166                         }
1167
1168                         ret = fio_cmd_option_parse(td, opt, val);
1169                         break;
1170                 }
1171                 default:
1172                         do_exit++;
1173                         exit_val = 1;
1174                         break;
1175                 }
1176         }
1177
1178         if (do_exit)
1179                 exit(exit_val);
1180
1181         if (td) {
1182                 if (!ret)
1183                         ret = add_job(td, td->o.name ?: "fio", 0);
1184                 if (ret)
1185                         put_job(td);
1186         }
1187
1188         while (optind < argc) {
1189                 ini_idx++;
1190                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
1191                 ini_file[ini_idx - 1] = strdup(argv[optind]);
1192                 optind++;
1193         }
1194
1195         return ini_idx;
1196 }
1197
1198 int parse_options(int argc, char *argv[])
1199 {
1200         int job_files, i;
1201
1202         f_out = stdout;
1203         f_err = stderr;
1204
1205         fio_options_dup_and_init(l_opts);
1206
1207         if (setup_thread_area())
1208                 return 1;
1209         if (fill_def_thread())
1210                 return 1;
1211
1212         job_files = parse_cmd_line(argc, argv);
1213
1214         for (i = 0; i < job_files; i++) {
1215                 if (fill_def_thread())
1216                         return 1;
1217                 if (parse_jobs_ini(ini_file[i], i))
1218                         return 1;
1219                 free(ini_file[i]);
1220         }
1221
1222         free(ini_file);
1223         options_mem_free(&def_thread);
1224
1225         if (!thread_number) {
1226                 if (dump_cmdline)
1227                         return 0;
1228
1229                 log_err("No jobs defined(s)\n\n");
1230                 usage(argv[0]);
1231                 return 1;
1232         }
1233
1234         if (def_thread.o.gtod_offload) {
1235                 fio_gtod_init();
1236                 fio_gtod_offload = 1;
1237                 fio_gtod_cpu = def_thread.o.gtod_cpu;
1238         }
1239
1240         return 0;
1241 }