Add a typecheck for the endianness conversions
[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/types.h>
13 #include <sys/stat.h>
14
15 #include "fio.h"
16 #ifndef FIO_NO_HAVE_SHM_H
17 #include <sys/shm.h>
18 #endif
19
20 #include "parse.h"
21 #include "smalloc.h"
22 #include "filehash.h"
23 #include "verify.h"
24 #include "profile.h"
25 #include "server.h"
26 #include "idletime.h"
27 #include "filelock.h"
28
29 #include "lib/getopt.h"
30 #include "lib/strcasestr.h"
31
32 #include "crc/test.h"
33
34 const char fio_version_string[] = FIO_VERSION;
35
36 #define FIO_RANDSEED            (0xb1899bedUL)
37
38 static char **ini_file;
39 static int max_jobs = FIO_MAX_JOBS;
40 static int dump_cmdline;
41 static long long def_timeout;
42 static int parse_only;
43
44 static struct thread_data def_thread;
45 struct thread_data *threads = NULL;
46 static char **job_sections;
47 static int nr_job_sections;
48
49 int exitall_on_terminate = 0;
50 int output_format = FIO_OUTPUT_NORMAL;
51 int append_terse_output = 0;
52 int eta_print = FIO_ETA_AUTO;
53 int eta_new_line = 0;
54 FILE *f_out = NULL;
55 FILE *f_err = NULL;
56 char *exec_profile = NULL;
57 int warnings_fatal = 0;
58 int terse_version = 3;
59 int is_backend = 0;
60 int nr_clients = 0;
61 int log_syslog = 0;
62
63 int write_bw_log = 0;
64 int read_only = 0;
65 int status_interval = 0;
66
67 static int write_lat_log;
68
69 static int prev_group_jobs;
70
71 unsigned long fio_debug = 0;
72 unsigned int fio_debug_jobno = -1;
73 unsigned int *fio_debug_jobp = NULL;
74
75 static char cmd_optstr[256];
76 static int did_arg;
77
78 #define FIO_CLIENT_FLAG         (1 << 16)
79
80 /*
81  * Command line options. These will contain the above, plus a few
82  * extra that only pertain to fio itself and not jobs.
83  */
84 static struct option l_opts[FIO_NR_OPTIONS] = {
85         {
86                 .name           = (char *) "output",
87                 .has_arg        = required_argument,
88                 .val            = 'o' | FIO_CLIENT_FLAG,
89         },
90         {
91                 .name           = (char *) "timeout",
92                 .has_arg        = required_argument,
93                 .val            = 't' | FIO_CLIENT_FLAG,
94         },
95         {
96                 .name           = (char *) "latency-log",
97                 .has_arg        = required_argument,
98                 .val            = 'l' | FIO_CLIENT_FLAG,
99         },
100         {
101                 .name           = (char *) "bandwidth-log",
102                 .has_arg        = required_argument,
103                 .val            = 'b' | FIO_CLIENT_FLAG,
104         },
105         {
106                 .name           = (char *) "minimal",
107                 .has_arg        = no_argument,
108                 .val            = 'm' | FIO_CLIENT_FLAG,
109         },
110         {
111                 .name           = (char *) "output-format",
112                 .has_arg        = optional_argument,
113                 .val            = 'F' | FIO_CLIENT_FLAG,
114         },
115         {
116                 .name           = (char *) "append-terse",
117                 .has_arg        = optional_argument,
118                 .val            = 'f',
119         },
120         {
121                 .name           = (char *) "version",
122                 .has_arg        = no_argument,
123                 .val            = 'v' | FIO_CLIENT_FLAG,
124         },
125         {
126                 .name           = (char *) "help",
127                 .has_arg        = no_argument,
128                 .val            = 'h' | FIO_CLIENT_FLAG,
129         },
130         {
131                 .name           = (char *) "cmdhelp",
132                 .has_arg        = optional_argument,
133                 .val            = 'c' | FIO_CLIENT_FLAG,
134         },
135         {
136                 .name           = (char *) "enghelp",
137                 .has_arg        = optional_argument,
138                 .val            = 'i' | FIO_CLIENT_FLAG,
139         },
140         {
141                 .name           = (char *) "showcmd",
142                 .has_arg        = no_argument,
143                 .val            = 's' | FIO_CLIENT_FLAG,
144         },
145         {
146                 .name           = (char *) "readonly",
147                 .has_arg        = no_argument,
148                 .val            = 'r' | FIO_CLIENT_FLAG,
149         },
150         {
151                 .name           = (char *) "eta",
152                 .has_arg        = required_argument,
153                 .val            = 'e' | FIO_CLIENT_FLAG,
154         },
155         {
156                 .name           = (char *) "eta-newline",
157                 .has_arg        = required_argument,
158                 .val            = 'E' | FIO_CLIENT_FLAG,
159         },
160         {
161                 .name           = (char *) "debug",
162                 .has_arg        = required_argument,
163                 .val            = 'd' | FIO_CLIENT_FLAG,
164         },
165         {
166                 .name           = (char *) "parse-only",
167                 .has_arg        = no_argument,
168                 .val            = 'P' | FIO_CLIENT_FLAG,
169         },
170         {
171                 .name           = (char *) "section",
172                 .has_arg        = required_argument,
173                 .val            = 'x' | FIO_CLIENT_FLAG,
174         },
175         {
176                 .name           = (char *) "alloc-size",
177                 .has_arg        = required_argument,
178                 .val            = 'a' | FIO_CLIENT_FLAG,
179         },
180         {
181                 .name           = (char *) "profile",
182                 .has_arg        = required_argument,
183                 .val            = 'p' | FIO_CLIENT_FLAG,
184         },
185         {
186                 .name           = (char *) "warnings-fatal",
187                 .has_arg        = no_argument,
188                 .val            = 'w' | FIO_CLIENT_FLAG,
189         },
190         {
191                 .name           = (char *) "max-jobs",
192                 .has_arg        = required_argument,
193                 .val            = 'j' | FIO_CLIENT_FLAG,
194         },
195         {
196                 .name           = (char *) "terse-version",
197                 .has_arg        = required_argument,
198                 .val            = 'V' | FIO_CLIENT_FLAG,
199         },
200         {
201                 .name           = (char *) "server",
202                 .has_arg        = optional_argument,
203                 .val            = 'S',
204         },
205         {       .name           = (char *) "daemonize",
206                 .has_arg        = required_argument,
207                 .val            = 'D',
208         },
209         {
210                 .name           = (char *) "client",
211                 .has_arg        = required_argument,
212                 .val            = 'C',
213         },
214         {
215                 .name           = (char *) "cpuclock-test",
216                 .has_arg        = no_argument,
217                 .val            = 'T',
218         },
219         {
220                 .name           = (char *) "crctest",
221                 .has_arg        = optional_argument,
222                 .val            = 'G',
223         },
224         {
225                 .name           = (char *) "idle-prof",
226                 .has_arg        = required_argument,
227                 .val            = 'I',
228         },
229         {
230                 .name           = (char *) "status-interval",
231                 .has_arg        = required_argument,
232                 .val            = 'L',
233         },
234         {
235                 .name           = NULL,
236         },
237 };
238
239 void free_threads_shm(void)
240 {
241         if (threads) {
242                 void *tp = threads;
243 #ifndef CONFIG_NO_SHM
244                 struct shmid_ds sbuf;
245
246                 threads = NULL;
247                 shmdt(tp);
248                 shmctl(shm_id, IPC_RMID, &sbuf);
249                 shm_id = -1;
250 #else
251                 threads = NULL;
252                 free(tp);
253 #endif
254         }
255 }
256
257 static void free_shm(void)
258 {
259         if (threads) {
260                 file_hash_exit();
261                 flow_exit();
262                 fio_debug_jobp = NULL;
263                 free_threads_shm();
264         }
265
266         options_free(fio_options, &def_thread);
267         fio_filelock_exit();
268         scleanup();
269 }
270
271 /*
272  * The thread area is shared between the main process and the job
273  * threads/processes. So setup a shared memory segment that will hold
274  * all the job info. We use the end of the region for keeping track of
275  * open files across jobs, for file sharing.
276  */
277 static int setup_thread_area(void)
278 {
279         void *hash;
280
281         if (threads)
282                 return 0;
283
284         /*
285          * 1024 is too much on some machines, scale max_jobs if
286          * we get a failure that looks like too large a shm segment
287          */
288         do {
289                 size_t size = max_jobs * sizeof(struct thread_data);
290
291                 size += file_hash_size;
292                 size += sizeof(unsigned int);
293
294 #ifndef CONFIG_NO_SHM
295                 shm_id = shmget(0, size, IPC_CREAT | 0600);
296                 if (shm_id != -1)
297                         break;
298                 if (errno != EINVAL && errno != ENOMEM && errno != ENOSPC) {
299                         perror("shmget");
300                         break;
301                 }
302 #else
303                 threads = malloc(size);
304                 if (threads)
305                         break;
306 #endif
307
308                 max_jobs >>= 1;
309         } while (max_jobs);
310
311 #ifndef CONFIG_NO_SHM
312         if (shm_id == -1)
313                 return 1;
314
315         threads = shmat(shm_id, NULL, 0);
316         if (threads == (void *) -1) {
317                 perror("shmat");
318                 return 1;
319         }
320 #endif
321
322         memset(threads, 0, max_jobs * sizeof(struct thread_data));
323         hash = (void *) threads + max_jobs * sizeof(struct thread_data);
324         fio_debug_jobp = (void *) hash + file_hash_size;
325         *fio_debug_jobp = -1;
326         file_hash_init(hash);
327
328         flow_init();
329
330         return 0;
331 }
332
333 static void set_cmd_options(struct thread_data *td)
334 {
335         struct thread_options *o = &td->o;
336
337         if (!o->timeout)
338                 o->timeout = def_timeout;
339 }
340
341 /*
342  * Return a free job structure.
343  */
344 static struct thread_data *get_new_job(int global, struct thread_data *parent,
345                                        int preserve_eo, const char *jobname)
346 {
347         struct thread_data *td;
348
349         if (global) {
350                 set_cmd_options(&def_thread);
351                 return &def_thread;
352         }
353         if (setup_thread_area()) {
354                 log_err("error: failed to setup shm segment\n");
355                 return NULL;
356         }
357         if (thread_number >= max_jobs) {
358                 log_err("error: maximum number of jobs (%d) reached.\n",
359                                 max_jobs);
360                 return NULL;
361         }
362
363         td = &threads[thread_number++];
364         *td = *parent;
365
366         td->io_ops = NULL;
367         if (!preserve_eo)
368                 td->eo = NULL;
369
370         td->o.uid = td->o.gid = -1U;
371
372         dup_files(td, parent);
373         fio_options_mem_dupe(td);
374
375         profile_add_hooks(td);
376
377         td->thread_number = thread_number;
378
379         if (jobname)
380                 td->o.name = strdup(jobname);
381
382         if (!parent->o.group_reporting)
383                 stat_number++;
384
385         set_cmd_options(td);
386         return td;
387 }
388
389 static void put_job(struct thread_data *td)
390 {
391         if (td == &def_thread)
392                 return;
393
394         profile_td_exit(td);
395         flow_exit_job(td);
396
397         if (td->error)
398                 log_info("fio: %s\n", td->verror);
399
400         fio_options_free(td);
401         if (td->io_ops)
402                 free_ioengine(td);
403
404         if (td->o.name)
405                 free(td->o.name);
406
407         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
408         thread_number--;
409 }
410
411 static int __setup_rate(struct thread_data *td, enum fio_ddir ddir)
412 {
413         unsigned int bs = td->o.min_bs[ddir];
414
415         assert(ddir_rw(ddir));
416
417         if (td->o.rate[ddir])
418                 td->rate_bps[ddir] = td->o.rate[ddir];
419         else
420                 td->rate_bps[ddir] = td->o.rate_iops[ddir] * bs;
421
422         if (!td->rate_bps[ddir]) {
423                 log_err("rate lower than supported\n");
424                 return -1;
425         }
426
427         td->rate_pending_usleep[ddir] = 0;
428         return 0;
429 }
430
431 static int setup_rate(struct thread_data *td)
432 {
433         int ret = 0;
434
435         if (td->o.rate[DDIR_READ] || td->o.rate_iops[DDIR_READ])
436                 ret = __setup_rate(td, DDIR_READ);
437         if (td->o.rate[DDIR_WRITE] || td->o.rate_iops[DDIR_WRITE])
438                 ret |= __setup_rate(td, DDIR_WRITE);
439         if (td->o.rate[DDIR_TRIM] || td->o.rate_iops[DDIR_TRIM])
440                 ret |= __setup_rate(td, DDIR_TRIM);
441
442         return ret;
443 }
444
445 static int fixed_block_size(struct thread_options *o)
446 {
447         return o->min_bs[DDIR_READ] == o->max_bs[DDIR_READ] &&
448                 o->min_bs[DDIR_WRITE] == o->max_bs[DDIR_WRITE] &&
449                 o->min_bs[DDIR_TRIM] == o->max_bs[DDIR_TRIM] &&
450                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_WRITE] &&
451                 o->min_bs[DDIR_READ] == o->min_bs[DDIR_TRIM];
452 }
453
454
455 static unsigned long long get_rand_start_delay(struct thread_data *td)
456 {
457         unsigned long long delayrange;
458         unsigned long r;
459
460         delayrange = td->o.start_delay_high - td->o.start_delay;
461
462         if (td->o.use_os_rand) {
463                 r = os_random_long(&td->delay_state);
464                 delayrange = (unsigned long long) ((double) delayrange * (r / (OS_RAND_MAX + 1.0)));
465         } else {
466                 r = __rand(&td->__delay_state);
467                 delayrange = (unsigned long long) ((double) delayrange * (r / (FRAND_MAX + 1.0)));
468         }
469
470         delayrange += td->o.start_delay;
471         return delayrange;
472 }
473
474 /*
475  * Lazy way of fixing up options that depend on each other. We could also
476  * define option callback handlers, but this is easier.
477  */
478 static int fixup_options(struct thread_data *td)
479 {
480         struct thread_options *o = &td->o;
481         int ret = 0;
482
483 #ifndef FIO_HAVE_PSHARED_MUTEX
484         if (!o->use_thread) {
485                 log_info("fio: this platform does not support process shared"
486                          " mutexes, forcing use of threads. Use the 'thread'"
487                          " option to get rid of this warning.\n");
488                 o->use_thread = 1;
489                 ret = warnings_fatal;
490         }
491 #endif
492
493         if (o->write_iolog_file && o->read_iolog_file) {
494                 log_err("fio: read iolog overrides write_iolog\n");
495                 free(o->write_iolog_file);
496                 o->write_iolog_file = NULL;
497                 ret = warnings_fatal;
498         }
499
500         /*
501          * only really works with 1 file
502          */
503         if (o->zone_size && o->open_files > 1)
504                 o->zone_size = 0;
505
506         /*
507          * If zone_range isn't specified, backward compatibility dictates it
508          * should be made equal to zone_size.
509          */
510         if (o->zone_size && !o->zone_range)
511                 o->zone_range = o->zone_size;
512
513         /*
514          * Reads can do overwrites, we always need to pre-create the file
515          */
516         if (td_read(td) || td_rw(td))
517                 o->overwrite = 1;
518
519         if (!o->min_bs[DDIR_READ])
520                 o->min_bs[DDIR_READ] = o->bs[DDIR_READ];
521         if (!o->max_bs[DDIR_READ])
522                 o->max_bs[DDIR_READ] = o->bs[DDIR_READ];
523         if (!o->min_bs[DDIR_WRITE])
524                 o->min_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
525         if (!o->max_bs[DDIR_WRITE])
526                 o->max_bs[DDIR_WRITE] = o->bs[DDIR_WRITE];
527         if (!o->min_bs[DDIR_TRIM])
528                 o->min_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
529         if (!o->max_bs[DDIR_TRIM])
530                 o->max_bs[DDIR_TRIM] = o->bs[DDIR_TRIM];
531
532
533         o->rw_min_bs = min(o->min_bs[DDIR_READ], o->min_bs[DDIR_WRITE]);
534         o->rw_min_bs = min(o->min_bs[DDIR_TRIM], o->rw_min_bs);
535
536         /*
537          * For random IO, allow blockalign offset other than min_bs.
538          */
539         if (!o->ba[DDIR_READ] || !td_random(td))
540                 o->ba[DDIR_READ] = o->min_bs[DDIR_READ];
541         if (!o->ba[DDIR_WRITE] || !td_random(td))
542                 o->ba[DDIR_WRITE] = o->min_bs[DDIR_WRITE];
543         if (!o->ba[DDIR_TRIM] || !td_random(td))
544                 o->ba[DDIR_TRIM] = o->min_bs[DDIR_TRIM];
545
546         if ((o->ba[DDIR_READ] != o->min_bs[DDIR_READ] ||
547             o->ba[DDIR_WRITE] != o->min_bs[DDIR_WRITE] ||
548             o->ba[DDIR_TRIM] != o->min_bs[DDIR_TRIM]) &&
549             !o->norandommap) {
550                 log_err("fio: Any use of blockalign= turns off randommap\n");
551                 o->norandommap = 1;
552                 ret = warnings_fatal;
553         }
554
555         if (!o->file_size_high)
556                 o->file_size_high = o->file_size_low;
557
558         if (o->start_delay_high)
559                 o->start_delay = get_rand_start_delay(td);
560
561         if (o->norandommap && o->verify != VERIFY_NONE
562             && !fixed_block_size(o))  {
563                 log_err("fio: norandommap given for variable block sizes, "
564                         "verify disabled\n");
565                 o->verify = VERIFY_NONE;
566                 ret = warnings_fatal;
567         }
568         if (o->bs_unaligned && (o->odirect || td->io_ops->flags & FIO_RAWIO))
569                 log_err("fio: bs_unaligned may not work with raw io\n");
570
571         /*
572          * thinktime_spin must be less than thinktime
573          */
574         if (o->thinktime_spin > o->thinktime)
575                 o->thinktime_spin = o->thinktime;
576
577         /*
578          * The low water mark cannot be bigger than the iodepth
579          */
580         if (o->iodepth_low > o->iodepth || !o->iodepth_low)
581                 o->iodepth_low = o->iodepth;
582
583         /*
584          * If batch number isn't set, default to the same as iodepth
585          */
586         if (o->iodepth_batch > o->iodepth || !o->iodepth_batch)
587                 o->iodepth_batch = o->iodepth;
588
589         if (o->nr_files > td->files_index)
590                 o->nr_files = td->files_index;
591
592         if (o->open_files > o->nr_files || !o->open_files)
593                 o->open_files = o->nr_files;
594
595         if (((o->rate[DDIR_READ] + o->rate[DDIR_WRITE] + o->rate[DDIR_TRIM]) &&
596             (o->rate_iops[DDIR_READ] + o->rate_iops[DDIR_WRITE] + o->rate_iops[DDIR_TRIM])) ||
597             ((o->ratemin[DDIR_READ] + o->ratemin[DDIR_WRITE] + o->ratemin[DDIR_TRIM]) &&
598             (o->rate_iops_min[DDIR_READ] + o->rate_iops_min[DDIR_WRITE] + o->rate_iops_min[DDIR_TRIM]))) {
599                 log_err("fio: rate and rate_iops are mutually exclusive\n");
600                 ret = 1;
601         }
602         if ((o->rate[DDIR_READ] < o->ratemin[DDIR_READ]) ||
603             (o->rate[DDIR_WRITE] < o->ratemin[DDIR_WRITE]) ||
604             (o->rate[DDIR_TRIM] < o->ratemin[DDIR_TRIM]) ||
605             (o->rate_iops[DDIR_READ] < o->rate_iops_min[DDIR_READ]) ||
606             (o->rate_iops[DDIR_WRITE] < o->rate_iops_min[DDIR_WRITE]) ||
607             (o->rate_iops[DDIR_TRIM] < o->rate_iops_min[DDIR_TRIM])) {
608                 log_err("fio: minimum rate exceeds rate\n");
609                 ret = 1;
610         }
611
612         if (!o->timeout && o->time_based) {
613                 log_err("fio: time_based requires a runtime/timeout setting\n");
614                 o->time_based = 0;
615                 ret = warnings_fatal;
616         }
617
618         if (o->fill_device && !o->size)
619                 o->size = -1ULL;
620
621         if (o->verify != VERIFY_NONE) {
622                 if (td_write(td) && o->do_verify && o->numjobs > 1) {
623                         log_info("Multiple writers may overwrite blocks that "
624                                 "belong to other jobs. This can cause "
625                                 "verification failures.\n");
626                         ret = warnings_fatal;
627                 }
628
629                 o->refill_buffers = 1;
630                 if (o->max_bs[DDIR_WRITE] != o->min_bs[DDIR_WRITE] &&
631                     !o->verify_interval)
632                         o->verify_interval = o->min_bs[DDIR_WRITE];
633         }
634
635         if (o->pre_read) {
636                 o->invalidate_cache = 0;
637                 if (td->io_ops->flags & FIO_PIPEIO) {
638                         log_info("fio: cannot pre-read files with an IO engine"
639                                  " that isn't seekable. Pre-read disabled.\n");
640                         ret = warnings_fatal;
641                 }
642         }
643
644         if (!o->unit_base) {
645                 if (td->io_ops->flags & FIO_BIT_BASED)
646                         o->unit_base = 1;
647                 else
648                         o->unit_base = 8;
649         }
650
651 #ifndef CONFIG_FDATASYNC
652         if (o->fdatasync_blocks) {
653                 log_info("fio: this platform does not support fdatasync()"
654                          " falling back to using fsync().  Use the 'fsync'"
655                          " option instead of 'fdatasync' to get rid of"
656                          " this warning\n");
657                 o->fsync_blocks = o->fdatasync_blocks;
658                 o->fdatasync_blocks = 0;
659                 ret = warnings_fatal;
660         }
661 #endif
662
663 #ifdef WIN32
664         /*
665          * Windows doesn't support O_DIRECT or O_SYNC with the _open interface,
666          * so fail if we're passed those flags
667          */
668         if ((td->io_ops->flags & FIO_SYNCIO) && (td->o.odirect || td->o.sync_io)) {
669                 log_err("fio: Windows does not support direct or non-buffered io with"
670                                 " the synchronous ioengines. Use the 'windowsaio' ioengine"
671                                 " with 'direct=1' and 'iodepth=1' instead.\n");
672                 ret = 1;
673         }
674 #endif
675
676         /*
677          * For fully compressible data, just zero them at init time.
678          * It's faster than repeatedly filling it.
679          */
680         if (td->o.compress_percentage == 100) {
681                 td->o.zero_buffers = 1;
682                 td->o.compress_percentage = 0;
683         }
684
685         /*
686          * Using a non-uniform random distribution excludes usage of
687          * a random map
688          */
689         if (td->o.random_distribution != FIO_RAND_DIST_RANDOM)
690                 td->o.norandommap = 1;
691
692         /*
693          * If size is set but less than the min block size, complain
694          */
695         if (o->size && o->size < td_min_bs(td)) {
696                 log_err("fio: size too small, must be larger than the IO size: %llu\n", (unsigned long long) o->size);
697                 ret = 1;
698         }
699
700         /*
701          * O_ATOMIC implies O_DIRECT
702          */
703         if (td->o.oatomic)
704                 td->o.odirect = 1;
705
706         /*
707          * If randseed is set, that overrides randrepeat
708          */
709         if (td->o.rand_seed)
710                 td->o.rand_repeatable = 0;
711
712         if ((td->io_ops->flags & FIO_NOEXTEND) && td->o.file_append) {
713                 log_err("fio: can't append/extent with IO engine %s\n", td->io_ops->name);
714                 ret = 1;
715         }
716
717         return ret;
718 }
719
720 /*
721  * This function leaks the buffer
722  */
723 char *fio_uint_to_kmg(unsigned int val)
724 {
725         char *buf = malloc(32);
726         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
727         char *p = post;
728
729         do {
730                 if (val & 1023)
731                         break;
732
733                 val >>= 10;
734                 p++;
735         } while (*p);
736
737         snprintf(buf, 32, "%u%c", val, *p);
738         return buf;
739 }
740
741 /* External engines are specified by "external:name.o") */
742 static const char *get_engine_name(const char *str)
743 {
744         char *p = strstr(str, ":");
745
746         if (!p)
747                 return str;
748
749         p++;
750         strip_blank_front(&p);
751         strip_blank_end(p);
752         return p;
753 }
754
755 static int exists_and_not_file(const char *filename)
756 {
757         struct stat sb;
758
759         if (lstat(filename, &sb) == -1)
760                 return 0;
761
762         /* \\.\ is the device namespace in Windows, where every file
763          * is a device node */
764         if (S_ISREG(sb.st_mode) && strncmp(filename, "\\\\.\\", 4) != 0)
765                 return 0;
766
767         return 1;
768 }
769
770 static void td_fill_rand_seeds_os(struct thread_data *td)
771 {
772         os_random_seed(td->rand_seeds[FIO_RAND_BS_OFF], &td->bsrange_state);
773         os_random_seed(td->rand_seeds[FIO_RAND_VER_OFF], &td->verify_state);
774         os_random_seed(td->rand_seeds[FIO_RAND_MIX_OFF], &td->rwmix_state);
775
776         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
777                 os_random_seed(td->rand_seeds[FIO_RAND_FILE_OFF], &td->next_file_state);
778
779         os_random_seed(td->rand_seeds[FIO_RAND_FILE_SIZE_OFF], &td->file_size_state);
780         os_random_seed(td->rand_seeds[FIO_RAND_TRIM_OFF], &td->trim_state);
781         os_random_seed(td->rand_seeds[FIO_RAND_START_DELAY], &td->delay_state);
782
783         if (!td_random(td))
784                 return;
785
786         if (td->o.rand_repeatable)
787                 td->rand_seeds[FIO_RAND_BLOCK_OFF] = FIO_RANDSEED * td->thread_number;
788
789         os_random_seed(td->rand_seeds[FIO_RAND_BLOCK_OFF], &td->random_state);
790
791         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_READ_OFF], &td->seq_rand_state[DDIR_READ]);
792         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_WRITE_OFF], &td->seq_rand_state[DDIR_WRITE]);
793         os_random_seed(td->rand_seeds[FIO_RAND_SEQ_RAND_TRIM_OFF], &td->seq_rand_state[DDIR_TRIM]);
794 }
795
796 static void td_fill_rand_seeds_internal(struct thread_data *td)
797 {
798         init_rand_seed(&td->__bsrange_state, td->rand_seeds[FIO_RAND_BS_OFF]);
799         init_rand_seed(&td->__verify_state, td->rand_seeds[FIO_RAND_VER_OFF]);
800         init_rand_seed(&td->__rwmix_state, td->rand_seeds[FIO_RAND_MIX_OFF]);
801
802         if (td->o.file_service_type == FIO_FSERVICE_RANDOM)
803                 init_rand_seed(&td->__next_file_state, td->rand_seeds[FIO_RAND_FILE_OFF]);
804
805         init_rand_seed(&td->__file_size_state, td->rand_seeds[FIO_RAND_FILE_SIZE_OFF]);
806         init_rand_seed(&td->__trim_state, td->rand_seeds[FIO_RAND_TRIM_OFF]);
807         init_rand_seed(&td->__delay_state, td->rand_seeds[FIO_RAND_START_DELAY]);
808
809         if (!td_random(td))
810                 return;
811
812         if (td->o.rand_repeatable)
813                 td->rand_seeds[FIO_RAND_BLOCK_OFF] = FIO_RANDSEED * td->thread_number;
814
815         init_rand_seed(&td->__random_state, td->rand_seeds[FIO_RAND_BLOCK_OFF]);
816         init_rand_seed(&td->__seq_rand_state[DDIR_READ], td->rand_seeds[FIO_RAND_SEQ_RAND_READ_OFF]);
817         init_rand_seed(&td->__seq_rand_state[DDIR_WRITE], td->rand_seeds[FIO_RAND_SEQ_RAND_WRITE_OFF]);
818         init_rand_seed(&td->__seq_rand_state[DDIR_TRIM], td->rand_seeds[FIO_RAND_SEQ_RAND_TRIM_OFF]);
819 }
820
821 void td_fill_rand_seeds(struct thread_data *td)
822 {
823         if (td->o.allrand_repeatable) {
824                 for (int i = 0; i < FIO_RAND_NR_OFFS; i++)
825                         td->rand_seeds[i] = FIO_RANDSEED * td->thread_number
826                                 + i;
827         }
828
829         if (td->o.use_os_rand)
830                 td_fill_rand_seeds_os(td);
831         else
832                 td_fill_rand_seeds_internal(td);
833
834         init_rand_seed(&td->buf_state, td->rand_seeds[FIO_RAND_BUF_OFF]);
835 }
836
837 /*
838  * Initializes the ioengine configured for a job, if it has not been done so
839  * already.
840  */
841 int ioengine_load(struct thread_data *td)
842 {
843         const char *engine;
844
845         /*
846          * Engine has already been loaded.
847          */
848         if (td->io_ops)
849                 return 0;
850         if (!td->o.ioengine) {
851                 log_err("fio: internal fault, no IO engine specified\n");
852                 return 1;
853         }
854
855         engine = get_engine_name(td->o.ioengine);
856         td->io_ops = load_ioengine(td, engine);
857         if (!td->io_ops) {
858                 log_err("fio: failed to load engine %s\n", engine);
859                 return 1;
860         }
861
862         if (td->io_ops->option_struct_size && td->io_ops->options) {
863                 /*
864                  * In cases where td->eo is set, clone it for a child thread.
865                  * This requires that the parent thread has the same ioengine,
866                  * but that requirement must be enforced by the code which
867                  * cloned the thread.
868                  */
869                 void *origeo = td->eo;
870                 /*
871                  * Otherwise use the default thread options.
872                  */
873                 if (!origeo && td != &def_thread && def_thread.eo &&
874                     def_thread.io_ops->options == td->io_ops->options)
875                         origeo = def_thread.eo;
876
877                 options_init(td->io_ops->options);
878                 td->eo = malloc(td->io_ops->option_struct_size);
879                 /*
880                  * Use the default thread as an option template if this uses the
881                  * same options structure and there are non-default options
882                  * used.
883                  */
884                 if (origeo) {
885                         memcpy(td->eo, origeo, td->io_ops->option_struct_size);
886                         options_mem_dupe(td->eo, td->io_ops->options);
887                 } else {
888                         memset(td->eo, 0, td->io_ops->option_struct_size);
889                         fill_default_options(td->eo, td->io_ops->options);
890                 }
891                 *(struct thread_data **)td->eo = td;
892         }
893
894         return 0;
895 }
896
897 static void init_flags(struct thread_data *td)
898 {
899         struct thread_options *o = &td->o;
900
901         if (o->verify_backlog)
902                 td->flags |= TD_F_VER_BACKLOG;
903         if (o->trim_backlog)
904                 td->flags |= TD_F_TRIM_BACKLOG;
905         if (o->read_iolog_file)
906                 td->flags |= TD_F_READ_IOLOG;
907         if (o->refill_buffers)
908                 td->flags |= TD_F_REFILL_BUFFERS;
909         if (o->scramble_buffers)
910                 td->flags |= TD_F_SCRAMBLE_BUFFERS;
911         if (o->verify != VERIFY_NONE)
912                 td->flags |= TD_F_VER_NONE;
913 }
914
915 static int setup_random_seeds(struct thread_data *td)
916 {
917         unsigned long seed;
918         unsigned int i;
919
920         if (!td->o.rand_repeatable && !td->o.rand_seed)
921                 return init_random_state(td, td->rand_seeds, sizeof(td->rand_seeds));
922
923         if (!td->o.rand_seed)
924                 seed = 0x89;
925         else
926                 seed = td->o.rand_seed;
927
928         for (i = 0; i < 4; i++)
929                 seed *= 0x9e370001UL;
930
931         for (i = 0; i < FIO_RAND_NR_OFFS; i++) {
932                 td->rand_seeds[i] = seed;
933                 seed *= 0x9e370001UL;
934         }
935
936         td_fill_rand_seeds(td);
937         return 0;
938 }
939
940 enum {
941         FPRE_NONE = 0,
942         FPRE_JOBNAME,
943         FPRE_JOBNUM,
944         FPRE_FILENUM
945 };
946
947 static struct fpre_keyword {
948         const char *keyword;
949         size_t strlen;
950         int key;
951 } fpre_keywords[] = {
952         { .keyword = "$jobname",        .key = FPRE_JOBNAME, },
953         { .keyword = "$jobnum",         .key = FPRE_JOBNUM, },
954         { .keyword = "$filenum",        .key = FPRE_FILENUM, },
955         { .keyword = NULL, },
956         };
957
958 static char *make_filename(char *buf, size_t buf_size,struct thread_options *o,
959                            const char *jobname, int jobnum, int filenum)
960 {
961         struct fpre_keyword *f;
962         char copy[PATH_MAX];
963         size_t dst_left = PATH_MAX - 1;
964
965         if (!o->filename_format || !strlen(o->filename_format)) {
966                 sprintf(buf, "%s.%d.%d", jobname, jobnum, filenum);
967                 return NULL;
968         }
969
970         for (f = &fpre_keywords[0]; f->keyword; f++)
971                 f->strlen = strlen(f->keyword);
972
973         buf[buf_size - 1] = '\0';
974         strncpy(buf, o->filename_format, buf_size - 1);
975
976         memset(copy, 0, sizeof(copy));
977         for (f = &fpre_keywords[0]; f->keyword; f++) {
978                 do {
979                         size_t pre_len, post_start = 0;
980                         char *str, *dst = copy;
981
982                         str = strcasestr(buf, f->keyword);
983                         if (!str)
984                                 break;
985
986                         pre_len = str - buf;
987                         if (strlen(str) != f->strlen)
988                                 post_start = pre_len + f->strlen;
989
990                         if (pre_len) {
991                                 strncpy(dst, buf, pre_len);
992                                 dst += pre_len;
993                                 dst_left -= pre_len;
994                         }
995
996                         switch (f->key) {
997                         case FPRE_JOBNAME: {
998                                 int ret;
999
1000                                 ret = snprintf(dst, dst_left, "%s", jobname);
1001                                 if (ret < 0)
1002                                         break;
1003                                 dst += ret;
1004                                 dst_left -= ret;
1005                                 break;
1006                                 }
1007                         case FPRE_JOBNUM: {
1008                                 int ret;
1009
1010                                 ret = snprintf(dst, dst_left, "%d", jobnum);
1011                                 if (ret < 0)
1012                                         break;
1013                                 dst += ret;
1014                                 dst_left -= ret;
1015                                 break;
1016                                 }
1017                         case FPRE_FILENUM: {
1018                                 int ret;
1019
1020                                 ret = snprintf(dst, dst_left, "%d", filenum);
1021                                 if (ret < 0)
1022                                         break;
1023                                 dst += ret;
1024                                 dst_left -= ret;
1025                                 break;
1026                                 }
1027                         default:
1028                                 assert(0);
1029                                 break;
1030                         }
1031
1032                         if (post_start)
1033                                 strncpy(dst, buf + post_start, dst_left);
1034
1035                         strncpy(buf, copy, buf_size - 1);
1036                 } while (1);
1037         }
1038
1039         return buf;
1040 }
1041
1042 int parse_dryrun(void)
1043 {
1044         return dump_cmdline || parse_only;
1045 }
1046
1047 /*
1048  * Adds a job to the list of things todo. Sanitizes the various options
1049  * to make sure we don't have conflicts, and initializes various
1050  * members of td.
1051  */
1052 static int add_job(struct thread_data *td, const char *jobname, int job_add_num,
1053                    int recursed, int client_type)
1054 {
1055         unsigned int i;
1056         char fname[PATH_MAX];
1057         int numjobs, file_alloced;
1058         struct thread_options *o = &td->o;
1059
1060         /*
1061          * the def_thread is just for options, it's not a real job
1062          */
1063         if (td == &def_thread)
1064                 return 0;
1065
1066         init_flags(td);
1067
1068         /*
1069          * if we are just dumping the output command line, don't add the job
1070          */
1071         if (parse_dryrun()) {
1072                 put_job(td);
1073                 return 0;
1074         }
1075
1076         td->client_type = client_type;
1077
1078         if (profile_td_init(td))
1079                 goto err;
1080
1081         if (ioengine_load(td))
1082                 goto err;
1083
1084         if (o->odirect)
1085                 td->io_ops->flags |= FIO_RAWIO;
1086
1087         file_alloced = 0;
1088         if (!o->filename && !td->files_index && !o->read_iolog_file) {
1089                 file_alloced = 1;
1090
1091                 if (o->nr_files == 1 && exists_and_not_file(jobname))
1092                         add_file(td, jobname, job_add_num, 0);
1093                 else {
1094                         for (i = 0; i < o->nr_files; i++)
1095                                 add_file(td, make_filename(fname, sizeof(fname), o, jobname, job_add_num, i), job_add_num, 0);
1096                 }
1097         }
1098
1099         if (fixup_options(td))
1100                 goto err;
1101
1102         flow_init_job(td);
1103
1104         /*
1105          * IO engines only need this for option callbacks, and the address may
1106          * change in subprocesses.
1107          */
1108         if (td->eo)
1109                 *(struct thread_data **)td->eo = NULL;
1110
1111         if (td->io_ops->flags & FIO_DISKLESSIO) {
1112                 struct fio_file *f;
1113
1114                 for_each_file(td, f, i)
1115                         f->real_file_size = -1ULL;
1116         }
1117
1118         td->mutex = fio_mutex_init(FIO_MUTEX_LOCKED);
1119
1120         td->ts.clat_percentiles = o->clat_percentiles;
1121         td->ts.percentile_precision = o->percentile_precision;
1122         memcpy(td->ts.percentile_list, o->percentile_list, sizeof(o->percentile_list));
1123
1124         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1125                 td->ts.clat_stat[i].min_val = ULONG_MAX;
1126                 td->ts.slat_stat[i].min_val = ULONG_MAX;
1127                 td->ts.lat_stat[i].min_val = ULONG_MAX;
1128                 td->ts.bw_stat[i].min_val = ULONG_MAX;
1129         }
1130         td->ddir_seq_nr = o->ddir_seq_nr;
1131
1132         if ((o->stonewall || o->new_group) && prev_group_jobs) {
1133                 prev_group_jobs = 0;
1134                 groupid++;
1135         }
1136
1137         td->groupid = groupid;
1138         prev_group_jobs++;
1139
1140         if (setup_random_seeds(td)) {
1141                 td_verror(td, errno, "init_random_state");
1142                 goto err;
1143         }
1144
1145         if (setup_rate(td))
1146                 goto err;
1147
1148         if (o->lat_log_file || write_lat_log) {
1149                 setup_log(&td->lat_log, o->log_avg_msec, IO_LOG_TYPE_LAT,
1150                                 o->log_offset);
1151                 setup_log(&td->slat_log, o->log_avg_msec, IO_LOG_TYPE_SLAT,
1152                                 o->log_offset);
1153                 setup_log(&td->clat_log, o->log_avg_msec, IO_LOG_TYPE_CLAT,
1154                                 o->log_offset);
1155         }
1156         if (o->bw_log_file || write_bw_log)
1157                 setup_log(&td->bw_log, o->log_avg_msec, IO_LOG_TYPE_BW,
1158                                 o->log_offset);
1159         if (o->iops_log_file)
1160                 setup_log(&td->iops_log, o->log_avg_msec, IO_LOG_TYPE_IOPS,
1161                                 o->log_offset);
1162
1163         if (!o->name)
1164                 o->name = strdup(jobname);
1165
1166         if (output_format == FIO_OUTPUT_NORMAL) {
1167                 if (!job_add_num) {
1168                         if (is_backend && !recursed)
1169                                 fio_server_send_add_job(td);
1170
1171                         if (!(td->io_ops->flags & FIO_NOIO)) {
1172                                 char *c1, *c2, *c3, *c4;
1173                                 char *c5 = NULL, *c6 = NULL;
1174
1175                                 c1 = fio_uint_to_kmg(o->min_bs[DDIR_READ]);
1176                                 c2 = fio_uint_to_kmg(o->max_bs[DDIR_READ]);
1177                                 c3 = fio_uint_to_kmg(o->min_bs[DDIR_WRITE]);
1178                                 c4 = fio_uint_to_kmg(o->max_bs[DDIR_WRITE]);
1179
1180                                 if (!o->bs_is_seq_rand) {
1181                                         c5 = fio_uint_to_kmg(o->min_bs[DDIR_TRIM]);
1182                                         c6 = fio_uint_to_kmg(o->max_bs[DDIR_TRIM]);
1183                                 }
1184
1185                                 log_info("%s: (g=%d): rw=%s, ", td->o.name,
1186                                                         td->groupid,
1187                                                         ddir_str(o->td_ddir));
1188
1189                                 if (o->bs_is_seq_rand)
1190                                         log_info("bs(seq/rand)=%s-%s/%s-%s, ",
1191                                                         c1, c2, c3, c4);
1192                                 else
1193                                         log_info("bs=%s-%s/%s-%s/%s-%s, ",
1194                                                         c1, c2, c3, c4, c5, c6);
1195
1196                                 log_info("ioengine=%s, iodepth=%u\n",
1197                                                 td->io_ops->name, o->iodepth);
1198
1199                                 free(c1);
1200                                 free(c2);
1201                                 free(c3);
1202                                 free(c4);
1203                                 free(c5);
1204                                 free(c6);
1205                         }
1206                 } else if (job_add_num == 1)
1207                         log_info("...\n");
1208         }
1209
1210         /*
1211          * recurse add identical jobs, clear numjobs and stonewall options
1212          * as they don't apply to sub-jobs
1213          */
1214         numjobs = o->numjobs;
1215         while (--numjobs) {
1216                 struct thread_data *td_new = get_new_job(0, td, 1, jobname);
1217
1218                 if (!td_new)
1219                         goto err;
1220
1221                 td_new->o.numjobs = 1;
1222                 td_new->o.stonewall = 0;
1223                 td_new->o.new_group = 0;
1224
1225                 if (file_alloced) {
1226                         if (td_new->files) {
1227                                 struct fio_file *f;
1228                                 for_each_file(td_new, f, i) {
1229                                         if (f->file_name)
1230                                                 sfree(f->file_name);
1231                                         sfree(f);
1232                                 }
1233                                 free(td_new->files);
1234                                 td_new->files = NULL;
1235                         }
1236                         td_new->files_index = 0;
1237                         td_new->files_size = 0;
1238                         if (td_new->o.filename) {
1239                                 free(td_new->o.filename);
1240                                 td_new->o.filename = NULL;
1241                         }
1242                 }
1243
1244                 if (add_job(td_new, jobname, numjobs, 1, client_type))
1245                         goto err;
1246         }
1247
1248         return 0;
1249 err:
1250         put_job(td);
1251         return -1;
1252 }
1253
1254 /*
1255  * Parse as if 'o' was a command line
1256  */
1257 void add_job_opts(const char **o, int client_type)
1258 {
1259         struct thread_data *td, *td_parent;
1260         int i, in_global = 1;
1261         char jobname[32];
1262
1263         i = 0;
1264         td_parent = td = NULL;
1265         while (o[i]) {
1266                 if (!strncmp(o[i], "name", 4)) {
1267                         in_global = 0;
1268                         if (td)
1269                                 add_job(td, jobname, 0, 0, client_type);
1270                         td = NULL;
1271                         sprintf(jobname, "%s", o[i] + 5);
1272                 }
1273                 if (in_global && !td_parent)
1274                         td_parent = get_new_job(1, &def_thread, 0, jobname);
1275                 else if (!in_global && !td) {
1276                         if (!td_parent)
1277                                 td_parent = &def_thread;
1278                         td = get_new_job(0, td_parent, 0, jobname);
1279                 }
1280                 if (in_global)
1281                         fio_options_parse(td_parent, (char **) &o[i], 1, 0);
1282                 else
1283                         fio_options_parse(td, (char **) &o[i], 1, 0);
1284                 i++;
1285         }
1286
1287         if (td)
1288                 add_job(td, jobname, 0, 0, client_type);
1289 }
1290
1291 static int skip_this_section(const char *name)
1292 {
1293         int i;
1294
1295         if (!nr_job_sections)
1296                 return 0;
1297         if (!strncmp(name, "global", 6))
1298                 return 0;
1299
1300         for (i = 0; i < nr_job_sections; i++)
1301                 if (!strcmp(job_sections[i], name))
1302                         return 0;
1303
1304         return 1;
1305 }
1306
1307 static int is_empty_or_comment(char *line)
1308 {
1309         unsigned int i;
1310
1311         for (i = 0; i < strlen(line); i++) {
1312                 if (line[i] == ';')
1313                         return 1;
1314                 if (line[i] == '#')
1315                         return 1;
1316                 if (!isspace((int) line[i]) && !iscntrl((int) line[i]))
1317                         return 0;
1318         }
1319
1320         return 1;
1321 }
1322
1323 /*
1324  * This is our [ini] type file parser.
1325  */
1326 int parse_jobs_ini(char *file, int is_buf, int stonewall_flag, int type)
1327 {
1328         unsigned int global;
1329         struct thread_data *td;
1330         char *string, *name;
1331         FILE *f;
1332         char *p;
1333         int ret = 0, stonewall;
1334         int first_sect = 1;
1335         int skip_fgets = 0;
1336         int inside_skip = 0;
1337         char **opts;
1338         int i, alloc_opts, num_opts;
1339
1340         if (is_buf)
1341                 f = NULL;
1342         else {
1343                 if (!strcmp(file, "-"))
1344                         f = stdin;
1345                 else
1346                         f = fopen(file, "r");
1347
1348                 if (!f) {
1349                         perror("fopen job file");
1350                         return 1;
1351                 }
1352         }
1353
1354         string = malloc(4096);
1355
1356         /*
1357          * it's really 256 + small bit, 280 should suffice
1358          */
1359         name = malloc(280);
1360         memset(name, 0, 280);
1361
1362         alloc_opts = 8;
1363         opts = malloc(sizeof(char *) * alloc_opts);
1364         num_opts = 0;
1365
1366         stonewall = stonewall_flag;
1367         do {
1368                 /*
1369                  * if skip_fgets is set, we already have loaded a line we
1370                  * haven't handled.
1371                  */
1372                 if (!skip_fgets) {
1373                         if (is_buf)
1374                                 p = strsep(&file, "\n");
1375                         else
1376                                 p = fgets(string, 4096, f);
1377                         if (!p)
1378                                 break;
1379                 }
1380
1381                 skip_fgets = 0;
1382                 strip_blank_front(&p);
1383                 strip_blank_end(p);
1384
1385                 if (is_empty_or_comment(p))
1386                         continue;
1387                 if (sscanf(p, "[%255[^\n]]", name) != 1) {
1388                         if (inside_skip)
1389                                 continue;
1390                         log_err("fio: option <%s> outside of [] job section\n",
1391                                                                         p);
1392                         break;
1393                 }
1394
1395                 name[strlen(name) - 1] = '\0';
1396
1397                 if (skip_this_section(name)) {
1398                         inside_skip = 1;
1399                         continue;
1400                 } else
1401                         inside_skip = 0;
1402
1403                 global = !strncmp(name, "global", 6);
1404
1405                 if (dump_cmdline) {
1406                         if (first_sect)
1407                                 log_info("fio ");
1408                         if (!global)
1409                                 log_info("--name=%s ", name);
1410                         first_sect = 0;
1411                 }
1412
1413                 td = get_new_job(global, &def_thread, 0, name);
1414                 if (!td) {
1415                         ret = 1;
1416                         break;
1417                 }
1418
1419                 /*
1420                  * Separate multiple job files by a stonewall
1421                  */
1422                 if (!global && stonewall) {
1423                         td->o.stonewall = stonewall;
1424                         stonewall = 0;
1425                 }
1426
1427                 num_opts = 0;
1428                 memset(opts, 0, alloc_opts * sizeof(char *));
1429
1430                 while (1) {
1431                         if (is_buf)
1432                                 p = strsep(&file, "\n");
1433                         else
1434                                 p = fgets(string, 4096, f);
1435                         if (!p)
1436                                 break;
1437
1438                         if (is_empty_or_comment(p))
1439                                 continue;
1440
1441                         strip_blank_front(&p);
1442
1443                         /*
1444                          * new section, break out and make sure we don't
1445                          * fgets() a new line at the top.
1446                          */
1447                         if (p[0] == '[') {
1448                                 skip_fgets = 1;
1449                                 break;
1450                         }
1451
1452                         strip_blank_end(p);
1453
1454                         if (num_opts == alloc_opts) {
1455                                 alloc_opts <<= 1;
1456                                 opts = realloc(opts,
1457                                                 alloc_opts * sizeof(char *));
1458                         }
1459
1460                         opts[num_opts] = strdup(p);
1461                         num_opts++;
1462                 }
1463
1464                 ret = fio_options_parse(td, opts, num_opts, dump_cmdline);
1465                 if (!ret)
1466                         ret = add_job(td, name, 0, 0, type);
1467                 else {
1468                         log_err("fio: job %s dropped\n", name);
1469                         put_job(td);
1470                 }
1471
1472                 for (i = 0; i < num_opts; i++)
1473                         free(opts[i]);
1474                 num_opts = 0;
1475         } while (!ret);
1476
1477         if (dump_cmdline)
1478                 log_info("\n");
1479
1480         i = 0;
1481         while (i < nr_job_sections) {
1482                 free(job_sections[i]);
1483                 i++;
1484         }
1485
1486         free(string);
1487         free(name);
1488         free(opts);
1489         if (!is_buf && f != stdin)
1490                 fclose(f);
1491         return ret;
1492 }
1493
1494 static int fill_def_thread(void)
1495 {
1496         memset(&def_thread, 0, sizeof(def_thread));
1497
1498         fio_getaffinity(getpid(), &def_thread.o.cpumask);
1499         def_thread.o.error_dump = 1;
1500
1501         /*
1502          * fill default options
1503          */
1504         fio_fill_default_options(&def_thread);
1505         return 0;
1506 }
1507
1508 static void usage(const char *name)
1509 {
1510         printf("%s\n", fio_version_string);
1511         printf("%s [options] [job options] <job file(s)>\n", name);
1512         printf("  --debug=options\tEnable debug logging. May be one/more of:\n"
1513                 "\t\t\tprocess,file,io,mem,blktrace,verify,random,parse,\n"
1514                 "\t\t\tdiskutil,job,mutex,profile,time,net,rate\n");
1515         printf("  --parse-only\t\tParse options only, don't start any IO\n");
1516         printf("  --output\t\tWrite output to file\n");
1517         printf("  --runtime\t\tRuntime in seconds\n");
1518         printf("  --latency-log\t\tGenerate per-job latency logs\n");
1519         printf("  --bandwidth-log\tGenerate per-job bandwidth logs\n");
1520         printf("  --minimal\t\tMinimal (terse) output\n");
1521         printf("  --output-format=x\tOutput format (terse,json,normal)\n");
1522         printf("  --terse-version=x\tSet terse version output format to 'x'\n");
1523         printf("  --version\t\tPrint version info and exit\n");
1524         printf("  --help\t\tPrint this page\n");
1525         printf("  --cpuclock-test\tPerform test/validation of CPU clock\n");
1526         printf("  --crctest\t\tTest speed of checksum functions\n");
1527         printf("  --cmdhelp=cmd\t\tPrint command help, \"all\" for all of"
1528                 " them\n");
1529         printf("  --enghelp=engine\tPrint ioengine help, or list"
1530                 " available ioengines\n");
1531         printf("  --enghelp=engine,cmd\tPrint help for an ioengine"
1532                 " cmd\n");
1533         printf("  --showcmd\t\tTurn a job file into command line options\n");
1534         printf("  --eta=when\t\tWhen ETA estimate should be printed\n");
1535         printf("            \t\tMay be \"always\", \"never\" or \"auto\"\n");
1536         printf("  --eta-newline=time\tForce a new line for every 'time'");
1537         printf(" period passed\n");
1538         printf("  --status-interval=t\tForce full status dump every");
1539         printf(" 't' period passed\n");
1540         printf("  --readonly\t\tTurn on safety read-only checks, preventing"
1541                 " writes\n");
1542         printf("  --section=name\tOnly run specified section in job file\n");
1543         printf("  --alloc-size=kb\tSet smalloc pool to this size in kb"
1544                 " (def 1024)\n");
1545         printf("  --warnings-fatal\tFio parser warnings are fatal\n");
1546         printf("  --max-jobs=nr\t\tMaximum number of threads/processes to support\n");
1547         printf("  --server=args\t\tStart a backend fio server\n");
1548         printf("  --daemonize=pidfile\tBackground fio server, write pid to file\n");
1549         printf("  --client=hostname\tTalk to remote backend fio server at hostname\n");
1550         printf("  --idle-prof=option\tReport cpu idleness on a system or percpu basis\n"
1551                 "\t\t\t(option=system,percpu) or run unit work\n"
1552                 "\t\t\tcalibration only (option=calibrate)\n");
1553         printf("\nFio was written by Jens Axboe <jens.axboe@oracle.com>");
1554         printf("\n                   Jens Axboe <jaxboe@fusionio.com>");
1555         printf("\n                   Jens Axboe <axboe@fb.com>\n");
1556 }
1557
1558 #ifdef FIO_INC_DEBUG
1559 struct debug_level debug_levels[] = {
1560         { .name = "process",
1561           .help = "Process creation/exit logging",
1562           .shift = FD_PROCESS,
1563         },
1564         { .name = "file",
1565           .help = "File related action logging",
1566           .shift = FD_FILE,
1567         },
1568         { .name = "io",
1569           .help = "IO and IO engine action logging (offsets, queue, completions, etc)",
1570           .shift = FD_IO,
1571         },
1572         { .name = "mem",
1573           .help = "Memory allocation/freeing logging",
1574           .shift = FD_MEM,
1575         },
1576         { .name = "blktrace",
1577           .help = "blktrace action logging",
1578           .shift = FD_BLKTRACE,
1579         },
1580         { .name = "verify",
1581           .help = "IO verification action logging",
1582           .shift = FD_VERIFY,
1583         },
1584         { .name = "random",
1585           .help = "Random generation logging",
1586           .shift = FD_RANDOM,
1587         },
1588         { .name = "parse",
1589           .help = "Parser logging",
1590           .shift = FD_PARSE,
1591         },
1592         { .name = "diskutil",
1593           .help = "Disk utility logging actions",
1594           .shift = FD_DISKUTIL,
1595         },
1596         { .name = "job",
1597           .help = "Logging related to creating/destroying jobs",
1598           .shift = FD_JOB,
1599         },
1600         { .name = "mutex",
1601           .help = "Mutex logging",
1602           .shift = FD_MUTEX
1603         },
1604         { .name = "profile",
1605           .help = "Logging related to profiles",
1606           .shift = FD_PROFILE,
1607         },
1608         { .name = "time",
1609           .help = "Logging related to time keeping functions",
1610           .shift = FD_TIME,
1611         },
1612         { .name = "net",
1613           .help = "Network logging",
1614           .shift = FD_NET,
1615         },
1616         { .name = "rate",
1617           .help = "Rate logging",
1618           .shift = FD_RATE,
1619         },
1620         { .name = NULL, },
1621 };
1622
1623 static int set_debug(const char *string)
1624 {
1625         struct debug_level *dl;
1626         char *p = (char *) string;
1627         char *opt;
1628         int i;
1629
1630         if (!strcmp(string, "?") || !strcmp(string, "help")) {
1631                 log_info("fio: dumping debug options:");
1632                 for (i = 0; debug_levels[i].name; i++) {
1633                         dl = &debug_levels[i];
1634                         log_info("%s,", dl->name);
1635                 }
1636                 log_info("all\n");
1637                 return 1;
1638         }
1639
1640         while ((opt = strsep(&p, ",")) != NULL) {
1641                 int found = 0;
1642
1643                 if (!strncmp(opt, "all", 3)) {
1644                         log_info("fio: set all debug options\n");
1645                         fio_debug = ~0UL;
1646                         continue;
1647                 }
1648
1649                 for (i = 0; debug_levels[i].name; i++) {
1650                         dl = &debug_levels[i];
1651                         found = !strncmp(opt, dl->name, strlen(dl->name));
1652                         if (!found)
1653                                 continue;
1654
1655                         if (dl->shift == FD_JOB) {
1656                                 opt = strchr(opt, ':');
1657                                 if (!opt) {
1658                                         log_err("fio: missing job number\n");
1659                                         break;
1660                                 }
1661                                 opt++;
1662                                 fio_debug_jobno = atoi(opt);
1663                                 log_info("fio: set debug jobno %d\n",
1664                                                         fio_debug_jobno);
1665                         } else {
1666                                 log_info("fio: set debug option %s\n", opt);
1667                                 fio_debug |= (1UL << dl->shift);
1668                         }
1669                         break;
1670                 }
1671
1672                 if (!found)
1673                         log_err("fio: debug mask %s not found\n", opt);
1674         }
1675         return 0;
1676 }
1677 #else
1678 static int set_debug(const char *string)
1679 {
1680         log_err("fio: debug tracing not included in build\n");
1681         return 1;
1682 }
1683 #endif
1684
1685 static void fio_options_fill_optstring(void)
1686 {
1687         char *ostr = cmd_optstr;
1688         int i, c;
1689
1690         c = i = 0;
1691         while (l_opts[i].name) {
1692                 ostr[c++] = l_opts[i].val;
1693                 if (l_opts[i].has_arg == required_argument)
1694                         ostr[c++] = ':';
1695                 else if (l_opts[i].has_arg == optional_argument) {
1696                         ostr[c++] = ':';
1697                         ostr[c++] = ':';
1698                 }
1699                 i++;
1700         }
1701         ostr[c] = '\0';
1702 }
1703
1704 static int client_flag_set(char c)
1705 {
1706         int i;
1707
1708         i = 0;
1709         while (l_opts[i].name) {
1710                 int val = l_opts[i].val;
1711
1712                 if (c == (val & 0xff))
1713                         return (val & FIO_CLIENT_FLAG);
1714
1715                 i++;
1716         }
1717
1718         return 0;
1719 }
1720
1721 static void parse_cmd_client(void *client, char *opt)
1722 {
1723         fio_client_add_cmd_option(client, opt);
1724 }
1725
1726 int parse_cmd_line(int argc, char *argv[], int client_type)
1727 {
1728         struct thread_data *td = NULL;
1729         int c, ini_idx = 0, lidx, ret = 0, do_exit = 0, exit_val = 0;
1730         char *ostr = cmd_optstr;
1731         void *pid_file = NULL;
1732         void *cur_client = NULL;
1733         int backend = 0;
1734
1735         /*
1736          * Reset optind handling, since we may call this multiple times
1737          * for the backend.
1738          */
1739         optind = 1;
1740
1741         while ((c = getopt_long_only(argc, argv, ostr, l_opts, &lidx)) != -1) {
1742                 if ((c & FIO_CLIENT_FLAG) || client_flag_set(c)) {
1743                         parse_cmd_client(cur_client, argv[optind - 1]);
1744                         c &= ~FIO_CLIENT_FLAG;
1745                 }
1746
1747                 switch (c) {
1748                 case 'a':
1749                         smalloc_pool_size = atoi(optarg);
1750                         break;
1751                 case 't':
1752                         if (check_str_time(optarg, &def_timeout, 1)) {
1753                                 log_err("fio: failed parsing time %s\n", optarg);
1754                                 do_exit++;
1755                                 exit_val = 1;
1756                         }
1757                         break;
1758                 case 'l':
1759                         write_lat_log = 1;
1760                         break;
1761                 case 'b':
1762                         write_bw_log = 1;
1763                         break;
1764                 case 'o':
1765                         if (f_out && f_out != stdout)
1766                                 fclose(f_out);
1767
1768                         f_out = fopen(optarg, "w+");
1769                         if (!f_out) {
1770                                 perror("fopen output");
1771                                 exit(1);
1772                         }
1773                         f_err = f_out;
1774                         break;
1775                 case 'm':
1776                         output_format = FIO_OUTPUT_TERSE;
1777                         break;
1778                 case 'F':
1779                         if (!optarg) {
1780                                 log_err("fio: missing --output-format argument\n");
1781                                 exit_val = 1;
1782                                 do_exit++;
1783                                 break;
1784                         }
1785                         if (!strcmp(optarg, "minimal") ||
1786                             !strcmp(optarg, "terse") ||
1787                             !strcmp(optarg, "csv"))
1788                                 output_format = FIO_OUTPUT_TERSE;
1789                         else if (!strcmp(optarg, "json"))
1790                                 output_format = FIO_OUTPUT_JSON;
1791                         else
1792                                 output_format = FIO_OUTPUT_NORMAL;
1793                         break;
1794                 case 'f':
1795                         append_terse_output = 1;
1796                         break;
1797                 case 'h':
1798                         did_arg = 1;
1799                         if (!cur_client) {
1800                                 usage(argv[0]);
1801                                 do_exit++;
1802                         }
1803                         break;
1804                 case 'c':
1805                         did_arg = 1;
1806                         if (!cur_client) {
1807                                 fio_show_option_help(optarg);
1808                                 do_exit++;
1809                         }
1810                         break;
1811                 case 'i':
1812                         did_arg = 1;
1813                         if (!cur_client) {
1814                                 fio_show_ioengine_help(optarg);
1815                                 do_exit++;
1816                         }
1817                         break;
1818                 case 's':
1819                         did_arg = 1;
1820                         dump_cmdline = 1;
1821                         break;
1822                 case 'r':
1823                         read_only = 1;
1824                         break;
1825                 case 'v':
1826                         did_arg = 1;
1827                         if (!cur_client) {
1828                                 log_info("%s\n", fio_version_string);
1829                                 do_exit++;
1830                         }
1831                         break;
1832                 case 'V':
1833                         terse_version = atoi(optarg);
1834                         if (!(terse_version == 2 || terse_version == 3 ||
1835                              terse_version == 4)) {
1836                                 log_err("fio: bad terse version format\n");
1837                                 exit_val = 1;
1838                                 do_exit++;
1839                         }
1840                         break;
1841                 case 'e':
1842                         if (!strcmp("always", optarg))
1843                                 eta_print = FIO_ETA_ALWAYS;
1844                         else if (!strcmp("never", optarg))
1845                                 eta_print = FIO_ETA_NEVER;
1846                         break;
1847                 case 'E': {
1848                         long long t = 0;
1849
1850                         if (str_to_decimal(optarg, &t, 0, NULL, 1)) {
1851                                 log_err("fio: failed parsing eta time %s\n", optarg);
1852                                 exit_val = 1;
1853                                 do_exit++;
1854                         }
1855                         eta_new_line = t;
1856                         break;
1857                         }
1858                 case 'd':
1859                         if (set_debug(optarg))
1860                                 do_exit++;
1861                         break;
1862                 case 'P':
1863                         did_arg = 1;
1864                         parse_only = 1;
1865                         break;
1866                 case 'x': {
1867                         size_t new_size;
1868
1869                         if (!strcmp(optarg, "global")) {
1870                                 log_err("fio: can't use global as only "
1871                                         "section\n");
1872                                 do_exit++;
1873                                 exit_val = 1;
1874                                 break;
1875                         }
1876                         new_size = (nr_job_sections + 1) * sizeof(char *);
1877                         job_sections = realloc(job_sections, new_size);
1878                         job_sections[nr_job_sections] = strdup(optarg);
1879                         nr_job_sections++;
1880                         break;
1881                         }
1882                 case 'p':
1883                         did_arg = 1;
1884                         if (exec_profile)
1885                                 free(exec_profile);
1886                         exec_profile = strdup(optarg);
1887                         break;
1888                 case FIO_GETOPT_JOB: {
1889                         const char *opt = l_opts[lidx].name;
1890                         char *val = optarg;
1891
1892                         if (!strncmp(opt, "name", 4) && td) {
1893                                 ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
1894                                 if (ret)
1895                                         goto out_free;
1896                                 td = NULL;
1897                                 did_arg = 1;
1898                         }
1899                         if (!td) {
1900                                 int is_section = !strncmp(opt, "name", 4);
1901                                 int global = 0;
1902
1903                                 if (!is_section || !strncmp(val, "global", 6))
1904                                         global = 1;
1905
1906                                 if (is_section && skip_this_section(val))
1907                                         continue;
1908
1909                                 td = get_new_job(global, &def_thread, 1, NULL);
1910                                 if (!td || ioengine_load(td)) {
1911                                         if (td) {
1912                                                 put_job(td);
1913                                                 td = NULL;
1914                                         }
1915                                         do_exit++;
1916                                         break;
1917                                 }
1918                                 fio_options_set_ioengine_opts(l_opts, td);
1919                         }
1920
1921                         if ((!val || !strlen(val)) &&
1922                             l_opts[lidx].has_arg == required_argument) {
1923                                 log_err("fio: option %s requires an argument\n", opt);
1924                                 ret = 1;
1925                         } else
1926                                 ret = fio_cmd_option_parse(td, opt, val);
1927
1928                         if (ret) {
1929                                 if (td) {
1930                                         put_job(td);
1931                                         td = NULL;
1932                                 }
1933                                 do_exit++;
1934                         }
1935
1936                         if (!ret && !strcmp(opt, "ioengine")) {
1937                                 free_ioengine(td);
1938                                 if (ioengine_load(td)) {
1939                                         if (td) {
1940                                                 put_job(td);
1941                                                 td = NULL;
1942                                         }
1943                                         do_exit++;
1944                                         break;
1945                                 }
1946                                 fio_options_set_ioengine_opts(l_opts, td);
1947                         }
1948                         break;
1949                 }
1950                 case FIO_GETOPT_IOENGINE: {
1951                         const char *opt = l_opts[lidx].name;
1952                         char *val = optarg;
1953
1954                         if (!td)
1955                                 break;
1956
1957                         ret = fio_cmd_ioengine_option_parse(td, opt, val);
1958                         break;
1959                 }
1960                 case 'w':
1961                         warnings_fatal = 1;
1962                         break;
1963                 case 'j':
1964                         max_jobs = atoi(optarg);
1965                         if (!max_jobs || max_jobs > REAL_MAX_JOBS) {
1966                                 log_err("fio: invalid max jobs: %d\n", max_jobs);
1967                                 do_exit++;
1968                                 exit_val = 1;
1969                         }
1970                         break;
1971                 case 'S':
1972                         did_arg = 1;
1973 #ifndef CONFIG_NO_SHM
1974                         if (nr_clients) {
1975                                 log_err("fio: can't be both client and server\n");
1976                                 do_exit++;
1977                                 exit_val = 1;
1978                                 break;
1979                         }
1980                         if (optarg)
1981                                 fio_server_set_arg(optarg);
1982                         is_backend = 1;
1983                         backend = 1;
1984 #else
1985                         log_err("fio: client/server requires SHM support\n");
1986                         do_exit++;
1987                         exit_val = 1;
1988 #endif
1989                         break;
1990                 case 'D':
1991                         if (pid_file)
1992                                 free(pid_file);
1993                         pid_file = strdup(optarg);
1994                         break;
1995                 case 'I':
1996                         if ((ret = fio_idle_prof_parse_opt(optarg))) {
1997                                 /* exit on error and calibration only */
1998                                 did_arg = 1;
1999                                 do_exit++;
2000                                 if (ret == -1)
2001                                         exit_val = 1;
2002                         }
2003                         break;
2004                 case 'C':
2005                         did_arg = 1;
2006                         if (is_backend) {
2007                                 log_err("fio: can't be both client and server\n");
2008                                 do_exit++;
2009                                 exit_val = 1;
2010                                 break;
2011                         }
2012                         if (fio_client_add(&fio_client_ops, optarg, &cur_client)) {
2013                                 log_err("fio: failed adding client %s\n", optarg);
2014                                 do_exit++;
2015                                 exit_val = 1;
2016                                 break;
2017                         }
2018                         /*
2019                          * If the next argument exists and isn't an option,
2020                          * assume it's a job file for this client only.
2021                          */
2022                         while (optind < argc) {
2023                                 if (!strncmp(argv[optind], "--", 2) ||
2024                                     !strncmp(argv[optind], "-", 1))
2025                                         break;
2026
2027                                 fio_client_add_ini_file(cur_client, argv[optind]);
2028                                 optind++;
2029                         }
2030                         break;
2031                 case 'T':
2032                         did_arg = 1;
2033                         do_exit++;
2034                         exit_val = fio_monotonic_clocktest();
2035                         break;
2036                 case 'G':
2037                         did_arg = 1;
2038                         do_exit++;
2039                         exit_val = fio_crctest(optarg);
2040                         break;
2041                 case 'L': {
2042                         long long val;
2043
2044                         if (check_str_time(optarg, &val, 0)) {
2045                                 log_err("fio: failed parsing time %s\n", optarg);
2046                                 do_exit++;
2047                                 exit_val = 1;
2048                                 break;
2049                         }
2050                         status_interval = val * 1000;
2051                         break;
2052                         }
2053                 case '?':
2054                         log_err("%s: unrecognized option '%s'\n", argv[0],
2055                                                         argv[optind - 1]);
2056                 default:
2057                         do_exit++;
2058                         exit_val = 1;
2059                         break;
2060                 }
2061                 if (do_exit)
2062                         break;
2063         }
2064
2065         if (do_exit && !(is_backend || nr_clients))
2066                 exit(exit_val);
2067
2068         if (nr_clients && fio_clients_connect())
2069                 exit(1);
2070
2071         if (is_backend && backend)
2072                 return fio_start_server(pid_file);
2073         else if (pid_file)
2074                 free(pid_file);
2075
2076         if (td) {
2077                 if (!ret) {
2078                         ret = add_job(td, td->o.name ?: "fio", 0, 0, client_type);
2079                         if (ret)
2080                                 did_arg = 1;
2081                 }
2082         }
2083
2084         while (!ret && optind < argc) {
2085                 ini_idx++;
2086                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
2087                 ini_file[ini_idx - 1] = strdup(argv[optind]);
2088                 optind++;
2089         }
2090
2091 out_free:
2092         if (pid_file)
2093                 free(pid_file);
2094
2095         return ini_idx;
2096 }
2097
2098 int fio_init_options(void)
2099 {
2100         f_out = stdout;
2101         f_err = stderr;
2102
2103         fio_options_fill_optstring();
2104         fio_options_dup_and_init(l_opts);
2105
2106         atexit(free_shm);
2107
2108         if (fill_def_thread())
2109                 return 1;
2110
2111         return 0;
2112 }
2113
2114 extern int fio_check_options(struct thread_options *);
2115
2116 int parse_options(int argc, char *argv[])
2117 {
2118         const int type = FIO_CLIENT_TYPE_CLI;
2119         int job_files, i;
2120
2121         if (fio_init_options())
2122                 return 1;
2123         if (fio_test_cconv(&def_thread.o))
2124                 log_err("fio: failed internal cconv test\n");
2125
2126         job_files = parse_cmd_line(argc, argv, type);
2127
2128         if (job_files > 0) {
2129                 for (i = 0; i < job_files; i++) {
2130                         if (i && fill_def_thread())
2131                                 return 1;
2132                         if (nr_clients) {
2133                                 if (fio_clients_send_ini(ini_file[i]))
2134                                         return 1;
2135                                 free(ini_file[i]);
2136                         } else if (!is_backend) {
2137                                 if (parse_jobs_ini(ini_file[i], 0, i, type))
2138                                         return 1;
2139                                 free(ini_file[i]);
2140                         }
2141                 }
2142         } else if (nr_clients) {
2143                 if (fill_def_thread())
2144                         return 1;
2145                 if (fio_clients_send_ini(NULL))
2146                         return 1;
2147         }
2148
2149         free(ini_file);
2150         fio_options_free(&def_thread);
2151         filesetup_mem_free();
2152
2153         if (!thread_number) {
2154                 if (parse_dryrun())
2155                         return 0;
2156                 if (exec_profile)
2157                         return 0;
2158                 if (is_backend || nr_clients)
2159                         return 0;
2160                 if (did_arg)
2161                         return 0;
2162
2163                 log_err("No jobs(s) defined\n\n");
2164
2165                 if (!did_arg) {
2166                         usage(argv[0]);
2167                         return 1;
2168                 }
2169
2170                 return 0;
2171         }
2172
2173         if (def_thread.o.gtod_offload) {
2174                 fio_gtod_init();
2175                 fio_gtod_offload = 1;
2176                 fio_gtod_cpu = def_thread.o.gtod_cpu;
2177         }
2178
2179         if (output_format == FIO_OUTPUT_NORMAL)
2180                 log_info("%s\n", fio_version_string);
2181
2182         return 0;
2183 }
2184
2185 void options_default_fill(struct thread_options *o)
2186 {
2187         memcpy(o, &def_thread.o, sizeof(*o));
2188 }