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