[PATCH] fio: some verify fixes
[disktools.git] / fio.c
1 /*
2  * fio - the flexible io tester
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <string.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <ctype.h>
30 #include <sched.h>
31 #include <libaio.h>
32 #include <math.h>
33 #include <limits.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <sys/stat.h>
37 #include <sys/wait.h>
38 #include <semaphore.h>
39 #include <sys/ipc.h>
40 #include <sys/shm.h>
41 #include <asm/unistd.h>
42 #include <asm/types.h>
43
44 #include "list.h"
45 #include "md5.h"
46
47 #define MAX_JOBS        (1024)
48
49 /*
50  * assume we don't have _get either, if _set isn't defined
51  */
52 #ifndef __NR_ioprio_set
53 #if defined(__i386__)
54 #define __NR_ioprio_set         289
55 #define __NR_ioprio_get         290
56 #elif defined(__powerpc__) || defined(__powerpc64__)
57 #define __NR_ioprio_set         273
58 #define __NR_ioprio_get         274
59 #elif defined(__x86_64__)
60 #define __NR_ioprio_set         251
61 #define __NR_ioprio_get         252
62 #elif defined(__ia64__)
63 #define __NR_ioprio_set         1274
64 #define __NR_ioprio_get         1275
65 #elif defined(__alpha__)
66 #define __NR_ioprio_set         442
67 #define __NR_ioprio_get         443
68 #elif defined(__s390x__) || defined(__s390__)
69 #define __NR_ioprio_set         282
70 #define __NR_ioprio_get         283
71 #else
72 #error "Unsupported arch"
73 #endif
74 #endif
75
76 #ifndef __NR_fadvise64
77 #if defined(__i386__)
78 #define __NR_fadvise64          250
79 #elif defined(__powerpc__) || defined(__powerpc64__)
80 #define __NR_fadvise64          233
81 #elif defined(__x86_64__)
82 #define __NR_fadvise64          221
83 #elif defined(__ia64__)
84 #define __NR_fadvise64          1234
85 #elif defined(__alpha__)
86 #define __NR_fadvise64          413
87 #elif defined(__s390x__) || defined(__s390__)
88 #define __NR_fadvise64          253
89 #else
90 #error "Unsupported arch"
91 #endif
92 #endif
93
94 static int ioprio_set(int which, int who, int ioprio)
95 {
96         return syscall(__NR_ioprio_set, which, who, ioprio);
97 }
98
99 /*
100  * we want fadvise64 really, but it's so tangled... later
101  */
102 static int fadvise(int fd, loff_t offset, size_t len, int advice)
103 {
104 #if 0
105         return syscall(__NR_fadvise64, fd, offset, offset >> 32, len, advice);
106 #else
107         return posix_fadvise(fd, (off_t) offset, len, advice);
108 #endif
109 }
110
111 enum {
112         IOPRIO_WHO_PROCESS = 1,
113         IOPRIO_WHO_PGRP,
114         IOPRIO_WHO_USER,
115 };
116
117 #define IOPRIO_CLASS_SHIFT      13
118
119 #define MASK    (4095)
120
121 #define DEF_BS          (4096)
122 #define DEF_TIMEOUT     (30)
123 #define DEF_RATE_CYCLE  (1000)
124 #define DEF_ODIRECT     (1)
125 #define DEF_SEQUENTIAL  (1)
126 #define DEF_RAND_REPEAT (1)
127 #define DEF_OVERWRITE   (0)
128 #define DEF_CREATE      (1)
129 #define DEF_INVALIDATE  (1)
130 #define DEF_SYNCIO      (0)
131 #define DEF_RANDSEED    (0xb1899bedUL)
132 #define DEF_BWAVGTIME   (500)
133 #define DEF_CREATE_SER  (1)
134 #define DEF_CREATE_FSYNC        (1)
135 #define DEF_LOOPS       (1)
136 #define DEF_VERIFY      (0)
137
138 #define ALIGN(buf)      (char *) (((unsigned long) (buf) + MASK) & ~(MASK))
139
140 static int repeatable = DEF_RAND_REPEAT;
141 static int rate_quit = 1;
142 static int write_lat_log;
143 static int write_bw_log;
144 static int exitall_on_terminate;
145
146 static int thread_number;
147 static char *ini_file;
148
149 static int max_jobs = MAX_JOBS;
150
151 static char run_str[MAX_JOBS + 1];
152
153 static int shm_id;
154
155 enum {
156         DDIR_READ = 0,
157         DDIR_WRITE,
158 };
159
160 /*
161  * thread life cycle
162  */
163 enum {
164         TD_NOT_CREATED = 0,
165         TD_CREATED,
166         TD_RUNNING,
167         TD_VERIFYING,
168         TD_EXITED,
169         TD_REAPED,
170 };
171
172 enum {
173         MEM_MALLOC,
174         MEM_SHM,
175 };
176
177 /*
178  * The io unit
179  */
180 struct io_u {
181         struct iocb iocb;
182         struct timeval start_time;
183         struct timeval issue_time;
184
185         char *buf;
186         unsigned int buflen;
187         unsigned long long offset;
188
189         struct list_head list;
190 };
191
192 struct io_stat {
193         unsigned long val;
194         unsigned long val_sq;
195         unsigned long max_val;
196         unsigned long min_val;
197         unsigned long samples;
198 };
199
200 struct io_sample {
201         unsigned long time;
202         unsigned long val;
203 };
204
205 struct io_log {
206         unsigned long nr_samples;
207         unsigned long max_samples;
208         struct io_sample *log;
209 };
210
211 #define FIO_HDR_MAGIC   0xf00baaef
212
213 struct verify_header {
214         unsigned int fio_magic;
215         unsigned int len;
216         char md5_digest[MD5_HASH_WORDS * 4];
217 };
218
219 #define td_read(td)             ((td)->ddir == DDIR_READ)
220 #define should_fsync(td)        (!td_read(td) && !(td)->odirect)
221
222 struct thread_data {
223         char file_name[256];
224         int thread_number;
225         int error;
226         int fd;
227         pid_t pid;
228         char *orig_buffer;
229         volatile int terminate;
230         volatile int runstate;
231         unsigned int ddir;
232         unsigned int ioprio;
233         unsigned int sequential;
234         unsigned int bs;
235         unsigned int min_bs;
236         unsigned int max_bs;
237         unsigned int odirect;
238         unsigned int thinktime;
239         unsigned int fsync_blocks;
240         unsigned int start_delay;
241         unsigned int timeout;
242         unsigned int use_aio;
243         unsigned int create_file;
244         unsigned int overwrite;
245         unsigned int invalidate_cache;
246         unsigned int bw_avg_time;
247         unsigned int create_serialize;
248         unsigned int create_fsync;
249         unsigned int loops;
250         unsigned long long file_size;
251         unsigned long long file_offset;
252         unsigned int sync_io;
253         unsigned int mem_type;
254         unsigned int verify;
255         cpu_set_t cpumask;
256
257         struct drand48_data bsrange_state;
258         struct drand48_data verify_state;
259
260         int shm_id;
261
262         off_t cur_off;
263
264         io_context_t aio_ctx;
265         unsigned int aio_depth;
266         struct io_event *aio_events;
267
268         unsigned int cur_depth;
269         struct list_head io_u_freelist;
270         struct list_head io_u_busylist;
271
272         unsigned int rate;
273         unsigned int ratemin;
274         unsigned int ratecycle;
275         unsigned long rate_usec_cycle;
276         long rate_pending_usleep;
277         unsigned long rate_kb;
278         struct timeval lastrate;
279
280         unsigned long runtime;          /* sec */
281         unsigned long kb;
282         unsigned long io_blocks;
283         unsigned long io_kb;
284         unsigned long this_io_kb;
285         unsigned long last_kb;
286         sem_t mutex;
287         struct drand48_data random_state;
288
289         /*
290          * bandwidth and latency stats
291          */
292         struct io_stat clat_stat;               /* completion latency */
293         struct io_stat slat_stat;               /* submission latency */
294
295         struct io_stat bw_stat;                 /* bandwidth stats */
296         unsigned long stat_io_kb;
297         struct timeval stat_sample_time;
298
299         struct io_log *lat_log;
300         struct io_log *bw_log;
301
302         struct timeval start;
303 };
304
305 static struct thread_data *threads;
306 static struct thread_data def_thread;
307
308 static sem_t startup_sem;
309
310 static void sig_handler(int sig)
311 {
312         int i;
313
314         for (i = 0; i < thread_number; i++) {
315                 struct thread_data *td = &threads[i];
316
317                 td->terminate = 1;
318                 td->start_delay = 0;
319         }
320 }
321
322 static int init_random_state(struct thread_data *td)
323 {
324         unsigned long seed;
325         int fd;
326
327         fd = open("/dev/random", O_RDONLY);
328         if (fd == -1) {
329                 td->error = errno;
330                 return 1;
331         }
332
333         if (read(fd, &seed, sizeof(seed)) < (int) sizeof(seed)) {
334                 td->error = EIO;
335                 close(fd);
336                 return 1;
337         }
338
339         close(fd);
340
341         srand48_r(seed, &td->bsrange_state);
342         srand48_r(seed, &td->verify_state);
343
344         if (td->sequential)
345                 return 0;
346
347         if (repeatable)
348                 seed = DEF_RANDSEED;
349
350         srand48_r(seed, &td->random_state);
351         return 0;
352 }
353
354 static unsigned long utime_since(struct timeval *s, struct timeval *e)
355 {
356         double sec, usec;
357
358         sec = e->tv_sec - s->tv_sec;
359         usec = e->tv_usec - s->tv_usec;
360         if (sec > 0 && usec < 0) {
361                 sec--;
362                 usec += 1000000;
363         }
364
365         sec *= (double) 1000000;
366
367         return sec + usec;
368 }
369
370 static unsigned long mtime_since(struct timeval *s, struct timeval *e)
371 {
372         double sec, usec;
373
374         sec = e->tv_sec - s->tv_sec;
375         usec = e->tv_usec - s->tv_usec;
376         if (sec > 0 && usec < 0) {
377                 sec--;
378                 usec += 1000000;
379         }
380
381         sec *= (double) 1000;
382         usec /= (double) 1000;
383
384         return sec + usec;
385 }
386
387 static unsigned long mtime_since_now(struct timeval *s)
388 {
389         struct timeval t;
390
391         gettimeofday(&t, NULL);
392         return mtime_since(s, &t);
393 }
394
395 static inline unsigned long msec_now(struct timeval *s)
396 {
397         return s->tv_sec * 1000 + s->tv_usec / 1000;
398 }
399
400 static unsigned long long get_next_offset(struct thread_data *td)
401 {
402         unsigned long long kb;
403         long r;
404
405         if (!td->sequential) {
406                 lrand48_r(&td->random_state, &r);
407                 kb = (1+(double) (td->kb-1) * r / (RAND_MAX+1.0));
408         } else
409                 kb = td->last_kb;
410
411         return (kb << 10) + td->file_offset;
412 }
413
414 static unsigned int get_next_buflen(struct thread_data *td)
415 {
416         unsigned int buflen;
417         long r;
418
419         if (td->min_bs == td->max_bs)
420                 buflen = td->min_bs;
421         else {
422                 lrand48_r(&td->bsrange_state, &r);
423                 buflen = (1 + (double) (td->max_bs - 1) * r / (RAND_MAX + 1.0));
424                 buflen = (buflen + td->min_bs - 1) & ~(td->min_bs - 1);
425         }
426
427         if (buflen > ((td->kb - td->this_io_kb) << 10))
428                 buflen = (td->kb - td->this_io_kb) << 10;
429
430         td->last_kb += buflen >> 10;
431         return buflen;
432 }
433
434 static inline void add_stat_sample(struct thread_data *td, struct io_stat *is,
435                                    unsigned long val)
436 {
437         if (val > is->max_val)
438                 is->max_val = val;
439         if (val < is->min_val)
440                 is->min_val = val;
441
442         is->val += val;
443         is->val_sq += val * val;
444         is->samples++;
445 }
446
447 static void add_log_sample(struct thread_data *td, struct io_log *log,
448                            unsigned long val)
449 {
450         if (log->nr_samples == log->max_samples) {
451                 int new_size = sizeof(struct io_sample) * log->max_samples * 2;
452
453                 log->log = realloc(log->log, new_size);
454                 log->max_samples <<= 1;
455         }
456
457         log->log[log->nr_samples].val = val;
458         log->log[log->nr_samples].time = mtime_since_now(&td->start);
459         log->nr_samples++;
460 }
461
462 static void add_clat_sample(struct thread_data *td, unsigned long msec)
463 {
464         add_stat_sample(td, &td->clat_stat, msec);
465
466         if (td->lat_log)
467                 add_log_sample(td, td->lat_log, msec);
468 }
469
470 static void add_slat_sample(struct thread_data *td, unsigned long msec)
471 {
472         add_stat_sample(td, &td->slat_stat, msec);
473 }
474
475 static void add_bw_sample(struct thread_data *td, unsigned long msec)
476 {
477         unsigned long spent = mtime_since_now(&td->stat_sample_time);
478         unsigned long rate;
479
480         if (spent < td->bw_avg_time)
481                 return;
482
483         rate = ((td->this_io_kb - td->stat_io_kb) * 1024) / spent;
484         add_stat_sample(td, &td->bw_stat, rate);
485
486         if (td->bw_log)
487                 add_log_sample(td, td->bw_log, rate);
488
489         gettimeofday(&td->stat_sample_time, NULL);
490         td->stat_io_kb = td->this_io_kb;
491 }
492
493 static void usec_sleep(int usec)
494 {
495         struct timespec req = { .tv_sec = 0, .tv_nsec = usec * 1000 };
496         struct timespec rem;
497
498         do {
499                 rem.tv_sec = rem.tv_nsec = 0;
500                 nanosleep(&req, &rem);
501                 if (!rem.tv_nsec)
502                         break;
503
504                 req.tv_nsec = rem.tv_nsec;
505         } while (1);
506 }
507
508 static void rate_throttle(struct thread_data *td, unsigned long time_spent,
509                           unsigned int bytes)
510 {
511         unsigned long usec_cycle;
512
513         if (!td->rate)
514                 return;
515
516         usec_cycle = td->rate_usec_cycle * (bytes / td->min_bs);
517
518         if (time_spent < usec_cycle) {
519                 unsigned long s = usec_cycle - time_spent;
520
521                 td->rate_pending_usleep += s;
522                 if (td->rate_pending_usleep >= 100000) {
523                         usec_sleep(td->rate_pending_usleep);
524                         td->rate_pending_usleep = 0;
525                 }
526         } else {
527                 long overtime = time_spent - usec_cycle;
528
529                 td->rate_pending_usleep -= overtime;
530         }
531 }
532
533 static int check_min_rate(struct thread_data *td, struct timeval *now)
534 {
535         unsigned long spent;
536         unsigned long rate;
537
538         /*
539          * allow a 2 second settle period in the beginning
540          */
541         if (mtime_since(&td->start, now) < 2000)
542                 return 0;
543
544         /*
545          * if rate blocks is set, sample is running
546          */
547         if (td->rate_kb) {
548                 spent = mtime_since(&td->lastrate, now);
549                 if (spent < td->ratecycle)
550                         return 0;
551
552                 rate = ((td->this_io_kb - td->rate_kb) * 1024) / spent;
553                 if (rate < td->ratemin) {
554                         printf("Client%d: min rate %d not met, got %ldKiB/sec\n", td->thread_number, td->ratemin, rate);
555                         if (rate_quit)
556                                 sig_handler(0);
557                         return 1;
558                 }
559         }
560
561         td->rate_kb = td->this_io_kb;
562         memcpy(&td->lastrate, now, sizeof(*now));
563         return 0;
564 }
565
566 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
567 {
568         if (mtime_since(&td->start, t) >= td->timeout * 1000)
569                 return 1;
570
571         return 0;
572 }
573
574 static void fill_random_bytes(struct thread_data *td,
575                               unsigned char *p, unsigned int len)
576 {
577         int todo;
578         long r;
579
580         while (len) {
581                 lrand48_r(&td->verify_state, &r);
582
583                 todo = sizeof(long);
584                 if (todo > len)
585                         todo = len;
586
587                 memcpy(p, &r, todo);
588
589                 len -= todo;
590                 p += todo;
591         }
592 }
593
594 static int verify_io_u(struct thread_data *td, struct io_u *io_u)
595 {
596         struct verify_header *hdr = (struct verify_header *) io_u->buf;
597         unsigned char *p = (unsigned char *) io_u->buf;
598         struct md5_ctx md5_ctx;
599
600         if (hdr->fio_magic != FIO_HDR_MAGIC)
601                 return 1;
602
603         memset(&md5_ctx, 0, sizeof(md5_ctx));
604         p += sizeof(*hdr);
605         md5_update(&md5_ctx, p, hdr->len - sizeof(*hdr));
606
607         return memcmp(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
608 }
609
610 static int verify_io_us(struct thread_data *td, struct io_u *io_u, int *back)
611 {
612         struct verify_header *hdr;
613         unsigned int left;
614         struct io_u i;
615         char *buf;
616         off_t off;
617
618         *back = 0;
619
620         left = io_u->buflen;
621         buf = io_u->buf;
622         off = io_u->offset;
623         while (left) {
624                 hdr = (struct verify_header *) buf;
625                 i.buf = buf;
626                 i.buflen = hdr->len;
627         
628                 if (hdr->len > left) {
629                         *back = left;
630                         return 0;
631                 }
632
633                 if (verify_io_u(td, &i)) {
634                         printf("failed verify at offset %lu\n", (unsigned long) off);
635                         return 1;
636                 }
637
638                 buf += hdr->len;
639                 left -= hdr->len;
640                 off += hdr->len;
641         }
642
643         return 0;
644 }
645
646 /*
647  * fill body of io_u->buf with random data and add a header with the
648  * (eg) sha1sum of that data.
649  */
650 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
651 {
652         struct md5_ctx md5_ctx;
653         struct verify_header hdr;
654         unsigned char *p = (unsigned char *) io_u->buf;
655
656         hdr.fio_magic = FIO_HDR_MAGIC;
657         hdr.len = io_u->buflen;
658         p += sizeof(hdr);
659         fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
660
661         memset(&md5_ctx, 0, sizeof(md5_ctx));
662         md5_update(&md5_ctx, p, io_u->buflen - sizeof(hdr));
663         memcpy(hdr.md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
664         memcpy(io_u->buf, &hdr, sizeof(hdr));
665 }
666
667 static void put_io_u(struct thread_data *td, struct io_u *io_u)
668 {
669         list_del(&io_u->list);
670         list_add(&io_u->list, &td->io_u_freelist);
671         td->cur_depth--;
672 }
673
674 static struct io_u *__get_io_u(struct thread_data *td)
675 {
676         struct io_u *io_u;
677
678         if (list_empty(&td->io_u_freelist))
679                 return NULL;
680
681         io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
682         list_del(&io_u->list);
683         list_add(&io_u->list, &td->io_u_busylist);
684         return io_u;
685 }
686
687 static struct io_u *get_io_u(struct thread_data *td)
688 {
689         struct io_u *io_u;
690         unsigned int len;
691         unsigned long long off;
692
693         io_u = __get_io_u(td);
694         if (!io_u)
695                 return NULL;
696
697         off = get_next_offset(td);
698         len = get_next_buflen(td);
699         if (!len) {
700                 put_io_u(td, io_u);
701                 return NULL;
702         }
703
704         io_u->offset = off;
705         io_u->buflen = len;
706
707         if (!td_read(td) && td->verify)
708                 populate_io_u(td, io_u);
709
710         if (td->use_aio) {
711                 if (td_read(td))
712                         io_prep_pread(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
713                 else
714                         io_prep_pwrite(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
715         }
716
717         gettimeofday(&io_u->start_time, NULL);
718         td->cur_depth++;
719         return io_u;
720 }
721
722 static int do_sync_verify(struct thread_data *td)
723 {
724         struct io_u *io_u = NULL;
725         loff_t off = 0;
726         int back, ret;
727
728         td->runstate = TD_VERIFYING;
729
730         io_u = __get_io_u(td);
731
732         if (lseek(td->fd, 0, SEEK_SET) < 0) {
733                 td->error = errno;
734                 goto out;
735         }
736
737         do {
738                 if (td->terminate)
739                         break;
740                 
741                 io_u->offset = off;
742                 io_u->buflen = td->max_bs;
743
744                 ret = read(td->fd, io_u->buf, io_u->buflen);
745                 if (ret < (int) io_u->buflen) {
746                         if (ret == -1) {
747                                 td->error = errno;
748                                 break;
749                         } else if (!ret)
750                                 break;
751                         else
752                                 io_u->buflen = ret;
753                 }
754
755                 if (verify_io_us(td, io_u, &back))
756                         break;
757
758                 if (back) {
759                         ret -= back;
760                         if (lseek(td->fd, -back, SEEK_CUR) < 0) {
761                                 td->error = errno;
762                                 break;
763                         }
764                 }
765
766                 off += ret;
767         } while (1);
768
769 out:
770         td->runstate = TD_RUNNING;
771         put_io_u(td, io_u);
772
773         return td->error == 0;
774 }
775
776 static void do_sync_io(struct thread_data *td)
777 {
778         unsigned long msec, usec;
779         struct io_u *io_u = NULL;
780         struct timeval e;
781
782         td->cur_off = 0;
783         td->last_kb = 0;
784
785         for (td->this_io_kb = 0; td->this_io_kb < td->kb;) {
786                 int ret;
787
788                 if (td->terminate)
789                         break;
790
791                 io_u = get_io_u(td);
792                 if (!io_u)
793                         break;
794
795                 if (td->cur_off != io_u->offset) {
796                         if (lseek(td->fd, io_u->offset, SEEK_SET) == -1) {
797                                 td->error = errno;
798                                 break;
799                         }
800                 }
801
802                 if (td_read(td))
803                         ret = read(td->fd, io_u->buf, io_u->buflen);
804                 else
805                         ret = write(td->fd, io_u->buf, io_u->buflen);
806
807                 if (ret < (int) io_u->buflen) {
808                         if (ret == -1)
809                                 td->error = errno;
810                         break;
811                 }
812
813                 td->io_blocks++;
814                 td->io_kb += io_u->buflen >> 10;
815                 td->this_io_kb += io_u->buflen >> 10;
816                 td->cur_off = io_u->offset + io_u->buflen;
817
818                 gettimeofday(&e, NULL);
819
820                 usec = utime_since(&io_u->start_time, &e);
821
822                 rate_throttle(td, usec, io_u->buflen);
823
824                 if (check_min_rate(td, &e)) {
825                         td->error = ENODATA;
826                         break;
827                 }
828
829                 msec = usec / 1000;
830                 add_clat_sample(td, msec);
831                 add_bw_sample(td, msec);
832
833                 if (runtime_exceeded(td, &e))
834                         break;
835
836                 put_io_u(td, io_u);
837                 io_u = NULL;
838
839                 if (td->thinktime)
840                         usec_sleep(td->thinktime);
841
842                 if (should_fsync(td) && td->fsync_blocks &&
843                     (td->io_blocks % td->fsync_blocks) == 0)
844                         fsync(td->fd);
845         }
846
847         if (io_u)
848                 put_io_u(td, io_u);
849
850         if (should_fsync(td))
851                 fsync(td->fd);
852 }
853
854 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
855 {
856         struct iocb *iocb = &io_u->iocb;
857         int ret;
858
859         do {
860                 ret = io_submit(td->aio_ctx, 1, &iocb);
861                 if (ret == 1)
862                         return 0;
863                 else if (ret == EAGAIN)
864                         usleep(100);
865                 else if (ret == EINTR)
866                         continue;
867                 else
868                         break;
869         } while (1);
870
871         return ret;
872 }
873
874 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
875 #define ev_to_iou(ev)   (struct io_u *) ((unsigned long) (ev)->obj)
876
877 static int ios_completed(struct thread_data *td, int nr)
878 {
879         unsigned long msec;
880         struct io_u *io_u;
881         struct timeval e;
882         int i, bytes_done;
883
884         gettimeofday(&e, NULL);
885
886         for (i = 0, bytes_done = 0; i < nr; i++) {
887                 io_u = ev_to_iou(td->aio_events + i);
888
889                 td->io_blocks++;
890                 td->io_kb += io_u->buflen >> 10;
891                 td->this_io_kb += io_u->buflen >> 10;
892                 bytes_done += io_u->buflen;
893
894                 msec = mtime_since(&io_u->issue_time, &e);
895
896                 add_clat_sample(td, msec);
897                 add_bw_sample(td, msec);
898
899                 put_io_u(td, io_u);
900         }
901
902         return bytes_done;
903 }
904
905 static void cleanup_pending_aio(struct thread_data *td)
906 {
907         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
908         struct list_head *entry, *n;
909         struct io_u *io_u;
910         int r;
911
912         /*
913          * get immediately available events, if any
914          */
915         r = io_getevents(td->aio_ctx, 0, td->cur_depth, td->aio_events, &ts);
916         if (r > 0)
917                 ios_completed(td, r);
918
919         /*
920          * now cancel remaining active events
921          */
922         list_for_each_safe(entry, n, &td->io_u_busylist) {
923                 io_u = list_entry(entry, struct io_u, list);
924
925                 r = io_cancel(td->aio_ctx, &io_u->iocb, td->aio_events);
926                 if (!r)
927                         put_io_u(td, io_u);
928         }
929
930         if (td->cur_depth) {
931                 r = io_getevents(td->aio_ctx, td->cur_depth, td->cur_depth, td->aio_events, NULL);
932                 if (r > 0)
933                         ios_completed(td, r);
934         }
935 }
936
937 static int do_async_verify(struct thread_data *td)
938 {
939         /*
940          * need to implement the async version
941          */
942         return do_sync_verify(td);
943 }
944
945 static void do_async_io(struct thread_data *td)
946 {
947         struct timeval s, e;
948         unsigned long usec;
949
950         td->cur_off = 0;
951         td->last_kb = 0;
952
953         for (td->this_io_kb = 0; td->this_io_kb < td->kb;) {
954                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
955                 struct timespec *timeout;
956                 int ret, min_evts = 0;
957                 struct io_u *io_u;
958                 unsigned int bytes_done;
959
960                 if (td->terminate)
961                         break;
962
963                 io_u = get_io_u(td);
964                 if (!io_u)
965                         break;
966
967                 memcpy(&s, &io_u->start_time, sizeof(s));
968
969                 ret = io_u_queue(td, io_u);
970                 if (ret) {
971                         put_io_u(td, io_u);
972                         td->error = ret;
973                         break;
974                 }
975
976                 gettimeofday(&io_u->issue_time, NULL);
977                 add_slat_sample(td, mtime_since(&io_u->start_time, &io_u->issue_time));
978                 if (td->cur_depth < td->aio_depth) {
979                         timeout = &ts;
980                         min_evts = 0;
981                 } else {
982                         timeout = NULL;
983                         min_evts = 1;
984                 }
985
986                 ret = io_getevents(td->aio_ctx, min_evts, td->cur_depth, td->aio_events, timeout);
987                 if (ret < 0) {
988                         td->error = errno;
989                         break;
990                 } else if (!ret)
991                         continue;
992
993                 bytes_done = ios_completed(td, ret);
994
995                 /*
996                  * the rate is batched for now, it should work for batches
997                  * of completions except the very first one which may look
998                  * a little bursty
999                  */
1000                 gettimeofday(&e, NULL);
1001                 usec = utime_since(&s, &e);
1002
1003                 rate_throttle(td, usec, bytes_done);
1004
1005                 if (check_min_rate(td, &e)) {
1006                         td->error = ENODATA;
1007                         break;
1008                 }
1009
1010                 if (runtime_exceeded(td, &e))
1011                         break;
1012
1013                 if (td->thinktime)
1014                         usec_sleep(td->thinktime);
1015
1016                 if (should_fsync(td) && td->fsync_blocks &&
1017                     (td->io_blocks % td->fsync_blocks) == 0)
1018                         fsync(td->fd);
1019         }
1020
1021         if (td->cur_depth)
1022                 cleanup_pending_aio(td);
1023
1024         if (should_fsync(td))
1025                 fsync(td->fd);
1026 }
1027
1028 static void cleanup_aio(struct thread_data *td)
1029 {
1030         io_destroy(td->aio_ctx);
1031
1032         if (td->aio_events)
1033                 free(td->aio_events);
1034 }
1035
1036 static int init_aio(struct thread_data *td)
1037 {
1038         if (io_queue_init(td->aio_depth, &td->aio_ctx)) {
1039                 td->error = errno;
1040                 return 1;
1041         }
1042
1043         td->aio_events = malloc(td->aio_depth * sizeof(struct io_event));
1044         return 0;
1045 }
1046
1047 static void cleanup_io_u(struct thread_data *td)
1048 {
1049         struct list_head *entry, *n;
1050         struct io_u *io_u;
1051
1052         list_for_each_safe(entry, n, &td->io_u_freelist) {
1053                 io_u = list_entry(entry, struct io_u, list);
1054
1055                 list_del(&io_u->list);
1056                 free(io_u);
1057         }
1058
1059         if (td->mem_type == MEM_MALLOC)
1060                 free(td->orig_buffer);
1061         else if (td->mem_type == MEM_SHM) {
1062                 struct shmid_ds sbuf;
1063
1064                 shmdt(td->orig_buffer);
1065                 shmctl(td->shm_id, IPC_RMID, &sbuf);
1066         }
1067 }
1068
1069 static int init_io_u(struct thread_data *td)
1070 {
1071         struct io_u *io_u;
1072         int i, max_units, mem_size;
1073         char *p;
1074
1075         if (!td->use_aio)
1076                 max_units = 1;
1077         else
1078                 max_units = td->aio_depth;
1079
1080         mem_size = td->max_bs * max_units + MASK;
1081
1082         if (td->mem_type == MEM_MALLOC)
1083                 td->orig_buffer = malloc(mem_size);
1084         else if (td->mem_type == MEM_SHM) {
1085                 td->shm_id = shmget(IPC_PRIVATE, mem_size, IPC_CREAT | 0600);
1086                 if (td->shm_id < 0) {
1087                         td->error = errno;
1088                         perror("shmget");
1089                         return 1;
1090                 }
1091
1092                 td->orig_buffer = shmat(td->shm_id, NULL, 0);
1093                 if (td->orig_buffer == (void *) -1) {
1094                         td->error = errno;
1095                         perror("shmat");
1096                         return 1;
1097                 }
1098         }
1099
1100         INIT_LIST_HEAD(&td->io_u_freelist);
1101         INIT_LIST_HEAD(&td->io_u_busylist);
1102
1103         p = ALIGN(td->orig_buffer);
1104         for (i = 0; i < max_units; i++) {
1105                 io_u = malloc(sizeof(*io_u));
1106                 memset(io_u, 0, sizeof(*io_u));
1107                 INIT_LIST_HEAD(&io_u->list);
1108
1109                 io_u->buf = p + td->max_bs * i;
1110                 list_add(&io_u->list, &td->io_u_freelist);
1111         }
1112
1113         return 0;
1114 }
1115
1116 static void setup_log(struct io_log **log)
1117 {
1118         struct io_log *l = malloc(sizeof(*l));
1119
1120         l->nr_samples = 0;
1121         l->max_samples = 1024;
1122         l->log = malloc(l->max_samples * sizeof(struct io_sample));
1123         *log = l;
1124 }
1125
1126 static void finish_log(struct thread_data *td, struct io_log *log, char *name)
1127 {
1128         char file_name[128];
1129         FILE *f;
1130         int i;
1131
1132         sprintf(file_name, "client%d_%s.log", td->thread_number, name);
1133         f = fopen(file_name, "w");
1134         if (!f) {
1135                 perror("fopen log");
1136                 return;
1137         }
1138
1139         for (i = 0; i < log->nr_samples; i++)
1140                 fprintf(f, "%lu, %lu\n", log->log[i].time, log->log[i].val);
1141
1142         fclose(f);
1143         free(log->log);
1144         free(log);
1145 }
1146
1147 static int create_file(struct thread_data *td)
1148 {
1149         unsigned long long left;
1150         char *b;
1151         int r, bs;
1152
1153         /*
1154          * unless specifically asked for overwrite, let normal io extend it
1155          */
1156         if (!td_read(td) && !td->overwrite)
1157                 return 0;
1158
1159         if (!td->file_size) {
1160                 fprintf(stderr, "Need size for create\n");
1161                 td->error = EINVAL;
1162                 return 1;
1163         }
1164
1165         printf("Client%d: Laying out IO file\n", td->thread_number);
1166
1167         td->fd = open(td->file_name, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1168         if (td->fd < 0) {
1169                 td->error = errno;
1170                 return 1;
1171         }
1172
1173         td->kb = td->file_size >> 10;
1174         b = malloc(td->max_bs);
1175         memset(b, 0, td->max_bs);
1176
1177         left = td->file_size;
1178         while (left) {
1179                 bs = td->max_bs;
1180                 if (bs > left)
1181                         bs = left;
1182
1183                 r = write(td->fd, b, bs);
1184
1185                 if (r == bs) {
1186                         left -= bs;
1187                         continue;
1188                 } else {
1189                         if (r < 0)
1190                                 td->error = errno;
1191                         else
1192                                 td->error = EIO;
1193
1194                         break;
1195                 }
1196         }
1197
1198         if (td->create_fsync)
1199                 fsync(td->fd);
1200
1201         close(td->fd);
1202         td->fd = -1;
1203         free(b);
1204         return 0;
1205 }
1206
1207 static int file_exists(struct thread_data *td)
1208 {
1209         struct stat st;
1210
1211         if (stat(td->file_name, &st) != -1)
1212                 return 1;
1213
1214         return errno != ENOENT;
1215 }
1216
1217 static int setup_file(struct thread_data *td)
1218 {
1219         struct stat st;
1220         int flags = 0;
1221
1222         if (!file_exists(td)) {
1223                 if (!td->create_file) {
1224                         td->error = ENOENT;
1225                         return 1;
1226                 }
1227                 if (create_file(td))
1228                         return 1;
1229         }
1230
1231         if (td->odirect)
1232                 flags |= O_DIRECT;
1233
1234         if (td_read(td))
1235                 td->fd = open(td->file_name, flags | O_RDONLY);
1236         else {
1237                 if (!td->overwrite)
1238                         flags |= O_TRUNC;
1239                 if (td->sync_io)
1240                         flags |= O_SYNC;
1241                 if (td->verify)
1242                         flags |= O_RDWR;
1243                 else
1244                         flags |= O_WRONLY;
1245
1246                 td->fd = open(td->file_name, flags | O_CREAT, 0600);
1247         }
1248
1249         if (td->fd == -1) {
1250                 td->error = errno;
1251                 return 1;
1252         }
1253
1254         if (td_read(td)) {
1255                 if (fstat(td->fd, &st) == -1) {
1256                         td->error = errno;
1257                         return 1;
1258                 }
1259
1260                 if (td->file_size > st.st_size)
1261                         st.st_size = td->file_size;
1262         } else {
1263                 if (!td->file_size)
1264                         td->file_size = 1024 * 1024 * 1024;
1265
1266                 st.st_size = td->file_size;
1267         }
1268
1269         td->kb = (st.st_size - td->file_offset) / 1024;
1270         if (!td->kb) {
1271                 fprintf(stderr, "Client%d: no io blocks\n", td->thread_number);
1272                 td->error = EINVAL;
1273                 return 1;
1274         }
1275
1276         if (td->invalidate_cache) {
1277                 if (fadvise(td->fd, 0, st.st_size, POSIX_FADV_DONTNEED) < 0) {
1278                         td->error = errno;
1279                         return 1;
1280                 }
1281         }
1282
1283         return 0;
1284 }
1285
1286 static void *thread_main(int shm_id, int offset, char *argv[])
1287 {
1288         struct thread_data *td;
1289         int ret = 1;
1290         void *data;
1291
1292         setsid();
1293
1294         data = shmat(shm_id, NULL, 0);
1295         if (data == (void *) -1) {
1296                 perror("shmat");
1297                 return NULL;
1298         }
1299
1300         td = data + offset * sizeof(struct thread_data);
1301         td->pid = getpid();
1302
1303         if (init_io_u(td))
1304                 goto err;
1305
1306         if (sched_setaffinity(td->pid, sizeof(td->cpumask), &td->cpumask) == -1) {
1307                 td->error = errno;
1308                 goto err;
1309         }
1310
1311         sprintf(argv[0], "fio%d", offset);
1312
1313         if (td->use_aio && init_aio(td))
1314                 goto err;
1315
1316         if (init_random_state(td))
1317                 goto err;
1318
1319         if (td->ioprio) {
1320                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1321                         td->error = errno;
1322                         goto err;
1323                 }
1324         }
1325
1326         sem_post(&startup_sem);
1327         sem_wait(&td->mutex);
1328
1329         if (!td->create_serialize && setup_file(td))
1330                 goto err;
1331
1332         gettimeofday(&td->start, NULL);
1333
1334         if (td->ratemin)
1335                 memcpy(&td->lastrate, &td->start, sizeof(td->start));
1336
1337         memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1338
1339         while (td->loops--) {
1340                 if (!td->use_aio) {
1341                         do_sync_io(td);
1342
1343                         if (td->verify) {
1344                                 if (!do_sync_verify(td))
1345                                         break;
1346                         }
1347                 } else {
1348                         do_async_io(td);
1349
1350                         if (td->verify) {
1351                                 if (!do_async_verify(td))
1352                                         break;
1353                         }
1354                 }
1355         }
1356
1357         td->runtime = mtime_since_now(&td->start);
1358         ret = 0;
1359
1360         if (td->bw_log)
1361                 finish_log(td, td->bw_log, "bw");
1362         if (td->lat_log)
1363                 finish_log(td, td->lat_log, "lat");
1364
1365         if (exitall_on_terminate)
1366                 sig_handler(0);
1367
1368 err:
1369         if (td->fd != -1) {
1370                 close(td->fd);
1371                 td->fd = -1;
1372         }
1373         if (td->use_aio)
1374                 cleanup_aio(td);
1375         cleanup_io_u(td);
1376         if (ret) {
1377                 sem_post(&startup_sem);
1378                 sem_wait(&td->mutex);
1379         }
1380         td->runstate = TD_EXITED;
1381         shmdt(data);
1382         return NULL;
1383 }
1384
1385 static void free_shm(void)
1386 {
1387         struct shmid_ds sbuf;
1388
1389         if (threads) {
1390                 shmdt(threads);
1391                 threads = NULL;
1392                 shmctl(shm_id, IPC_RMID, &sbuf);
1393         }
1394 }
1395
1396 static int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
1397                     double *mean, double *dev)
1398 {
1399         double n;
1400
1401         if (is->samples == 0)
1402                 return 0;
1403
1404         *min = is->min_val;
1405         *max = is->max_val;
1406
1407         n = (double) is->samples;
1408         *mean = (double) is->val / n;
1409         *dev = sqrt(((double) is->val_sq - (*mean * *mean) / n) / (n - 1));
1410         return 1;
1411 }
1412
1413 static void show_thread_status(struct thread_data *td)
1414 {
1415         int prio, prio_class;
1416         unsigned long min, max, bw = 0;
1417         double mean, dev;
1418
1419         if (!td->io_kb && !td->error)
1420                 return;
1421
1422         if (td->runtime)
1423                 bw = td->io_kb * 1024 / td->runtime;
1424
1425         prio = td->ioprio & 0xff;
1426         prio_class = td->ioprio >> IOPRIO_CLASS_SHIFT;
1427
1428         printf("Client%d: err=%2d, io=%6luMiB, bw=%6luKiB/s, runt=%6lumsec\n", td->thread_number, td->error, td->io_kb >> 10, bw, td->runtime);
1429
1430         if (calc_lat(&td->slat_stat, &min, &max, &mean, &dev))
1431                 printf("  slat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1432         if (calc_lat(&td->clat_stat, &min, &max, &mean, &dev))
1433                 printf("  clat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1434         if (calc_lat(&td->bw_stat, &min, &max, &mean, &dev))
1435                 printf("  bw (KiB/s) : min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1436 }
1437
1438 static int setup_rate(struct thread_data *td)
1439 {
1440         int nr_reads_per_sec;
1441
1442         if (!td->rate)
1443                 return 0;
1444
1445         if (td->rate < td->ratemin) {
1446                 fprintf(stderr, "min rate larger than nominal rate\n");
1447                 return -1;
1448         }
1449
1450         nr_reads_per_sec = td->rate * 1024 / td->min_bs;
1451         td->rate_usec_cycle = 1000000 / nr_reads_per_sec;
1452         td->rate_pending_usleep = 0;
1453         return 0;
1454 }
1455
1456 static struct thread_data *get_new_job(int global)
1457 {
1458         struct thread_data *td;
1459
1460         if (global)
1461                 return &def_thread;
1462         if (thread_number >= max_jobs)
1463                 return NULL;
1464
1465         td = &threads[thread_number++];
1466         memset(td, 0, sizeof(*td));
1467
1468         td->fd = -1;
1469         td->thread_number = thread_number;
1470
1471         td->ddir = def_thread.ddir;
1472         td->ioprio = def_thread.ioprio;
1473         td->sequential = def_thread.sequential;
1474         td->bs = def_thread.bs;
1475         td->min_bs = def_thread.min_bs;
1476         td->max_bs = def_thread.max_bs;
1477         td->odirect = def_thread.odirect;
1478         td->thinktime = def_thread.thinktime;
1479         td->fsync_blocks = def_thread.fsync_blocks;
1480         td->start_delay = def_thread.start_delay;
1481         td->timeout = def_thread.timeout;
1482         td->use_aio = def_thread.use_aio;
1483         td->create_file = def_thread.create_file;
1484         td->overwrite = def_thread.overwrite;
1485         td->invalidate_cache = def_thread.invalidate_cache;
1486         td->file_size = def_thread.file_size;
1487         td->file_offset = def_thread.file_offset;
1488         td->rate = def_thread.rate;
1489         td->ratemin = def_thread.ratemin;
1490         td->ratecycle = def_thread.ratecycle;
1491         td->aio_depth = def_thread.aio_depth;
1492         td->sync_io = def_thread.sync_io;
1493         td->mem_type = def_thread.mem_type;
1494         td->bw_avg_time = def_thread.bw_avg_time;
1495         td->create_serialize = def_thread.create_serialize;
1496         td->create_fsync = def_thread.create_fsync;
1497         td->loops = def_thread.loops;
1498         td->verify = def_thread.verify;
1499         memcpy(&td->cpumask, &def_thread.cpumask, sizeof(td->cpumask));
1500
1501         return td;
1502 }
1503
1504 static void put_job(struct thread_data *td)
1505 {
1506         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
1507         thread_number--;
1508 }
1509
1510 static int add_job(struct thread_data *td, const char *filename, int prioclass,
1511                    int prio)
1512 {
1513         if (td == &def_thread)
1514                 return 0;
1515
1516         strcpy(td->file_name, filename);
1517         sem_init(&td->mutex, 1, 0);
1518         td->ioprio = (prioclass << IOPRIO_CLASS_SHIFT) | prio;
1519
1520         td->clat_stat.min_val = ULONG_MAX;
1521         td->slat_stat.min_val = ULONG_MAX;
1522         td->bw_stat.min_val = ULONG_MAX;
1523
1524         run_str[td->thread_number - 1] = 'P';
1525
1526         if (td->use_aio && !td->aio_depth)
1527                 td->aio_depth = 1;
1528
1529         if (td->min_bs == -1)
1530                 td->min_bs = td->bs;
1531         if (td->max_bs == -1)
1532                 td->max_bs = td->bs;
1533
1534         if (setup_rate(td))
1535                 return -1;
1536
1537         if (write_lat_log)
1538                 setup_log(&td->lat_log);
1539         if (write_bw_log)
1540                 setup_log(&td->bw_log);
1541
1542         printf("Client%d: file=%s, rw=%d, prio=%d/%d, seq=%d, odir=%d, bs=%d-%d, rate=%d, aio=%d, aio_depth=%d\n", td->thread_number, filename, td->ddir, prioclass, prio, td->sequential, td->odirect, td->min_bs, td->max_bs, td->rate, td->use_aio, td->aio_depth);
1543         return 0;
1544 }
1545
1546 static void fill_cpu_mask(cpu_set_t cpumask, int cpu)
1547 {
1548         unsigned int i;
1549
1550         CPU_ZERO(&cpumask);
1551
1552         for (i = 0; i < sizeof(int) * 8; i++) {
1553                 if ((1 << i) & cpu)
1554                         CPU_SET(i, &cpumask);
1555         }
1556 }
1557
1558 unsigned long get_mult(char c)
1559 {
1560         switch (c) {
1561                 case 'k':
1562                 case 'K':
1563                         return 1024;
1564                 case 'm':
1565                 case 'M':
1566                         return 1024 * 1024;
1567                 case 'g':
1568                 case 'G':
1569                         return 1024 * 1024 * 1024;
1570                 default:
1571                         return 1;
1572         }
1573 }
1574
1575 /*
1576  * convert string after '=' into decimal value, noting any size suffix
1577  */
1578 static int str_cnv(char *p, unsigned long long *val)
1579 {
1580         char *str;
1581         int len;
1582
1583         str = strstr(p, "=");
1584         if (!str)
1585                 return 1;
1586
1587         str++;
1588         len = strlen(str);
1589
1590         *val = strtoul(str, NULL, 10);
1591         if (*val == ULONG_MAX && errno == ERANGE)
1592                 return 1;
1593
1594         *val *= get_mult(str[len - 2]);
1595         return 0;
1596 }
1597
1598 static int check_strcnv(char *p, char *name, unsigned long long *val)
1599 {
1600         if (!strstr(p, name))
1601                 return 1;
1602
1603         return str_cnv(p, val);
1604 }
1605
1606 static int check_str(char *p, char *name, char *option)
1607 {
1608         char *s = strstr(p, name);
1609
1610         if (!s)
1611                 return 1;
1612
1613         s += strlen(name);
1614         if (strstr(s, option))
1615                 return 0;
1616
1617         return 1;
1618 }
1619
1620 static int check_range(char *p, char *name, unsigned long *s, unsigned long *e)
1621 {
1622         char str[128];
1623         char s1, s2;
1624
1625         sprintf(str, "%s=%%lu%%c-%%lu%%c", name);
1626         if (sscanf(p, str, s, &s1, e, &s2) == 4) {
1627                 *s *= get_mult(s1);
1628                 *e *= get_mult(s2);
1629                 return 0;
1630         }
1631
1632         sprintf(str, "%s = %%lu%%c-%%lu%%c", name);
1633         if (sscanf(p, str, s, &s1, e, &s2) == 4) {
1634                 *s *= get_mult(s1);
1635                 *e *= get_mult(s2);
1636                 return 0;
1637         }
1638
1639         sprintf(str, "%s=%%lu-%%lu", name);
1640         if (sscanf(p, str, s, e) == 2)
1641                 return 0;
1642
1643         sprintf(str, "%s = %%lu-%%lu", name);
1644         if (sscanf(p, str, s, e) == 2)
1645                 return 0;
1646
1647         return 1;
1648
1649 }
1650
1651 static int check_int(char *p, char *name, unsigned int *val)
1652 {
1653         char str[128];
1654
1655         sprintf(str, "%s=%%d", name);
1656         if (sscanf(p, str, val) == 1)
1657                 return 0;
1658
1659         sprintf(str, "%s = %%d", name);
1660         if (sscanf(p, str, val) == 1)
1661                 return 0;
1662
1663         return 1;
1664 }
1665
1666 static int is_empty_or_comment(char *line)
1667 {
1668         unsigned int i;
1669
1670         for (i = 0; i < strlen(line); i++) {
1671                 if (line[i] == ';')
1672                         return 1;
1673                 if (!isspace(line[i]) && !iscntrl(line[i]))
1674                         return 0;
1675         }
1676
1677         return 1;
1678 }
1679
1680 static int parse_jobs_ini(char *file)
1681 {
1682         unsigned int prioclass, prio, cpu, global;
1683         unsigned long long ull;
1684         unsigned long ul1, ul2;
1685         struct thread_data *td;
1686         char *string, *name;
1687         fpos_t off;
1688         FILE *f;
1689         char *p;
1690
1691         f = fopen(file, "r");
1692         if (!f) {
1693                 perror("fopen");
1694                 return 1;
1695         }
1696
1697         string = malloc(4096);
1698         name = malloc(256);
1699
1700         while ((p = fgets(string, 4096, f)) != NULL) {
1701                 if (is_empty_or_comment(p))
1702                         continue;
1703                 if (sscanf(p, "[%s]", name) != 1)
1704                         continue;
1705
1706                 global = !strncmp(name, "global", 6);
1707
1708                 name[strlen(name) - 1] = '\0';
1709
1710                 td = get_new_job(global);
1711                 if (!td)
1712                         break;
1713
1714                 prioclass = 2;
1715                 prio = 4;
1716
1717                 fgetpos(f, &off);
1718                 while ((p = fgets(string, 4096, f)) != NULL) {
1719                         if (is_empty_or_comment(p))
1720                                 continue;
1721                         if (strstr(p, "["))
1722                                 break;
1723                         if (!check_int(p, "rw", &td->ddir)) {
1724                                 fgetpos(f, &off);
1725                                 continue;
1726                         }
1727                         if (!check_int(p, "prio", &prio)) {
1728                                 fgetpos(f, &off);
1729                                 continue;
1730                         }
1731                         if (!check_int(p, "prioclass", &prioclass)) {
1732                                 fgetpos(f, &off);
1733                                 continue;
1734                         }
1735                         if (!check_int(p, "direct", &td->odirect)) {
1736                                 fgetpos(f, &off);
1737                                 continue;
1738                         }
1739                         if (!check_int(p, "rate", &td->rate)) {
1740                                 fgetpos(f, &off);
1741                                 continue;
1742                         }
1743                         if (!check_int(p, "ratemin", &td->ratemin)) {
1744                                 fgetpos(f, &off);
1745                                 continue;
1746                         }
1747                         if (!check_int(p, "ratecycle", &td->ratecycle)) {
1748                                 fgetpos(f, &off);
1749                                 continue;
1750                         }
1751                         if (!check_int(p, "thinktime", &td->thinktime)) {
1752                                 fgetpos(f, &off);
1753                                 continue;
1754                         }
1755                         if (!check_int(p, "cpumask", &cpu)) {
1756                                 fill_cpu_mask(td->cpumask, cpu);
1757                                 fgetpos(f, &off);
1758                                 continue;
1759                         }
1760                         if (!check_int(p, "fsync", &td->fsync_blocks)) {
1761                                 fgetpos(f, &off);
1762                                 continue;
1763                         }
1764                         if (!check_int(p, "startdelay", &td->start_delay)) {
1765                                 fgetpos(f, &off);
1766                                 continue;
1767                         }
1768                         if (!check_int(p, "timeout", &td->timeout)) {
1769                                 fgetpos(f, &off);
1770                                 continue;
1771                         }
1772                         if (!check_int(p, "invalidate",&td->invalidate_cache)) {
1773                                 fgetpos(f, &off);
1774                                 continue;
1775                         }
1776                         if (!check_int(p, "aio_depth", &td->aio_depth)) {
1777                                 fgetpos(f, &off);
1778                                 continue;
1779                         }
1780                         if (!check_int(p, "sync", &td->sync_io)) {
1781                                 fgetpos(f, &off);
1782                                 continue;
1783                         }
1784                         if (!check_int(p, "bwavgtime", &td->bw_avg_time)) {
1785                                 fgetpos(f, &off);
1786                                 continue;
1787                         }
1788                         if (!check_int(p, "create_serialize", &td->create_serialize)) {
1789                                 fgetpos(f, &off);
1790                                 continue;
1791                         }
1792                         if (!check_int(p, "create_fsync", &td->create_fsync)) {
1793                                 fgetpos(f, &off);
1794                                 continue;
1795                         }
1796                         if (!check_int(p, "loops", &td->loops)) {
1797                                 fgetpos(f, &off);
1798                                 continue;
1799                         }
1800                         if (!check_int(p, "verify", &td->verify)) {
1801                                 fgetpos(f, &off);
1802                                 continue;
1803                         }
1804                         if (!check_range(p, "bsrange", &ul1, &ul2)) {
1805                                 td->min_bs = ul1;
1806                                 td->max_bs = ul2;
1807                                 fgetpos(f, &off);
1808                                 continue;
1809                         }
1810                         if (!check_strcnv(p, "bs", &ull)) {
1811                                 td->bs = ull;
1812                                 fgetpos(f, &off);
1813                                 continue;
1814                         }
1815                         if (!check_strcnv(p, "size", &td->file_size)) {
1816                                 fgetpos(f, &off);
1817                                 continue;
1818                         }
1819                         if (!check_strcnv(p, "offset", &td->file_offset)) {
1820                                 fgetpos(f, &off);
1821                                 continue;
1822                         }
1823                         if (!check_str(p, "mem", "malloc")) {
1824                                 td->mem_type = MEM_MALLOC;
1825                                 fgetpos(f, &off);
1826                                 continue;
1827                         }
1828                         if (!check_str(p, "mem", "shm")) {
1829                                 td->mem_type = MEM_SHM;
1830                                 fgetpos(f, &off);
1831                                 continue;
1832                         }
1833                         if (!strncmp(p, "sequential", 10)) {
1834                                 td->sequential = 1;
1835                                 fgetpos(f, &off);
1836                                 continue;
1837                         }
1838                         if (!strncmp(p, "random", 6)) {
1839                                 td->sequential = 0;
1840                                 fgetpos(f, &off);
1841                                 continue;
1842                         }
1843                         if (!strncmp(p, "aio", 3)) {
1844                                 td->use_aio = 1;
1845                                 fgetpos(f, &off);
1846                                 continue;
1847                         }
1848                         if (!strncmp(p, "create", 6)) {
1849                                 td->create_file = 1;
1850                                 fgetpos(f, &off);
1851                                 continue;
1852                         }
1853                         if (!strncmp(p, "overwrite", 9)) {
1854                                 td->overwrite = 1;
1855                                 fgetpos(f, &off);
1856                                 continue;
1857                         }
1858                         if (!strncmp(p, "exitall", 7)) {
1859                                 exitall_on_terminate = 1;
1860                                 fgetpos(f, &off);
1861                                 continue;
1862                         }
1863                         printf("Client%d: bad option %s\n",td->thread_number,p);
1864                 }
1865                 fsetpos(f, &off);
1866
1867                 if (add_job(td, name, prioclass, prio))
1868                         put_job(td);
1869         }
1870
1871         free(string);
1872         free(name);
1873         fclose(f);
1874         return 0;
1875 }
1876
1877 static int parse_options(int argc, char *argv[])
1878 {
1879         int i;
1880
1881         for (i = 1; i < argc; i++) {
1882                 char *parm = argv[i];
1883
1884                 if (parm[0] != '-')
1885                         break;
1886
1887                 parm++;
1888                 switch (*parm) {
1889                         case 's':
1890                                 parm++;
1891                                 def_thread.sequential = !!atoi(parm);
1892                                 break;
1893                         case 'b':
1894                                 parm++;
1895                                 def_thread.bs = atoi(parm);
1896                                 def_thread.bs <<= 10;
1897                                 if (!def_thread.bs) {
1898                                         printf("bad block size\n");
1899                                         def_thread.bs = DEF_BS;
1900                                 }
1901                                 break;
1902                         case 't':
1903                                 parm++;
1904                                 def_thread.timeout = atoi(parm);
1905                                 break;
1906                         case 'r':
1907                                 parm++;
1908                                 repeatable = !!atoi(parm);
1909                                 break;
1910                         case 'R':
1911                                 parm++;
1912                                 rate_quit = !!atoi(parm);
1913                                 break;
1914                         case 'o':
1915                                 parm++;
1916                                 def_thread.odirect = !!atoi(parm);
1917                                 break;
1918                         case 'f':
1919                                 if (i + 1 >= argc) {
1920                                         printf("-f needs file as arg\n");
1921                                         break;
1922                                 }
1923                                 ini_file = strdup(argv[i+1]);
1924                                 i++;
1925                                 break;
1926                         case 'l':
1927                                 write_lat_log = 1;
1928                                 break;
1929                         case 'w':
1930                                 write_bw_log = 1;
1931                                 break;
1932                         default:
1933                                 printf("bad option %s\n", argv[i]);
1934                                 break;
1935                 }
1936         }
1937
1938         return i;
1939 }
1940
1941 static void print_thread_status(struct thread_data *td, int nr_running,
1942                                 int t_rate, int m_rate)
1943 {
1944         printf("Threads now running: %d", nr_running);
1945         if (m_rate || t_rate)
1946                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
1947         printf(" : [%s]\r", run_str);
1948         fflush(stdout);
1949 }
1950
1951 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1952 {
1953         int i;
1954
1955         /*
1956          * reap exited threads (TD_EXITED -> TD_REAPED)
1957          */
1958         for (i = 0; i < thread_number; i++) {
1959                 struct thread_data *td = &threads[i];
1960
1961                 if (td->runstate != TD_EXITED)
1962                         continue;
1963
1964                 td->runstate = TD_REAPED;
1965                 run_str[td->thread_number - 1] = '_';
1966                 waitpid(td->pid, NULL, 0);
1967                 (*nr_running)--;
1968                 (*m_rate) -= td->ratemin;
1969                 (*t_rate) -= td->rate;
1970
1971                 if (td->terminate)
1972                         continue;
1973
1974                 print_thread_status(td, *nr_running, *t_rate, *m_rate);
1975         }
1976 }
1977
1978 static void run_threads(char *argv[])
1979 {
1980         struct timeval genesis;
1981         struct thread_data *td;
1982         unsigned long spent;
1983         int i, todo, nr_running, m_rate, t_rate;
1984
1985         printf("Starting %d threads\n", thread_number);
1986         fflush(stdout);
1987
1988         signal(SIGINT, sig_handler);
1989
1990         todo = thread_number;
1991         nr_running = 0;
1992         m_rate = t_rate = 0;
1993
1994         for (i = 0; i < thread_number; i++) {
1995                 td = &threads[i];
1996
1997                 if (!td->create_serialize)
1998                         continue;
1999
2000                 /*
2001                  * do file setup here so it happens sequentially,
2002                  * we don't want X number of threads getting their
2003                  * client data interspersed on disk
2004                  */
2005                 if (setup_file(td)) {
2006                         td->runstate = TD_REAPED;
2007                         todo--;
2008                 }
2009         }
2010
2011         gettimeofday(&genesis, NULL);
2012
2013         while (todo) {
2014                 /*
2015                  * create threads (TD_NOT_CREATED -> TD_CREATED)
2016                  */
2017                 for (i = 0; i < thread_number; i++) {
2018                         td = &threads[i];
2019
2020                         if (td->runstate != TD_NOT_CREATED)
2021                                 continue;
2022
2023                         /*
2024                          * never got a chance to start, killed by other
2025                          * thread for some reason
2026                          */
2027                         if (td->terminate) {
2028                                 todo--;
2029                                 continue;
2030                         }
2031
2032                         if (td->start_delay) {
2033                                 spent = mtime_since_now(&genesis);
2034
2035                                 if (td->start_delay * 1000 > spent)
2036                                         continue;
2037                         }
2038
2039                         td->runstate = TD_CREATED;
2040                         run_str[td->thread_number - 1] = 'C';
2041                         sem_init(&startup_sem, 1, 1);
2042                         todo--;
2043
2044                         if (fork())
2045                                 sem_wait(&startup_sem);
2046                         else {
2047                                 thread_main(shm_id, i, argv);
2048                                 exit(0);
2049                         }
2050                 }
2051
2052                 /*
2053                  * start created threads (TD_CREATED -> TD_RUNNING)
2054                  */
2055                 for (i = 0; i < thread_number; i++) {
2056                         struct thread_data *td = &threads[i];
2057
2058                         if (td->runstate != TD_CREATED)
2059                                 continue;
2060
2061                         td->runstate = TD_RUNNING;
2062                         run_str[td->thread_number - 1] = '+';
2063                         nr_running++;
2064                         m_rate += td->ratemin;
2065                         t_rate += td->rate;
2066                         sem_post(&td->mutex);
2067
2068                         print_thread_status(td, nr_running, t_rate, m_rate);
2069                 }
2070
2071                 for (i = 0; i < thread_number; i++) {
2072                         struct thread_data *td = &threads[i];
2073
2074                         if (td->runstate == TD_RUNNING)
2075                                 run_str[td->thread_number - 1] = '+';
2076                         else if (td->runstate == TD_VERIFYING)
2077                                 run_str[td->thread_number - 1] = 'V';
2078                         else
2079                                 continue;
2080
2081                         print_thread_status(td, nr_running, t_rate, m_rate);
2082                 }
2083
2084                 reap_threads(&nr_running, &t_rate, &m_rate);
2085
2086                 if (todo)
2087                         usleep(100000);
2088         }
2089
2090         while (nr_running) {
2091                 reap_threads(&nr_running, &t_rate, &m_rate);
2092                 usleep(10000);
2093         }
2094 }
2095
2096 int setup_thread_area(void)
2097 {
2098         /*
2099          * 1024 is too much on some machines, scale max_jobs if
2100          * we get a failure that looks like too large a shm segment
2101          */
2102         do {
2103                 int s = max_jobs * sizeof(struct thread_data);
2104
2105                 shm_id = shmget(0, s, IPC_CREAT | 0600);
2106                 if (shm_id != -1)
2107                         break;
2108                 if (errno != EINVAL) {
2109                         perror("shmget");
2110                         break;
2111                 }
2112
2113                 max_jobs >>= 1;
2114         } while (max_jobs);
2115
2116         if (shm_id == -1)
2117                 return 1;
2118
2119         threads = shmat(shm_id, NULL, 0);
2120         if (threads == (void *) -1) {
2121                 perror("shmat");
2122                 return 1;
2123         }
2124
2125         atexit(free_shm);
2126         return 0;
2127 }
2128
2129 int main(int argc, char *argv[])
2130 {
2131         static unsigned long max_run[2], min_run[2];
2132         static unsigned long max_bw[2], min_bw[2];
2133         static unsigned long io_mb[2], agg[2];
2134         int i;
2135
2136         if (setup_thread_area())
2137                 return 1;
2138
2139         if (sched_getaffinity(getpid(), sizeof(cpu_set_t), &def_thread.cpumask) == -1) {
2140                 perror("sched_getaffinity");
2141                 return 1;
2142         }
2143
2144         /*
2145          * fill globals
2146          */
2147         def_thread.ddir = DDIR_READ;
2148         def_thread.bs = DEF_BS;
2149         def_thread.min_bs = -1;
2150         def_thread.max_bs = -1;
2151         def_thread.odirect = DEF_ODIRECT;
2152         def_thread.ratecycle = DEF_RATE_CYCLE;
2153         def_thread.sequential = DEF_SEQUENTIAL;
2154         def_thread.timeout = DEF_TIMEOUT;
2155         def_thread.create_file = DEF_CREATE;
2156         def_thread.overwrite = DEF_OVERWRITE;
2157         def_thread.invalidate_cache = DEF_INVALIDATE;
2158         def_thread.sync_io = DEF_SYNCIO;
2159         def_thread.mem_type = MEM_MALLOC;
2160         def_thread.bw_avg_time = DEF_BWAVGTIME;
2161         def_thread.create_serialize = DEF_CREATE_SER;
2162         def_thread.create_fsync = DEF_CREATE_FSYNC;
2163         def_thread.loops = DEF_LOOPS;
2164         def_thread.verify = DEF_VERIFY;
2165
2166         i = parse_options(argc, argv);
2167
2168         if (!ini_file) {
2169                 printf("Need job file\n");
2170                 return 1;
2171         }
2172
2173         if (parse_jobs_ini(ini_file))
2174                 return 1;
2175
2176         if (!thread_number) {
2177                 printf("Nothing to do\n");
2178                 return 1;
2179         }
2180
2181         run_threads(argv);
2182
2183         min_bw[0] = min_run[0] = ~0UL;
2184         min_bw[1] = min_run[1] = ~0UL;
2185         io_mb[0] = io_mb[1] = 0;
2186         agg[0] = agg[1] = 0;
2187         for (i = 0; i < thread_number; i++) {
2188                 struct thread_data *td = &threads[i];
2189                 unsigned long bw = 0;
2190
2191                 if (!td->error) {
2192                         if (td->runtime < min_run[td->ddir])
2193                                 min_run[td->ddir] = td->runtime;
2194                         if (td->runtime > max_run[td->ddir])
2195                                 max_run[td->ddir] = td->runtime;
2196
2197                         if (td->runtime)
2198                                 bw = td->io_kb * 1024 / td->runtime;
2199                         if (bw < min_bw[td->ddir])
2200                                 min_bw[td->ddir] = bw;
2201                         if (bw > max_bw[td->ddir])
2202                                 max_bw[td->ddir] = bw;
2203
2204                         io_mb[td->ddir] += td->io_kb >> 10;
2205                 }
2206
2207                 show_thread_status(td);
2208         }
2209         
2210         if (max_run[0])
2211                 agg[0] = io_mb[0] * 1024 * 1000 / max_run[0];
2212         if (max_run[1])
2213                 agg[1] = io_mb[1] * 1024 * 1000 / max_run[1];
2214
2215         printf("\nRun status:\n");
2216         if (max_run[DDIR_READ])
2217                 printf("   READ: io=%luMiB, aggrb=%lu, minb=%lu, maxb=%lu, mint=%lumsec, maxt=%lumsec\n", io_mb[0], agg[0], min_bw[0], max_bw[0], min_run[0], max_run[0]);
2218         if (max_run[DDIR_WRITE])
2219                 printf("  WRITE: io=%luMiB, aggrb=%lu, minb=%lu, maxb=%lu, mint=%lumsec, maxt=%lumsec\n", io_mb[1], agg[1], min_bw[1], max_bw[1], min_run[1], max_run[1]);
2220
2221         return 0;
2222 }