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