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