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