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