blockdev_invalidate_cache(): return -1 for error
[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 void 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
226 /*
227  * This function leaks the buffer
228  */
229 static char *to_kmg(unsigned int val)
230 {
231         char *buf = malloc(32);
232         char post[] = { 0, 'K', 'M', 'G', 'P', 'E', 0 };
233         char *p = post;
234
235         do {
236                 if (val & 1023)
237                         break;
238
239                 val >>= 10;
240                 p++;
241         } while (*p);
242
243         snprintf(buf, 31, "%u%c", val, *p);
244         return buf;
245 }
246
247 /* External engines are specified by "external:name.o") */
248 static const char *get_engine_name(const char *str)
249 {
250         char *p = strstr(str, ":");
251
252         if (!p)
253                 return str;
254
255         p++;
256         strip_blank_front(&p);
257         strip_blank_end(p);
258         return p;
259 }
260
261 static int exists_and_not_file(const char *filename)
262 {
263         struct stat sb;
264
265         if (lstat(filename, &sb) == -1)
266                 return 0;
267
268         if (S_ISREG(sb.st_mode))
269                 return 0;
270
271         return 1;
272 }
273
274 /*
275  * Initialize the various random states we need (random io, block size ranges,
276  * read/write mix, etc).
277  */
278 static int init_random_state(struct thread_data *td)
279 {
280         unsigned long seeds[6];
281         int fd, num_maps, blocks;
282         struct fio_file *f;
283         unsigned int i;
284
285         fd = open("/dev/urandom", O_RDONLY);
286         if (fd == -1) {
287                 td_verror(td, errno, "open");
288                 return 1;
289         }
290
291         if (read(fd, seeds, sizeof(seeds)) < (int) sizeof(seeds)) {
292                 td_verror(td, EIO, "read");
293                 close(fd);
294                 return 1;
295         }
296
297         close(fd);
298
299         os_random_seed(seeds[0], &td->bsrange_state);
300         os_random_seed(seeds[1], &td->verify_state);
301         os_random_seed(seeds[2], &td->rwmix_state);
302
303         if (td->file_service_type == FIO_FSERVICE_RANDOM)
304                 os_random_seed(seeds[3], &td->next_file_state);
305
306         os_random_seed(seeds[5], &td->file_size_state);
307
308         if (!td_random(td))
309                 return 0;
310
311         if (td->rand_repeatable)
312                 seeds[4] = FIO_RANDSEED * td->thread_number;
313
314         if (!td->norandommap) {
315                 for_each_file(td, f, i) {
316                         blocks = (f->real_file_size + td->rw_min_bs - 1) / td->rw_min_bs;
317                         num_maps = (blocks + BLOCKS_PER_MAP-1)/ BLOCKS_PER_MAP;
318                         f->file_map = malloc(num_maps * sizeof(long));
319                         if (!f->file_map) {
320                                 log_err("fio: failed allocating random map. If running a large number of jobs, try the 'norandommap' option\n");
321                                 return 1;
322                         }
323                         f->num_maps = num_maps;
324                         memset(f->file_map, 0, num_maps * sizeof(long));
325                 }
326         }
327
328         os_random_seed(seeds[4], &td->random_state);
329         return 0;
330 }
331
332
333 /*
334  * Adds a job to the list of things todo. Sanitizes the various options
335  * to make sure we don't have conflicts, and initializes various
336  * members of td.
337  */
338 static int add_job(struct thread_data *td, const char *jobname, int job_add_num)
339 {
340         const char *ddir_str[] = { NULL, "read", "write", "rw", NULL,
341                                    "randread", "randwrite", "randrw" };
342         unsigned int i;
343         struct fio_file *f;
344         const char *engine;
345         char fname[PATH_MAX];
346         int numjobs, file_alloced;
347
348         /*
349          * the def_thread is just for options, it's not a real job
350          */
351         if (td == &def_thread)
352                 return 0;
353
354         engine = get_engine_name(td->ioengine);
355         td->io_ops = load_ioengine(td, engine);
356         if (!td->io_ops) {
357                 log_err("fio: failed to load engine %s\n", engine);
358                 goto err;
359         }
360
361         if (td->use_thread)
362                 nr_thread++;
363         else
364                 nr_process++;
365
366         if (td->odirect)
367                 td->io_ops->flags |= FIO_RAWIO;
368
369         file_alloced = 0;
370         if (!td->filename && !td->files_index) {
371                 file_alloced = 1;
372
373                 if (td->nr_files == 1 && exists_and_not_file(jobname))
374                         add_file(td, jobname);
375                 else {
376                         for (i = 0; i < td->nr_files; i++) {
377                                 sprintf(fname, "%s.%d.%d", jobname, td->thread_number, i);
378                                 add_file(td, fname);
379                         }
380                 }
381         }
382
383         fixup_options(td);
384
385         for_each_file(td, f, i) {
386                 if (td->directory && f->filetype == FIO_TYPE_FILE) {
387                         sprintf(fname, "%s/%s", td->directory, f->file_name);
388                         f->file_name = strdup(fname);
389                 }
390         }
391                 
392         td->mutex = fio_sem_init(0);
393
394         td->ts.clat_stat[0].min_val = td->ts.clat_stat[1].min_val = ULONG_MAX;
395         td->ts.slat_stat[0].min_val = td->ts.slat_stat[1].min_val = ULONG_MAX;
396         td->ts.bw_stat[0].min_val = td->ts.bw_stat[1].min_val = ULONG_MAX;
397
398         if ((td->stonewall || td->numjobs > 1) && prev_group_jobs) {
399                 prev_group_jobs = 0;
400                 groupid++;
401         }
402
403         td->groupid = groupid;
404         prev_group_jobs++;
405
406         if (init_random_state(td))
407                 goto err;
408
409         if (setup_rate(td))
410                 goto err;
411
412         if (td->write_lat_log) {
413                 setup_log(&td->ts.slat_log);
414                 setup_log(&td->ts.clat_log);
415         }
416         if (td->write_bw_log)
417                 setup_log(&td->ts.bw_log);
418
419         if (!td->name)
420                 td->name = strdup(jobname);
421
422         if (!terse_output) {
423                 if (!job_add_num) {
424                         if (!strcmp(td->io_ops->name, "cpuio"))
425                                 log_info("%s: ioengine=cpu, cpuload=%u, cpucycle=%u\n", td->name, td->cpuload, td->cpucycle);
426                         else {
427                                 char *c1, *c2, *c3, *c4;
428
429                                 c1 = to_kmg(td->min_bs[DDIR_READ]);
430                                 c2 = to_kmg(td->max_bs[DDIR_READ]);
431                                 c3 = to_kmg(td->min_bs[DDIR_WRITE]);
432                                 c4 = to_kmg(td->max_bs[DDIR_WRITE]);
433
434                                 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);
435
436                                 free(c1);
437                                 free(c2);
438                                 free(c3);
439                                 free(c4);
440                         }
441                 } else if (job_add_num == 1)
442                         log_info("...\n");
443         }
444
445         /*
446          * recurse add identical jobs, clear numjobs and stonewall options
447          * as they don't apply to sub-jobs
448          */
449         numjobs = td->numjobs;
450         while (--numjobs) {
451                 struct thread_data *td_new = get_new_job(0, td);
452
453                 if (!td_new)
454                         goto err;
455
456                 td_new->numjobs = 1;
457                 td_new->stonewall = 0;
458
459                 if (file_alloced) {
460                         td_new->filename = NULL;
461                         td_new->files_index = 0;
462                         td_new->files = NULL;
463                 }
464
465                 job_add_num = numjobs - 1;
466
467                 if (add_job(td_new, jobname, job_add_num))
468                         goto err;
469         }
470
471         if (td->numjobs > 1) {
472                 groupid++;
473                 prev_group_jobs = 0;
474         }
475
476         return 0;
477 err:
478         put_job(td);
479         return -1;
480 }
481
482 static int is_empty_or_comment(char *line)
483 {
484         unsigned int i;
485
486         for (i = 0; i < strlen(line); i++) {
487                 if (line[i] == ';')
488                         return 1;
489                 if (line[i] == '#')
490                         return 1;
491                 if (!isspace(line[i]) && !iscntrl(line[i]))
492                         return 0;
493         }
494
495         return 1;
496 }
497
498 /*
499  * This is our [ini] type file parser.
500  */
501 static int parse_jobs_ini(char *file, int stonewall_flag)
502 {
503         unsigned int global;
504         struct thread_data *td;
505         char *string, *name;
506         fpos_t off;
507         FILE *f;
508         char *p;
509         int ret = 0, stonewall;
510
511         f = fopen(file, "r");
512         if (!f) {
513                 perror("fopen job file");
514                 return 1;
515         }
516
517         string = malloc(4096);
518         name = malloc(256);
519         memset(name, 0, 256);
520
521         stonewall = stonewall_flag;
522         do {
523                 p = fgets(string, 4095, f);
524                 if (!p)
525                         break;
526                 if (is_empty_or_comment(p))
527                         continue;
528                 if (sscanf(p, "[%255s]", name) != 1)
529                         continue;
530
531                 global = !strncmp(name, "global", 6);
532
533                 name[strlen(name) - 1] = '\0';
534
535                 td = get_new_job(global, &def_thread);
536                 if (!td) {
537                         ret = 1;
538                         break;
539                 }
540
541                 /*
542                  * Seperate multiple job files by a stonewall
543                  */
544                 if (!global && stonewall) {
545                         td->stonewall = stonewall;
546                         stonewall = 0;
547                 }
548
549                 fgetpos(f, &off);
550                 while ((p = fgets(string, 4096, f)) != NULL) {
551                         if (is_empty_or_comment(p))
552                                 continue;
553
554                         strip_blank_front(&p);
555
556                         if (p[0] == '[')
557                                 break;
558
559                         strip_blank_end(p);
560
561                         fgetpos(f, &off);
562
563                         /*
564                          * Don't break here, continue parsing options so we
565                          * dump all the bad ones. Makes trial/error fixups
566                          * easier on the user.
567                          */
568                         ret |= fio_option_parse(td, p);
569                 }
570
571                 if (!ret) {
572                         fsetpos(f, &off);
573                         ret = add_job(td, name, 0);
574                 } else {
575                         log_err("fio: job %s dropped\n", name);
576                         put_job(td);
577                 }
578         } while (!ret);
579
580         free(string);
581         free(name);
582         fclose(f);
583         return ret;
584 }
585
586 static int fill_def_thread(void)
587 {
588         memset(&def_thread, 0, sizeof(def_thread));
589
590         if (fio_getaffinity(getpid(), &def_thread.cpumask) == -1) {
591                 perror("sched_getaffinity");
592                 return 1;
593         }
594
595         /*
596          * fill default options
597          */
598         fio_fill_default_options(&def_thread);
599
600         def_thread.timeout = def_timeout;
601         def_thread.write_bw_log = write_bw_log;
602         def_thread.write_lat_log = write_lat_log;
603
604 #ifdef FIO_HAVE_DISK_UTIL
605         def_thread.do_disk_util = 1;
606 #endif
607
608         return 0;
609 }
610
611 static void free_shm(void)
612 {
613         struct shmid_ds sbuf;
614
615         if (threads) {
616                 shmdt((void *) threads);
617                 threads = NULL;
618                 shmctl(shm_id, IPC_RMID, &sbuf);
619         }
620 }
621
622 /*
623  * The thread area is shared between the main process and the job
624  * threads/processes. So setup a shared memory segment that will hold
625  * all the job info.
626  */
627 static int setup_thread_area(void)
628 {
629         /*
630          * 1024 is too much on some machines, scale max_jobs if
631          * we get a failure that looks like too large a shm segment
632          */
633         do {
634                 size_t size = max_jobs * sizeof(struct thread_data);
635
636                 shm_id = shmget(0, size, IPC_CREAT | 0600);
637                 if (shm_id != -1)
638                         break;
639                 if (errno != EINVAL) {
640                         perror("shmget");
641                         break;
642                 }
643
644                 max_jobs >>= 1;
645         } while (max_jobs);
646
647         if (shm_id == -1)
648                 return 1;
649
650         threads = shmat(shm_id, NULL, 0);
651         if (threads == (void *) -1) {
652                 perror("shmat");
653                 return 1;
654         }
655
656         atexit(free_shm);
657         return 0;
658 }
659
660 static void usage(void)
661 {
662         printf("%s\n", fio_version_string);
663         printf("\t--output\tWrite output to file\n");
664         printf("\t--timeout\tRuntime in seconds\n");
665         printf("\t--latency-log\tGenerate per-job latency logs\n");
666         printf("\t--bandwidth-log\tGenerate per-job bandwidth logs\n");
667         printf("\t--minimal\tMinimal (terse) output\n");
668         printf("\t--version\tPrint version info and exit\n");
669         printf("\t--help\t\tPrint this page\n");
670         printf("\t--cmdhelp=cmd\tPrint command help, \"all\" for all of them\n");
671 }
672
673 static int parse_cmd_line(int argc, char *argv[])
674 {
675         struct thread_data *td = NULL;
676         int c, ini_idx = 0, lidx, ret, dont_add_job = 0;
677
678         while ((c = getopt_long_only(argc, argv, "", long_options, &lidx)) != -1) {
679                 switch (c) {
680                 case 't':
681                         def_timeout = atoi(optarg);
682                         break;
683                 case 'l':
684                         write_lat_log = 1;
685                         break;
686                 case 'w':
687                         write_bw_log = 1;
688                         break;
689                 case 'o':
690                         f_out = fopen(optarg, "w+");
691                         if (!f_out) {
692                                 perror("fopen output");
693                                 exit(1);
694                         }
695                         f_err = f_out;
696                         break;
697                 case 'm':
698                         terse_output = 1;
699                         break;
700                 case 'h':
701                         usage();
702                         exit(0);
703                 case 'c':
704                         exit(fio_show_option_help(optarg));
705                 case 'v':
706                         printf("%s\n", fio_version_string);
707                         exit(0);
708                 case FIO_GETOPT_JOB: {
709                         const char *opt = long_options[lidx].name;
710                         char *val = optarg;
711
712                         if (!strncmp(opt, "name", 4) && td) {
713                                 ret = add_job(td, td->name ?: "fio", 0);
714                                 if (ret) {
715                                         put_job(td);
716                                         return 0;
717                                 }
718                                 td = NULL;
719                         }
720                         if (!td) {
721                                 int global = !strncmp(val, "global", 6);
722
723                                 td = get_new_job(global, &def_thread);
724                                 if (!td)
725                                         return 0;
726                         }
727
728                         ret = fio_cmd_option_parse(td, opt, val);
729                         if (ret)
730                                 dont_add_job = 1;
731                         break;
732                 }
733                 default:
734                         break;
735                 }
736         }
737
738         if (td) {
739                 if (dont_add_job)
740                         put_job(td);
741                 else {
742                         ret = add_job(td, td->name ?: "fio", 0);
743                         if (ret)
744                                 put_job(td);
745                 }
746         }
747
748         while (optind < argc) {
749                 ini_idx++;
750                 ini_file = realloc(ini_file, ini_idx * sizeof(char *));
751                 ini_file[ini_idx - 1] = strdup(argv[optind]);
752                 optind++;
753         }
754
755         return ini_idx;
756 }
757
758
759 int parse_options(int argc, char *argv[])
760 {
761         int job_files, i;
762
763         f_out = stdout;
764         f_err = stderr;
765
766         fio_options_dup_and_init(long_options);
767
768         if (setup_thread_area())
769                 return 1;
770         if (fill_def_thread())
771                 return 1;
772
773         job_files = parse_cmd_line(argc, argv);
774
775         for (i = 0; i < job_files; i++) {
776                 if (fill_def_thread())
777                         return 1;
778                 if (parse_jobs_ini(ini_file[i], i))
779                         return 1;
780                 free(ini_file[i]);
781         }
782
783         free(ini_file);
784
785         if (!thread_number) {
786                 log_err("No jobs defined(s)\n");
787                 return 1;
788         }
789
790         return 0;
791 }