Improve rate accounting
[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 <getopt.h>
12 #include <sys/ipc.h>
13 #include <sys/shm.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16
17 #include "fio.h"
18 #include "parse.h"
19
20 static char fio_version_string[] = "fio 1.14a";
21
22 #define FIO_RANDSEED            (0xb1899bedUL)
23
24 static char **ini_file;
25 static int max_jobs = MAX_JOBS;
26
27 struct thread_data def_thread;
28 struct thread_data *threads = NULL;
29
30 int exitall_on_terminate = 0;
31 int terse_output = 0;
32 unsigned long long mlock_size = 0;
33 FILE *f_out = NULL;
34 FILE *f_err = NULL;
35
36 int write_bw_log = 0;
37
38 static int def_timeout = 0;
39 static int write_lat_log = 0;
40
41 static int prev_group_jobs;
42
43 /*
44  * Command line options. These will contain the above, plus a few
45  * extra that only pertain to fio itself and not jobs.
46  */
47 static struct option long_options[FIO_NR_OPTIONS] = {
48         {
49                 .name           = "output",
50                 .has_arg        = required_argument,
51                 .val            = 'o',
52         },
53         {
54                 .name           = "timeout",
55                 .has_arg        = required_argument,
56                 .val            = 't',
57         },
58         {
59                 .name           = "latency-log",
60                 .has_arg        = required_argument,
61                 .val            = 'l',
62         },
63         {
64                 .name           = "bandwidth-log",
65                 .has_arg        = required_argument,
66                 .val            = 'b',
67         },
68         {
69                 .name           = "minimal",
70                 .has_arg        = optional_argument,
71                 .val            = 'm',
72         },
73         {
74                 .name           = "version",
75                 .has_arg        = no_argument,
76                 .val            = 'v',
77         },
78         {
79                 .name           = "help",
80                 .has_arg        = no_argument,
81                 .val            = 'h',
82         },
83         {
84                 .name           = "cmdhelp",
85                 .has_arg        = optional_argument,
86                 .val            = 'c',
87         },
88         {
89                 .name           = NULL,
90         },
91 };
92
93 FILE *get_f_out()
94 {
95         return f_out;
96 }
97
98 FILE *get_f_err()
99 {
100         return f_err;
101 }
102
103 /*
104  * Return a free job structure.
105  */
106 static struct thread_data *get_new_job(int global, struct thread_data *parent)
107 {
108         struct thread_data *td;
109
110         if (global)
111                 return &def_thread;
112         if (thread_number >= max_jobs)
113                 return NULL;
114
115         td = &threads[thread_number++];
116         *td = *parent;
117
118         td->thread_number = thread_number;
119         return td;
120 }
121
122 static void put_job(struct thread_data *td)
123 {
124         if (td == &def_thread)
125                 return;
126
127         if (td->error)
128                 log_info("fio: %s\n", td->verror);
129
130         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
131         thread_number--;
132 }
133
134 /*
135  * Lazy way of fixing up options that depend on each other. We could also
136  * define option callback handlers, but this is easier.
137  */
138 static int fixup_options(struct thread_data *td)
139 {
140         if (!td->rwmixread && td->rwmixwrite)
141                 td->rwmixread = 100 - td->rwmixwrite;
142
143         if (td->write_iolog_file && td->read_iolog_file) {
144                 log_err("fio: read iolog overrides write_iolog\n");
145                 free(td->write_iolog_file);
146                 td->write_iolog_file = NULL;
147         }
148
149         if (td->io_ops->flags & FIO_SYNCIO)
150                 td->iodepth = 1;
151         else {
152                 if (!td->iodepth)
153                         td->iodepth = td->open_files;
154         }
155
156         /*
157          * only really works for sequential io for now, and with 1 file
158          */
159         if (td->zone_size && td_random(td) && td->open_files == 1)
160                 td->zone_size = 0;
161
162         /*
163          * Reads can do overwrites, we always need to pre-create the file
164          */
165         if (td_read(td) || td_rw(td))
166                 td->overwrite = 1;
167
168         if (!td->min_bs[DDIR_READ])
169                 td->min_bs[DDIR_READ]= td->bs[DDIR_READ];
170         if (!td->max_bs[DDIR_READ])
171                 td->max_bs[DDIR_READ] = td->bs[DDIR_READ];
172         if (!td->min_bs[DDIR_WRITE])
173                 td->min_bs[DDIR_WRITE]= td->bs[DDIR_WRITE];
174         if (!td->max_bs[DDIR_WRITE])
175                 td->max_bs[DDIR_WRITE] = td->bs[DDIR_WRITE];
176
177         td->rw_min_bs = min(td->min_bs[DDIR_READ], td->min_bs[DDIR_WRITE]);
178
179         if (!td->file_size_high)
180                 td->file_size_high = td->file_size_low;
181
182         if (td_read(td) && !td_rw(td))
183                 td->verify = 0;
184
185         if (td->norandommap && td->verify != VERIFY_NONE) {
186                 log_err("fio: norandommap given, verify disabled\n");
187                 td->verify = VERIFY_NONE;
188         }
189         if (td->bs_unaligned && (td->odirect || td->io_ops->flags & FIO_RAWIO))
190                 log_err("fio: bs_unaligned may not work with raw io\n");
191
192         /*
193          * thinktime_spin must be less than thinktime
194          */
195         if (td->thinktime_spin > td->thinktime)
196                 td->thinktime_spin = td->thinktime;
197
198         /*
199          * The low water mark cannot be bigger than the iodepth
200          */
201         if (td->iodepth_low > td->iodepth || !td->iodepth_low) {
202                 /*
203                  * syslet work around - if the workload is sequential,
204                  * we want to let the queue drain all the way down to
205                  * avoid seeking between async threads
206                  */
207                 if (!strcmp(td->io_ops->name, "syslet-rw") && !td_random(td))
208                         td->iodepth_low = 1;
209                 else
210                         td->iodepth_low = td->iodepth;
211         }
212
213         /*
214          * If batch number isn't set, default to the same as iodepth
215          */
216         if (td->iodepth_batch > td->iodepth || !td->iodepth_batch)
217                 td->iodepth_batch = td->iodepth;
218
219         if (td->nr_files > td->files_index)
220                 td->nr_files = td->files_index;
221
222         if (td->open_files > td->nr_files || !td->open_files)
223                 td->open_files = td->nr_files;
224
225         if ((td->rate && td->rate_iops) || (td->ratemin && td->rate_iops_min)) {
226                 log_err("fio: rate and rate_iops are mutually exclusive\n");
227                 return 1;
228         }
229         if ((td->rate < td->ratemin) || (td->rate_iops < td->rate_iops_min)) {
230                 log_err("fio: minimum rate exceeds rate\n");
231                 return 1;
232         }
233
234         return 0;
235 }
236
237 /*
238  * This function leaks the buffer
239  */
240 static char *to_kmg(unsigned int val)
241 {
242         char *buf = malloc(32);
243         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
244         char *p = post;
245
246         do {
247                 if (val & 1023)
248                         break;
249
250                 val >>= 10;
251                 p++;
252         } while (*p);
253
254         snprintf(buf, 31, "%u%c", val, *p);
255         return buf;
256 }
257
258 /* External engines are specified by "external:name.o") */
259 static const char *get_engine_name(const char *str)
260 {
261         char *p = strstr(str, ":");
262
263         if (!p)
264                 return str;
265
266         p++;
267         strip_blank_front(&p);
268         strip_blank_end(p);
269         return p;
270 }
271
272 static int exists_and_not_file(const char *filename)
273 {
274         struct stat sb;
275
276         if (lstat(filename, &sb) == -1)
277                 return 0;
278
279         if (S_ISREG(sb.st_mode))
280                 return 0;
281
282         return 1;
283 }
284
285 /*
286  * Initialize the various random states we need (random io, block size ranges,
287  * read/write mix, etc).
288  */
289 static int init_random_state(struct thread_data *td)
290 {
291         unsigned long seeds[6];
292         int fd, num_maps, blocks;
293         struct fio_file *f;
294         unsigned int i;
295
296         fd = open("/dev/urandom", O_RDONLY);
297         if (fd == -1) {
298                 td_verror(td, errno, "open");
299                 return 1;
300         }
301
302         if (read(fd, seeds, sizeof(seeds)) < (int) sizeof(seeds)) {
303                 td_verror(td, EIO, "read");
304                 close(fd);
305                 return 1;
306         }
307
308         close(fd);
309
310         os_random_seed(seeds[0], &td->bsrange_state);
311         os_random_seed(seeds[1], &td->verify_state);
312         os_random_seed(seeds[2], &td->rwmix_state);
313
314         if (td->file_service_type == FIO_FSERVICE_RANDOM)
315                 os_random_seed(seeds[3], &td->next_file_state);
316
317         os_random_seed(seeds[5], &td->file_size_state);
318
319         if (!td_random(td))
320                 return 0;
321
322         if (td->rand_repeatable)
323                 seeds[4] = FIO_RANDSEED * td->thread_number;
324
325         if (!td->norandommap) {
326                 for_each_file(td, f, i) {
327                         blocks = (f->real_file_size + td->rw_min_bs - 1) / td->rw_min_bs;
328                         num_maps = (blocks + BLOCKS_PER_MAP-1)/ BLOCKS_PER_MAP;
329                         f->file_map = malloc(num_maps * sizeof(long));
330                         if (!f->file_map) {
331                                 log_err("fio: failed allocating random map. If running a large number of jobs, try the 'norandommap' option\n");
332                                 return 1;
333                         }
334                         f->num_maps = num_maps;
335                         memset(f->file_map, 0, num_maps * sizeof(long));
336                 }
337         }
338
339         os_random_seed(seeds[4], &td->random_state);
340         return 0;
341 }
342
343
344 /*
345  * Adds a job to the list of things todo. Sanitizes the various options
346  * to make sure we don't have conflicts, and initializes various
347  * members of td.
348  */
349 static int add_job(struct thread_data *td, const char *jobname, int job_add_num)
350 {
351         const char *ddir_str[] = { NULL, "read", "write", "rw", NULL,
352                                    "randread", "randwrite", "randrw" };
353         unsigned int i;
354         struct fio_file *f;
355         const char *engine;
356         char fname[PATH_MAX];
357         int numjobs, file_alloced;
358
359         /*
360          * the def_thread is just for options, it's not a real job
361          */
362         if (td == &def_thread)
363                 return 0;
364
365         engine = get_engine_name(td->ioengine);
366         td->io_ops = load_ioengine(td, engine);
367         if (!td->io_ops) {
368                 log_err("fio: failed to load engine %s\n", engine);
369                 goto err;
370         }
371
372         if (td->use_thread)
373                 nr_thread++;
374         else
375                 nr_process++;
376
377         if (td->odirect)
378                 td->io_ops->flags |= FIO_RAWIO;
379
380         file_alloced = 0;
381         if (!td->filename && !td->files_index) {
382                 file_alloced = 1;
383
384                 if (td->nr_files == 1 && exists_and_not_file(jobname))
385                         add_file(td, jobname);
386                 else {
387                         for (i = 0; i < td->nr_files; i++) {
388                                 sprintf(fname, "%s.%d.%d", jobname, td->thread_number, i);
389                                 add_file(td, fname);
390                         }
391                 }
392         }
393
394         if (fixup_options(td))
395                 goto err;
396
397         for_each_file(td, f, i) {
398                 if (td->directory && f->filetype == FIO_TYPE_FILE) {
399                         sprintf(fname, "%s/%s", td->directory, f->file_name);
400                         f->file_name = strdup(fname);
401                 }
402         }
403                 
404         td->mutex = fio_sem_init(0);
405
406         td->ts.clat_stat[0].min_val = td->ts.clat_stat[1].min_val = ULONG_MAX;
407         td->ts.slat_stat[0].min_val = td->ts.slat_stat[1].min_val = ULONG_MAX;
408         td->ts.bw_stat[0].min_val = td->ts.bw_stat[1].min_val = ULONG_MAX;
409
410         if ((td->stonewall || td->numjobs > 1) && prev_group_jobs) {
411                 prev_group_jobs = 0;
412                 groupid++;
413         }
414
415         td->groupid = groupid;
416         prev_group_jobs++;
417
418         if (init_random_state(td))
419                 goto err;
420
421         if (setup_rate(td))
422                 goto err;
423
424         if (td->write_lat_log) {
425                 setup_log(&td->ts.slat_log);
426                 setup_log(&td->ts.clat_log);
427         }
428         if (td->write_bw_log)
429                 setup_log(&td->ts.bw_log);
430
431         if (!td->name)
432                 td->name = strdup(jobname);
433
434         if (!terse_output) {
435                 if (!job_add_num) {
436                         if (!strcmp(td->io_ops->name, "cpuio"))
437                                 log_info("%s: ioengine=cpu, cpuload=%u, cpucycle=%u\n", td->name, td->cpuload, td->cpucycle);
438                         else {
439                                 char *c1, *c2, *c3, *c4;
440
441                                 c1 = to_kmg(td->min_bs[DDIR_READ]);
442                                 c2 = to_kmg(td->max_bs[DDIR_READ]);
443                                 c3 = to_kmg(td->min_bs[DDIR_WRITE]);
444                                 c4 = to_kmg(td->max_bs[DDIR_WRITE]);
445
446                                 log_info("%s: (g=%d): rw=%s, bs=%s-%s/%s-%s, ioengine=%s, iodepth=%u\n", td->name, td->groupid, ddir_str[td->td_ddir], c1, c2, c3, c4, td->io_ops->name, td->iodepth);
447
448                                 free(c1);
449                                 free(c2);
450                                 free(c3);
451                                 free(c4);
452                         }
453                 } else if (job_add_num == 1)
454                         log_info("...\n");
455         }
456
457         /*
458          * recurse add identical jobs, clear numjobs and stonewall options
459          * as they don't apply to sub-jobs
460          */
461         numjobs = td->numjobs;
462         while (--numjobs) {
463                 struct thread_data *td_new = get_new_job(0, td);
464
465                 if (!td_new)
466                         goto err;
467
468                 td_new->numjobs = 1;
469                 td_new->stonewall = 0;
470
471                 if (file_alloced) {
472                         td_new->filename = NULL;
473                         td_new->files_index = 0;
474                         td_new->files = NULL;
475                 }
476
477                 job_add_num = numjobs - 1;
478
479                 if (add_job(td_new, jobname, job_add_num))
480                         goto err;
481         }
482
483         if (td->numjobs > 1) {
484                 groupid++;
485                 prev_group_jobs = 0;
486         }
487
488         return 0;
489 err:
490         put_job(td);
491         return -1;
492 }
493
494 static int is_empty_or_comment(char *line)
495 {
496         unsigned int i;
497
498         for (i = 0; i < strlen(line); i++) {
499                 if (line[i] == ';')
500                         return 1;
501                 if (line[i] == '#')
502                         return 1;
503                 if (!isspace(line[i]) && !iscntrl(line[i]))
504                         return 0;
505         }
506
507         return 1;
508 }
509
510 /*
511  * This is our [ini] type file parser.
512  */
513 static int parse_jobs_ini(char *file, int stonewall_flag)
514 {
515         unsigned int global;
516         struct thread_data *td;
517         char *string, *name;
518         fpos_t off;
519         FILE *f;
520         char *p;
521         int ret = 0, stonewall;
522
523         f = fopen(file, "r");
524         if (!f) {
525                 perror("fopen job file");
526                 return 1;
527         }
528
529         string = malloc(4096);
530         name = malloc(256);
531         memset(name, 0, 256);
532
533         stonewall = stonewall_flag;
534         do {
535                 p = fgets(string, 4095, f);
536                 if (!p)
537                         break;
538                 if (is_empty_or_comment(p))
539                         continue;
540                 if (sscanf(p, "[%255s]", name) != 1)
541                         continue;
542
543                 global = !strncmp(name, "global", 6);
544
545                 name[strlen(name) - 1] = '\0';
546
547                 td = get_new_job(global, &def_thread);
548                 if (!td) {
549                         ret = 1;
550                         break;
551                 }
552
553                 /*
554                  * Seperate multiple job files by a stonewall
555                  */
556                 if (!global && stonewall) {
557                         td->stonewall = stonewall;
558                         stonewall = 0;
559                 }
560
561                 fgetpos(f, &off);
562                 while ((p = fgets(string, 4096, f)) != NULL) {
563                         if (is_empty_or_comment(p))
564                                 continue;
565
566                         strip_blank_front(&p);
567
568                         if (p[0] == '[')
569                                 break;
570
571                         strip_blank_end(p);
572
573                         fgetpos(f, &off);
574
575                         /*
576                          * Don't break here, continue parsing options so we
577                          * dump all the bad ones. Makes trial/error fixups
578                          * easier on the user.
579                          */
580                         ret |= fio_option_parse(td, p);
581                 }
582
583                 if (!ret) {
584                         fsetpos(f, &off);
585                         ret = add_job(td, name, 0);
586                 } else {
587                         log_err("fio: job %s dropped\n", name);
588                         put_job(td);
589                 }
590         } while (!ret);
591
592         free(string);
593         free(name);
594         fclose(f);
595         return ret;
596 }
597
598 static int fill_def_thread(void)
599 {
600         memset(&def_thread, 0, sizeof(def_thread));
601
602         if (fio_getaffinity(getpid(), &def_thread.cpumask) == -1) {
603                 perror("sched_getaffinity");
604                 return 1;
605         }
606
607         /*
608          * fill default options
609          */
610         fio_fill_default_options(&def_thread);
611
612         def_thread.timeout = def_timeout;
613         def_thread.write_bw_log = write_bw_log;
614         def_thread.write_lat_log = write_lat_log;
615
616 #ifdef FIO_HAVE_DISK_UTIL
617         def_thread.do_disk_util = 1;
618 #endif
619
620         return 0;
621 }
622
623 static void free_shm(void)
624 {
625         struct shmid_ds sbuf;
626
627         if (threads) {
628                 shmdt((void *) threads);
629                 threads = NULL;
630                 shmctl(shm_id, IPC_RMID, &sbuf);
631         }
632 }
633
634 /*
635  * The thread area is shared between the main process and the job
636  * threads/processes. So setup a shared memory segment that will hold
637  * all the job info.
638  */
639 static int setup_thread_area(void)
640 {
641         /*
642          * 1024 is too much on some machines, scale max_jobs if
643          * we get a failure that looks like too large a shm segment
644          */
645         do {
646                 size_t size = max_jobs * sizeof(struct thread_data);
647
648                 shm_id = shmget(0, size, IPC_CREAT | 0600);
649                 if (shm_id != -1)
650                         break;
651                 if (errno != EINVAL) {
652                         perror("shmget");
653                         break;
654                 }
655
656                 max_jobs >>= 1;
657         } while (max_jobs);
658
659         if (shm_id == -1)
660                 return 1;
661
662         threads = shmat(shm_id, NULL, 0);
663         if (threads == (void *) -1) {
664                 perror("shmat");
665                 return 1;
666         }
667
668         atexit(free_shm);
669         return 0;
670 }
671
672 static void usage(void)
673 {
674         printf("%s\n", fio_version_string);
675         printf("\t--output\tWrite output to file\n");
676         printf("\t--timeout\tRuntime in seconds\n");
677         printf("\t--latency-log\tGenerate per-job latency logs\n");
678         printf("\t--bandwidth-log\tGenerate per-job bandwidth logs\n");
679         printf("\t--minimal\tMinimal (terse) output\n");
680         printf("\t--version\tPrint version info and exit\n");
681         printf("\t--help\t\tPrint this page\n");
682         printf("\t--cmdhelp=cmd\tPrint command help, \"all\" for all of them\n");
683 }
684
685 static int parse_cmd_line(int argc, char *argv[])
686 {
687         struct thread_data *td = NULL;
688         int c, ini_idx = 0, lidx, ret, dont_add_job = 0;
689
690         while ((c = getopt_long_only(argc, argv, "", long_options, &lidx)) != -1) {
691                 switch (c) {
692                 case 't':
693                         def_timeout = atoi(optarg);
694                         break;
695                 case 'l':
696                         write_lat_log = 1;
697                         break;
698                 case 'w':
699                         write_bw_log = 1;
700                         break;
701                 case 'o':
702                         f_out = fopen(optarg, "w+");
703                         if (!f_out) {
704                                 perror("fopen output");
705                                 exit(1);
706                         }
707                         f_err = f_out;
708                         break;
709                 case 'm':
710                         terse_output = 1;
711                         break;
712                 case 'h':
713                         usage();
714                         exit(0);
715                 case 'c':
716                         exit(fio_show_option_help(optarg));
717                 case 'v':
718                         printf("%s\n", fio_version_string);
719                         exit(0);
720                 case FIO_GETOPT_JOB: {
721                         const char *opt = long_options[lidx].name;
722                         char *val = optarg;
723
724                         if (!strncmp(opt, "name", 4) && td) {
725                                 ret = add_job(td, td->name ?: "fio", 0);
726                                 if (ret) {
727                                         put_job(td);
728                                         return 0;
729                                 }
730                                 td = NULL;
731                         }
732                         if (!td) {
733                                 int global = !strncmp(val, "global", 6);
734
735                                 td = get_new_job(global, &def_thread);
736                                 if (!td)
737                                         return 0;
738                         }
739
740                         ret = fio_cmd_option_parse(td, opt, val);
741                         if (ret)
742                                 dont_add_job = 1;
743                         break;
744                 }
745                 default:
746                         break;
747                 }
748         }
749
750         if (td) {
751                 if (dont_add_job)
752                         put_job(td);
753                 else {
754                         ret = add_job(td, td->name ?: "fio", 0);
755                         if (ret)
756                                 put_job(td);
757                 }
758         }
759
760         while (optind < argc) {
761                 ini_idx++;
762                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
763                 ini_file[ini_idx - 1] = strdup(argv[optind]);
764                 optind++;
765         }
766
767         return ini_idx;
768 }
769
770
771 int parse_options(int argc, char *argv[])
772 {
773         int job_files, i;
774
775         f_out = stdout;
776         f_err = stderr;
777
778         fio_options_dup_and_init(long_options);
779
780         if (setup_thread_area())
781                 return 1;
782         if (fill_def_thread())
783                 return 1;
784
785         job_files = parse_cmd_line(argc, argv);
786
787         for (i = 0; i < job_files; i++) {
788                 if (fill_def_thread())
789                         return 1;
790                 if (parse_jobs_ini(ini_file[i], i))
791                         return 1;
792                 free(ini_file[i]);
793         }
794
795         free(ini_file);
796
797         if (!thread_number) {
798                 log_err("No jobs defined(s)\n");
799                 return 1;
800         }
801
802         return 0;
803 }