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