[PATCH] fio: fixup rate calculations
[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
138 static int thread_number;
139 static char *ini_file;
140
141 static int max_jobs = MAX_JOBS;
142
143 static char run_str[MAX_JOBS + 1];
144
145 static int shm_id;
146
147 enum {
148         DDIR_READ = 0,
149         DDIR_WRITE,
150 };
151
152 /*
153  * thread life cycle
154  */
155 enum {
156         TD_NOT_CREATED = 0,
157         TD_CREATED,
158         TD_STARTED,
159         TD_EXITED,
160         TD_REAPED,
161 };
162
163 enum {
164         MEM_MALLOC,
165         MEM_SHM,
166 };
167
168 /*
169  * The io unit
170  */
171 struct io_u {
172         struct iocb iocb;
173         struct timeval start_time;
174         struct timeval issue_time;
175
176         char *buf;
177         unsigned int buflen;
178         unsigned long long offset;
179
180         struct list_head list;
181 };
182
183 struct io_stat {
184         unsigned long val;
185         unsigned long val_sq;
186         unsigned long max_val;
187         unsigned long min_val;
188         unsigned long samples;
189 };
190
191 struct io_sample {
192         unsigned long time;
193         unsigned long val;
194 };
195
196 struct io_log {
197         unsigned long nr_samples;
198         unsigned long max_samples;
199         struct io_sample *log;
200 };
201
202 #define td_read(td)             ((td)->ddir == DDIR_READ)
203 #define should_fsync(td)        (!td_read(td) && !(td)->odirect)
204
205 struct thread_data {
206         char file_name[256];
207         int thread_number;
208         int error;
209         int fd;
210         pid_t pid;
211         char *orig_buffer;
212         volatile int terminate;
213         volatile int runstate;
214         unsigned int ddir;
215         unsigned int ioprio;
216         unsigned int sequential;
217         unsigned int bs;
218         unsigned int min_bs;
219         unsigned int max_bs;
220         unsigned int odirect;
221         unsigned int delay_sleep;
222         unsigned int fsync_blocks;
223         unsigned int start_delay;
224         unsigned int timeout;
225         unsigned int use_aio;
226         unsigned int create_file;
227         unsigned int overwrite;
228         unsigned int invalidate_cache;
229         unsigned long long file_size;
230         unsigned long long file_offset;
231         unsigned int sync_io;
232         unsigned int mem_type;
233         cpu_set_t cpumask;
234
235         struct drand48_data bsrange_state;
236
237         int shm_id;
238
239         off_t cur_off;
240
241         io_context_t aio_ctx;
242         unsigned int aio_depth;
243         struct io_event *aio_events;
244
245         unsigned int cur_depth;
246         struct list_head io_u_freelist;
247         struct list_head io_u_busylist;
248
249         unsigned int rate;
250         unsigned int ratemin;
251         unsigned int ratecycle;
252         unsigned long rate_usec_cycle;
253         long rate_pending_usleep;
254         unsigned long rate_kb;
255         struct timeval lastrate;
256
257         unsigned long runtime;          /* sec */
258         unsigned long kb;
259         unsigned long io_blocks;
260         unsigned long io_kb;
261         unsigned long last_kb;
262         sem_t mutex;
263         struct drand48_data random_state;
264
265         /*
266          * bandwidth and latency stats
267          */
268         struct io_stat clat_stat;               /* completion latency */
269         struct io_stat slat_stat;               /* submission latency */
270
271         struct io_stat bw_stat;                 /* bandwidth stats */
272         unsigned long stat_io_kb;
273         struct timeval stat_sample_time;
274
275         struct io_log *lat_log;
276         struct io_log *bw_log;
277
278         struct timeval start;
279 };
280
281 static struct thread_data *threads;
282 static struct thread_data def_thread;
283
284 static sem_t startup_sem;
285
286 static void sig_handler(int sig)
287 {
288         int i;
289
290         for (i = 0; i < thread_number; i++) {
291                 struct thread_data *td = &threads[i];
292
293                 td->terminate = 1;
294                 td->start_delay = 0;
295         }
296 }
297
298 static int init_random_state(struct thread_data *td)
299 {
300         unsigned long seed = DEF_RANDSEED;
301
302         srand48_r(seed, &td->bsrange_state);
303
304         if (td->sequential)
305                 return 0;
306
307         if (!repeatable) {
308                 int fd = open("/dev/random", O_RDONLY);
309
310                 if (fd == -1) {
311                         td->error = errno;
312                         return 1;
313                 }
314
315                 if (read(fd, &seed, sizeof(seed)) < (int) sizeof(seed)) {
316                         td->error = EIO;
317                         close(fd);
318                         return 1;
319                 }
320
321                 close(fd);
322         }
323
324         srand48_r(seed, &td->random_state);
325         return 0;
326 }
327
328 static unsigned long utime_since(struct timeval *s, struct timeval *e)
329 {
330         double sec, usec;
331
332         sec = e->tv_sec - s->tv_sec;
333         usec = e->tv_usec - s->tv_usec;
334         if (sec > 0 && usec < 0) {
335                 sec--;
336                 usec += 1000000;
337         }
338
339         sec *= (double) 1000000;
340
341         return sec + usec;
342 }
343
344 static unsigned long mtime_since(struct timeval *s, struct timeval *e)
345 {
346         double sec, usec;
347
348         sec = e->tv_sec - s->tv_sec;
349         usec = e->tv_usec - s->tv_usec;
350         if (sec > 0 && usec < 0) {
351                 sec--;
352                 usec += 1000000;
353         }
354
355         sec *= (double) 1000;
356         usec /= (double) 1000;
357
358         return sec + usec;
359 }
360
361 static unsigned long mtime_since_now(struct timeval *s)
362 {
363         struct timeval t;
364
365         gettimeofday(&t, NULL);
366         return mtime_since(s, &t);
367 }
368
369 static inline unsigned long msec_now(struct timeval *s)
370 {
371         return s->tv_sec * 1000 + s->tv_usec / 1000;
372 }
373
374 static unsigned long long get_next_offset(struct thread_data *td)
375 {
376         unsigned long long b;
377         long r;
378
379         if (!td->sequential) {
380                 lrand48_r(&td->random_state, &r);
381                 b = (1+(double) (td->kb-1) * r / (RAND_MAX+1.0));
382         } else
383                 b = td->last_kb << 10;
384
385         return b + td->file_offset;
386 }
387
388 static unsigned int get_next_buflen(struct thread_data *td)
389 {
390         unsigned int buflen;
391         long r;
392
393         if (td->min_bs == td->max_bs)
394                 buflen = td->min_bs;
395         else {
396                 lrand48_r(&td->bsrange_state, &r);
397                 buflen = (1 + (double) (td->max_bs - 1) * r / (RAND_MAX + 1.0));
398                 buflen = (buflen + td->min_bs - 1) & ~(td->min_bs - 1);
399         }
400
401         if (buflen > ((td->kb - td->io_kb) << 10))
402                 buflen = (td->kb - td->io_kb) << 10;
403
404         td->last_kb += buflen >> 10;
405         return buflen;
406 }
407
408 static inline void add_stat_sample(struct thread_data *td, struct io_stat *is,
409                                    unsigned long val)
410 {
411         if (val > is->max_val)
412                 is->max_val = val;
413         if (val < is->min_val)
414                 is->min_val = val;
415
416         is->val += val;
417         is->val_sq += val * val;
418         is->samples++;
419 }
420
421 static void add_log_sample(struct thread_data *td, struct io_log *log,
422                            unsigned long val)
423 {
424         if (log->nr_samples == log->max_samples) {
425                 int new_size = sizeof(struct io_sample) * log->max_samples * 2;
426
427                 log->log = realloc(log->log, new_size);
428                 log->max_samples <<= 1;
429         }
430
431         log->log[log->nr_samples].val = val;
432         log->log[log->nr_samples].time = mtime_since_now(&td->start);
433         log->nr_samples++;
434 }
435
436 static void add_clat_sample(struct thread_data *td, unsigned long msec)
437 {
438         add_stat_sample(td, &td->clat_stat, msec);
439
440         if (td->lat_log)
441                 add_log_sample(td, td->lat_log, msec);
442 }
443
444 static void add_slat_sample(struct thread_data *td, unsigned long msec)
445 {
446         add_stat_sample(td, &td->slat_stat, msec);
447 }
448
449 static void add_bw_sample(struct thread_data *td, unsigned long msec)
450 {
451         unsigned long spent = mtime_since_now(&td->stat_sample_time);
452         unsigned long rate;
453
454         if (spent < 500)
455                 return;
456
457         rate = ((td->io_kb - td->stat_io_kb) * 1024) / spent;
458         add_stat_sample(td, &td->bw_stat, rate);
459
460         if (td->bw_log)
461                 add_log_sample(td, td->bw_log, rate);
462
463         gettimeofday(&td->stat_sample_time, NULL);
464         td->stat_io_kb = td->io_kb;
465 }
466
467 static void usec_sleep(int usec)
468 {
469         struct timespec req = { .tv_sec = 0, .tv_nsec = usec * 1000 };
470         struct timespec rem;
471
472         do {
473                 rem.tv_sec = rem.tv_nsec = 0;
474                 nanosleep(&req, &rem);
475                 if (!rem.tv_nsec)
476                         break;
477
478                 req.tv_nsec = rem.tv_nsec;
479         } while (1);
480 }
481
482 static void rate_throttle(struct thread_data *td, unsigned long time_spent,
483                           unsigned int bytes)
484 {
485         unsigned long usec_cycle;
486
487         if (!td->rate)
488                 return;
489
490         usec_cycle = td->rate_usec_cycle * (bytes / td->min_bs);
491
492         if (time_spent < usec_cycle) {
493                 unsigned long s = usec_cycle - time_spent;
494
495                 td->rate_pending_usleep += s;
496                 if (td->rate_pending_usleep >= 100000) {
497                         usec_sleep(td->rate_pending_usleep);
498                         td->rate_pending_usleep = 0;
499                 }
500         } else {
501                 long overtime = time_spent - usec_cycle;
502
503                 td->rate_pending_usleep -= overtime;
504         }
505 }
506
507 static int check_min_rate(struct thread_data *td, struct timeval *now)
508 {
509         unsigned long spent;
510         unsigned long rate;
511
512         /*
513          * allow a 2 second settle period in the beginning
514          */
515         if (mtime_since(&td->start, now) < 2000)
516                 return 0;
517
518         /*
519          * if rate blocks is set, sample is running
520          */
521         if (td->rate_kb) {
522                 spent = mtime_since(&td->lastrate, now);
523                 if (spent < td->ratecycle)
524                         return 0;
525
526                 rate = ((td->io_kb - td->rate_kb) * 1024) / spent;
527                 if (rate < td->ratemin) {
528                         printf("Client%d: min rate %d not met, got %ldKiB/sec\n", td->thread_number, td->ratemin, rate);
529                         if (rate_quit)
530                                 sig_handler(0);
531                         return 1;
532                 }
533         }
534
535         td->rate_kb = td->io_kb;
536         memcpy(&td->lastrate, now, sizeof(*now));
537         return 0;
538 }
539
540 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
541 {
542         if (mtime_since(&td->start, t) >= td->timeout * 1000)
543                 return 1;
544
545         return 0;
546 }
547
548 static void put_io_u(struct thread_data *td, struct io_u *io_u)
549 {
550         list_del(&io_u->list);
551         list_add(&io_u->list, &td->io_u_freelist);
552         td->cur_depth--;
553 }
554
555 static struct io_u *get_io_u(struct thread_data *td)
556 {
557         struct io_u *io_u;
558         unsigned int len;
559         unsigned long long off;
560
561         if (list_empty(&td->io_u_freelist))
562                 return NULL;
563
564         off = get_next_offset(td);
565         len = get_next_buflen(td);
566         if (!len)
567                 return NULL;
568
569         io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
570         list_del(&io_u->list);
571         list_add(&io_u->list, &td->io_u_busylist);
572
573         io_u->offset = off;
574         io_u->buflen = len;
575
576         if (td->use_aio) {
577                 if (td_read(td))
578                         io_prep_pread(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
579                 else
580                         io_prep_pwrite(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
581         }
582
583         gettimeofday(&io_u->start_time, NULL);
584         td->cur_depth++;
585         return io_u;
586 }
587
588 static void do_sync_io(struct thread_data *td)
589 {
590         unsigned long msec, usec;
591         struct timeval e;
592
593         td->cur_off = 0;
594
595         for (td->io_kb = 0; td->io_kb < td->kb;) {
596                 struct io_u *io_u;
597                 int ret;
598
599                 if (td->terminate)
600                         break;
601
602                 io_u = get_io_u(td);
603                 if (!io_u)
604                         break;
605
606                 if (td->cur_off != io_u->offset) {
607                         if (lseek(td->fd, io_u->offset, SEEK_SET) == -1) {
608                                 td->error = errno;
609                                 break;
610                         }
611                 }
612
613                 if (td->delay_sleep)
614                         usec_sleep(td->delay_sleep);
615
616                 if (td_read(td))
617                         ret = read(td->fd, io_u->buf, io_u->buflen);
618                 else
619                         ret = write(td->fd, io_u->buf, io_u->buflen);
620
621                 if (ret < (int) io_u->buflen) {
622                         if (ret == -1)
623                                 td->error = errno;
624                         break;
625                 }
626
627                 td->io_blocks++;
628                 td->io_kb += io_u->buflen >> 10;
629                 td->cur_off = io_u->offset + io_u->buflen;
630
631                 if (should_fsync(td) && td->fsync_blocks &&
632                     (td->io_blocks % td->fsync_blocks) == 0)
633                         fsync(td->fd);
634
635                 gettimeofday(&e, NULL);
636
637                 usec = utime_since(&io_u->start_time, &e);
638
639                 rate_throttle(td, usec, io_u->buflen);
640
641                 if (check_min_rate(td, &e)) {
642                         td->error = ENODATA;
643                         break;
644                 }
645
646                 msec = usec / 1000;
647                 add_clat_sample(td, msec);
648                 add_bw_sample(td, msec);
649
650                 if (runtime_exceeded(td, &e))
651                         break;
652
653                 put_io_u(td, io_u);
654         }
655
656         if (should_fsync(td))
657                 fsync(td->fd);
658 }
659
660 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
661 {
662         struct iocb *iocb = &io_u->iocb;
663         int ret;
664
665         do {
666                 ret = io_submit(td->aio_ctx, 1, &iocb);
667                 if (ret == 1)
668                         return 0;
669                 else if (ret == EAGAIN)
670                         usleep(100);
671                 else if (ret == EINTR)
672                         continue;
673                 else
674                         break;
675         } while (1);
676
677         return ret;
678 }
679
680 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
681 #define ev_to_iou(ev)   (struct io_u *) ((unsigned long) (ev)->obj)
682
683 static int ios_completed(struct thread_data *td, int nr)
684 {
685         unsigned long msec;
686         struct io_u *io_u;
687         struct timeval e;
688         int i, bytes_done;
689
690         gettimeofday(&e, NULL);
691
692         for (i = 0, bytes_done = 0; i < nr; i++) {
693                 io_u = ev_to_iou(td->aio_events + i);
694
695                 td->io_blocks++;
696                 td->io_kb += io_u->buflen >> 10;
697                 bytes_done += io_u->buflen;
698
699                 msec = mtime_since(&io_u->issue_time, &e);
700
701                 add_clat_sample(td, msec);
702                 add_bw_sample(td, msec);
703
704                 put_io_u(td, io_u);
705         }
706
707         return bytes_done;
708 }
709
710 static void cleanup_pending_aio(struct thread_data *td)
711 {
712         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
713         struct list_head *entry, *n;
714         struct io_u *io_u;
715         int r;
716
717         /*
718          * get immediately available events, if any
719          */
720         r = io_getevents(td->aio_ctx, 0, td->cur_depth, td->aio_events, &ts);
721         if (r > 0)
722                 ios_completed(td, r);
723
724         /*
725          * now cancel remaining active events
726          */
727         list_for_each_safe(entry, n, &td->io_u_busylist) {
728                 io_u = list_entry(entry, struct io_u, list);
729
730                 r = io_cancel(td->aio_ctx, &io_u->iocb, td->aio_events);
731                 if (!r)
732                         put_io_u(td, io_u);
733         }
734
735         if (td->cur_depth) {
736                 r = io_getevents(td->aio_ctx, td->cur_depth, td->cur_depth, td->aio_events, NULL);
737                 if (r > 0)
738                         ios_completed(td, r);
739         }
740 }
741
742 static void do_async_io(struct thread_data *td)
743 {
744         struct timeval s, e;
745         unsigned long usec;
746
747         for (td->io_kb = 0; td->io_kb < td->kb;) {
748                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
749                 struct timespec *timeout;
750                 int ret, min_evts = 0;
751                 struct io_u *io_u;
752                 unsigned int bytes_done;
753
754                 if (td->terminate)
755                         break;
756
757                 if (td->delay_sleep)
758                         usec_sleep(td->delay_sleep);
759
760                 io_u = get_io_u(td);
761                 if (!io_u)
762                         break;
763
764                 memcpy(&s, &io_u->start_time, sizeof(s));
765
766                 ret = io_u_queue(td, io_u);
767                 if (ret) {
768                         put_io_u(td, io_u);
769                         td->error = ret;
770                         break;
771                 }
772
773                 gettimeofday(&io_u->issue_time, NULL);
774                 add_slat_sample(td, mtime_since(&io_u->start_time, &io_u->issue_time));
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 err:
1139         if (td->fd != -1) {
1140                 close(td->fd);
1141                 td->fd = -1;
1142         }
1143         if (td->use_aio)
1144                 cleanup_aio(td);
1145         cleanup_io_u(td);
1146         if (ret) {
1147                 sem_post(&startup_sem);
1148                 sem_wait(&td->mutex);
1149         }
1150         td->runstate = TD_EXITED;
1151         shmdt(data);
1152         return NULL;
1153 }
1154
1155 static void free_shm(void)
1156 {
1157         struct shmid_ds sbuf;
1158
1159         if (threads) {
1160                 shmdt(threads);
1161                 threads = NULL;
1162                 shmctl(shm_id, IPC_RMID, &sbuf);
1163         }
1164 }
1165
1166 static int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
1167                     double *mean, double *dev)
1168 {
1169         double n;
1170
1171         if (is->samples == 0)
1172                 return 0;
1173
1174         *min = is->min_val;
1175         *max = is->max_val;
1176
1177         n = (double) is->samples;
1178         *mean = (double) is->val / n;
1179         *dev = sqrt(((double) is->val_sq - (*mean * *mean) / n) / (n - 1));
1180         return 1;
1181 }
1182
1183 static void show_thread_status(struct thread_data *td)
1184 {
1185         int prio, prio_class;
1186         unsigned long min, max, bw = 0;
1187         double mean, dev;
1188
1189         if (!td->io_kb && !td->error)
1190                 return;
1191
1192         if (td->runtime)
1193                 bw = td->io_kb * 1024 / td->runtime;
1194
1195         prio = td->ioprio & 0xff;
1196         prio_class = td->ioprio >> IOPRIO_CLASS_SHIFT;
1197
1198         printf("Client%d: err=%2d, io=%6luMiB, bw=%6luKiB/s\n", td->thread_number, td->error, td->io_kb >> 10, bw);
1199
1200         if (calc_lat(&td->slat_stat, &min, &max, &mean, &dev))
1201                 printf("  slat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1202         if (calc_lat(&td->clat_stat, &min, &max, &mean, &dev))
1203                 printf("  clat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1204         if (calc_lat(&td->bw_stat, &min, &max, &mean, &dev))
1205                 printf("  bw (KiB/s) : min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1206 }
1207
1208 static int setup_rate(struct thread_data *td)
1209 {
1210         int nr_reads_per_sec;
1211
1212         if (!td->rate)
1213                 return 0;
1214
1215         if (td->rate < td->ratemin) {
1216                 fprintf(stderr, "min rate larger than nominal rate\n");
1217                 return -1;
1218         }
1219
1220         nr_reads_per_sec = td->rate * 1024 / td->min_bs;
1221         td->rate_usec_cycle = 1000000 / nr_reads_per_sec;
1222         td->rate_pending_usleep = 0;
1223         return 0;
1224 }
1225
1226 static struct thread_data *get_new_job(int global)
1227 {
1228         struct thread_data *td;
1229
1230         if (global)
1231                 return &def_thread;
1232         if (thread_number >= max_jobs)
1233                 return NULL;
1234
1235         td = &threads[thread_number++];
1236         memset(td, 0, sizeof(*td));
1237
1238         td->fd = -1;
1239         td->thread_number = thread_number;
1240
1241         td->ddir = def_thread.ddir;
1242         td->ioprio = def_thread.ioprio;
1243         td->sequential = def_thread.sequential;
1244         td->bs = def_thread.bs;
1245         td->min_bs = def_thread.min_bs;
1246         td->max_bs = def_thread.max_bs;
1247         td->odirect = def_thread.odirect;
1248         td->delay_sleep = def_thread.delay_sleep;
1249         td->fsync_blocks = def_thread.fsync_blocks;
1250         td->start_delay = def_thread.start_delay;
1251         td->timeout = def_thread.timeout;
1252         td->use_aio = def_thread.use_aio;
1253         td->create_file = def_thread.create_file;
1254         td->overwrite = def_thread.overwrite;
1255         td->invalidate_cache = def_thread.invalidate_cache;
1256         td->file_size = def_thread.file_size;
1257         td->file_offset = def_thread.file_offset;
1258         td->rate = def_thread.rate;
1259         td->ratemin = def_thread.ratemin;
1260         td->ratecycle = def_thread.ratecycle;
1261         td->aio_depth = def_thread.aio_depth;
1262         td->sync_io = def_thread.sync_io;
1263         td->mem_type = def_thread.mem_type;
1264         memcpy(&td->cpumask, &def_thread.cpumask, sizeof(td->cpumask));
1265
1266         return td;
1267 }
1268
1269 static void put_job(struct thread_data *td)
1270 {
1271         memset(&threads[td->thread_number - 1], 0, sizeof(*td));
1272         thread_number--;
1273 }
1274
1275 static int add_job(struct thread_data *td, const char *filename, int prioclass,
1276                    int prio)
1277 {
1278         if (td == &def_thread)
1279                 return 0;
1280
1281         strcpy(td->file_name, filename);
1282         sem_init(&td->mutex, 1, 0);
1283         td->ioprio = (prioclass << IOPRIO_CLASS_SHIFT) | prio;
1284
1285         td->clat_stat.min_val = ULONG_MAX;
1286         td->slat_stat.min_val = ULONG_MAX;
1287         td->bw_stat.min_val = ULONG_MAX;
1288
1289         run_str[td->thread_number - 1] = 'P';
1290
1291         if (td->use_aio && !td->aio_depth)
1292                 td->aio_depth = 1;
1293
1294         if (setup_rate(td))
1295                 return -1;
1296
1297         if (write_lat_log)
1298                 setup_log(&td->lat_log);
1299         if (write_bw_log)
1300                 setup_log(&td->bw_log);
1301
1302         if (td->min_bs == -1)
1303                 td->min_bs = td->bs;
1304         if (td->max_bs == -1)
1305                 td->max_bs = td->bs;
1306
1307         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);
1308         return 0;
1309 }
1310
1311 static void fill_cpu_mask(cpu_set_t cpumask, int cpu)
1312 {
1313         unsigned int i;
1314
1315         CPU_ZERO(&cpumask);
1316
1317         for (i = 0; i < sizeof(int) * 8; i++) {
1318                 if ((1 << i) & cpu)
1319                         CPU_SET(i, &cpumask);
1320         }
1321 }
1322
1323 static void fill_option(const char *input, char *output)
1324 {
1325         int i;
1326
1327         i = 0;
1328         while (input[i] != ',' && input[i] != '}' && input[i] != '\0') {
1329                 output[i] = input[i];
1330                 i++;
1331         }
1332
1333         output[i] = '\0';
1334 }
1335
1336 unsigned long get_mult(char c)
1337 {
1338         switch (c) {
1339                 case 'k':
1340                 case 'K':
1341                         return 1024;
1342                 case 'm':
1343                 case 'M':
1344                         return 1024 * 1024;
1345                 case 'g':
1346                 case 'G':
1347                         return 1024 * 1024 * 1024;
1348                 default:
1349                         return 1;
1350         }
1351 }
1352
1353 /*
1354  * convert string after '=' into decimal value, noting any size suffix
1355  */
1356 static int str_cnv(char *p, unsigned long long *val)
1357 {
1358         char *str;
1359         int len;
1360
1361         str = strstr(p, "=");
1362         if (!str)
1363                 return 1;
1364
1365         str++;
1366         len = strlen(str);
1367
1368         *val = strtoul(str, NULL, 10);
1369         if (*val == ULONG_MAX && errno == ERANGE)
1370                 return 1;
1371
1372         *val *= get_mult(str[len - 2]);
1373         return 0;
1374 }
1375
1376 /*
1377  * job key words:
1378  *
1379  * file=
1380  * bs=
1381  * rw=
1382  * direct=
1383  */
1384 static void parse_jobs_cmd(int argc, char *argv[], int index)
1385 {
1386         struct thread_data *td;
1387         unsigned int prio, prioclass, cpu;
1388         char *string, *filename, *p, *c;
1389         int i;
1390
1391         string = malloc(256);
1392         filename = malloc(256);
1393
1394         for (i = index; i < argc; i++) {
1395                 p = argv[i];
1396
1397                 c = strpbrk(p, "{");
1398                 if (!c)
1399                         break;
1400
1401                 filename[0] = 0;
1402
1403                 td = get_new_job(0);
1404                 if (!td)
1405                         break;
1406
1407                 prioclass = 2;
1408                 prio = 4;
1409
1410                 c = strstr(p, "rw=");
1411                 if (c) {
1412                         c += 3;
1413                         if (*c == '0')
1414                                 td->ddir = DDIR_READ;
1415                         else
1416                                 td->ddir = DDIR_WRITE;
1417                 }
1418
1419                 c = strstr(p, "prio=");
1420                 if (c) {
1421                         c += 5;
1422                         prio = *c - '0';
1423                 }
1424
1425                 c = strstr(p, "prioclass=");
1426                 if (c) {
1427                         c += 10;
1428                         prioclass = *c - '0';
1429                 }
1430
1431                 c = strstr(p, "file=");
1432                 if (c) {
1433                         c += 5;
1434                         fill_option(c, filename);
1435                 }
1436
1437                 c = strstr(p, "direct=");
1438                 if (c) {
1439                         c += 7;
1440                         if (*c != '0')
1441                                 td->odirect = 1;
1442                         else
1443                                 td->odirect = 0;
1444                 }
1445
1446                 c = strstr(p, "sync=");
1447                 if (c) {
1448                         c += 5;
1449                         if (*c != '0')
1450                                 td->sync_io = 1;
1451                         else
1452                                 td->sync_io = 0;
1453                 }
1454
1455                 c = strstr(p, "delay=");
1456                 if (c) {
1457                         c += 6;
1458                         fill_option(c, string);
1459                         td->delay_sleep = strtoul(string, NULL, 10);
1460                 }
1461
1462                 c = strstr(p, "rate=");
1463                 if (c) {
1464                         c += 5;
1465                         fill_option(c, string);
1466                         td->rate = strtoul(string, NULL, 10);
1467                 }
1468
1469                 c = strstr(p, "ratemin=");
1470                 if (c) {
1471                         c += 8;
1472                         fill_option(c, string);
1473                         td->ratemin = strtoul(string, NULL, 10);
1474                 }
1475
1476                 c = strstr(p, "ratecycle=");
1477                 if (c) {
1478                         c += 10;
1479                         fill_option(c, string);
1480                         td->ratecycle = strtoul(string, NULL, 10);
1481                 }
1482
1483                 c = strstr(p, "cpumask=");
1484                 if (c) {
1485                         c += 8;
1486                         fill_option(c, string);
1487                         cpu = strtoul(string, NULL, 10);
1488                         fill_cpu_mask(td->cpumask, cpu);
1489                 }
1490
1491                 c = strstr(p, "fsync=");
1492                 if (c) {
1493                         c += 6;
1494                         fill_option(c, string);
1495                         td->fsync_blocks = strtoul(string, NULL, 10);
1496                 }
1497
1498                 c = strstr(p, "startdelay=");
1499                 if (c) {
1500                         c += 11;
1501                         fill_option(c, string);
1502                         td->start_delay = strtoul(string, NULL, 10);
1503                 }
1504
1505                 c = strstr(p, "timeout=");
1506                 if (c) {
1507                         c += 8;
1508                         fill_option(c, string);
1509                         td->timeout = strtoul(string, NULL, 10);
1510                 }
1511
1512                 c = strstr(p, "invalidate=");
1513                 if (c) {
1514                         c += 11;
1515                         if (*c != '0')
1516                                 td->invalidate_cache = 1;
1517                         else
1518                                 td->invalidate_cache = 0;
1519                 }
1520
1521                 c = strstr(p, "bs=");
1522                 if (c) {
1523                         unsigned long long bs;
1524
1525                         c += 3;
1526                         str_cnv(c, &bs);
1527                         td->bs = bs;
1528                 }
1529
1530                 c = strstr(p, "size=");
1531                 if (c) {
1532                         c += 5;
1533                         str_cnv(c, &td->file_size);
1534                 }
1535
1536                 c = strstr(p, "offset=");
1537                 if (c) {
1538                         c += 7;
1539                         str_cnv(c, &td->file_offset);
1540                 }
1541
1542                 c = strstr(p, "aio_depth=");
1543                 if (c) {
1544                         c += 10;
1545                         fill_option(c, string);
1546                         td->aio_depth = strtoul(string, NULL, 10);
1547                 }
1548
1549                 c = strstr(p, "mem=");
1550                 if (c) {
1551                         c += 4;
1552                         if (!strncmp(c, "malloc", 6))
1553                                 td->mem_type = MEM_MALLOC;
1554                         else if (!strncmp(c, "shm", 3))
1555                                 td->mem_type = MEM_SHM;
1556                         else
1557                                 printf("bad mem type %s\n", c);
1558                 }
1559
1560                 c = strstr(p, "aio");
1561                 if (c)
1562                         td->use_aio = 1;
1563
1564                 c = strstr(p, "create");
1565                 if (c)
1566                         td->create_file = 1;
1567
1568                 c = strstr(p, "overwrite");
1569                 if (c)
1570                         td->overwrite = 1;
1571
1572                 c = strstr(p, "random");
1573                 if (c)
1574                         td->sequential = 0;
1575                 c = strstr(p, "sequential");
1576                 if (c)
1577                         td->sequential = 1;
1578
1579                 if (add_job(td, filename, prioclass, prio))
1580                         put_job(td);
1581         }
1582
1583         free(string);
1584         free(filename);
1585 }
1586
1587 static int check_strcnv(char *p, char *name, unsigned long long *val)
1588 {
1589         if (!strstr(p, name))
1590                 return 1;
1591
1592         return str_cnv(p, val);
1593 }
1594
1595 static int check_str(char *p, char *name, char *option)
1596 {
1597         char *s = strstr(p, name);
1598
1599         if (!s)
1600                 return 1;
1601
1602         s += strlen(name);
1603         if (strstr(s, option))
1604                 return 0;
1605
1606         return 1;
1607 }
1608
1609 static int check_range(char *p, char *name, unsigned long *s, unsigned long *e)
1610 {
1611         char str[128];
1612         char s1, s2;
1613
1614         sprintf(str, "%s=%%lu%%c-%%lu%%c", name);
1615         if (sscanf(p, str, s, &s1, e, &s2) == 4) {
1616                 *s *= get_mult(s1);
1617                 *e *= get_mult(s2);
1618                 return 0;
1619         }
1620
1621         sprintf(str, "%s = %%lu%%c-%%lu%%c", name);
1622         if (sscanf(p, str, s, &s1, e, &s2) == 4) {
1623                 *s *= get_mult(s1);
1624                 *e *= get_mult(s2);
1625                 return 0;
1626         }
1627
1628         sprintf(str, "%s=%%lu-%%lu", name);
1629         if (sscanf(p, str, s, e) == 2)
1630                 return 0;
1631
1632         sprintf(str, "%s = %%lu-%%lu", name);
1633         if (sscanf(p, str, s, e) == 2)
1634                 return 0;
1635
1636         return 1;
1637
1638 }
1639
1640 static int check_int(char *p, char *name, unsigned int *val)
1641 {
1642         char str[128];
1643
1644         sprintf(str, "%s=%%d", name);
1645         if (sscanf(p, str, val) == 1)
1646                 return 0;
1647
1648         sprintf(str, "%s = %%d", name);
1649         if (sscanf(p, str, val) == 1)
1650                 return 0;
1651
1652         return 1;
1653 }
1654
1655 static int is_empty_or_comment(char *line)
1656 {
1657         unsigned int i;
1658
1659         for (i = 0; i < strlen(line); i++) {
1660                 if (line[i] == ';')
1661                         return 1;
1662                 if (!isspace(line[i]) && !iscntrl(line[i]))
1663                         return 0;
1664         }
1665
1666         return 1;
1667 }
1668
1669 static int parse_jobs_ini(char *file)
1670 {
1671         unsigned int prioclass, prio, cpu, global;
1672         unsigned long long ull;
1673         unsigned long ul1, ul2;
1674         struct thread_data *td;
1675         char *string, *name;
1676         fpos_t off;
1677         FILE *f;
1678         char *p;
1679
1680         f = fopen(file, "r");
1681         if (!f) {
1682                 perror("fopen");
1683                 return 1;
1684         }
1685
1686         string = malloc(4096);
1687         name = malloc(256);
1688
1689         while ((p = fgets(string, 4096, f)) != NULL) {
1690                 if (is_empty_or_comment(p))
1691                         continue;
1692                 if (sscanf(p, "[%s]", name) != 1)
1693                         continue;
1694
1695                 global = !strncmp(name, "global", 6);
1696
1697                 name[strlen(name) - 1] = '\0';
1698
1699                 td = get_new_job(global);
1700                 if (!td)
1701                         break;
1702
1703                 prioclass = 2;
1704                 prio = 4;
1705
1706                 fgetpos(f, &off);
1707                 while ((p = fgets(string, 4096, f)) != NULL) {
1708                         if (is_empty_or_comment(p))
1709                                 continue;
1710                         if (strstr(p, "["))
1711                                 break;
1712                         if (!check_int(p, "rw", &td->ddir)) {
1713                                 fgetpos(f, &off);
1714                                 continue;
1715                         }
1716                         if (!check_int(p, "prio", &prio)) {
1717                                 fgetpos(f, &off);
1718                                 continue;
1719                         }
1720                         if (!check_int(p, "prioclass", &prioclass)) {
1721                                 fgetpos(f, &off);
1722                                 continue;
1723                         }
1724                         if (!check_int(p, "direct", &td->odirect)) {
1725                                 fgetpos(f, &off);
1726                                 continue;
1727                         }
1728                         if (!check_int(p, "rate", &td->rate)) {
1729                                 fgetpos(f, &off);
1730                                 continue;
1731                         }
1732                         if (!check_int(p, "ratemin", &td->ratemin)) {
1733                                 fgetpos(f, &off);
1734                                 continue;
1735                         }
1736                         if (!check_int(p, "ratecycle", &td->ratecycle)) {
1737                                 fgetpos(f, &off);
1738                                 continue;
1739                         }
1740                         if (!check_int(p, "delay", &td->delay_sleep)) {
1741                                 fgetpos(f, &off);
1742                                 continue;
1743                         }
1744                         if (!check_int(p, "cpumask", &cpu)) {
1745                                 fill_cpu_mask(td->cpumask, cpu);
1746                                 fgetpos(f, &off);
1747                                 continue;
1748                         }
1749                         if (!check_int(p, "fsync", &td->fsync_blocks)) {
1750                                 fgetpos(f, &off);
1751                                 continue;
1752                         }
1753                         if (!check_int(p, "startdelay", &td->start_delay)) {
1754                                 fgetpos(f, &off);
1755                                 continue;
1756                         }
1757                         if (!check_int(p, "timeout", &td->timeout)) {
1758                                 fgetpos(f, &off);
1759                                 continue;
1760                         }
1761                         if (!check_int(p, "invalidate",&td->invalidate_cache)) {
1762                                 fgetpos(f, &off);
1763                                 continue;
1764                         }
1765                         if (!check_int(p, "aio_depth", &td->aio_depth)) {
1766                                 fgetpos(f, &off);
1767                                 continue;
1768                         }
1769                         if (!check_int(p, "sync", &td->sync_io)) {
1770                                 fgetpos(f, &off);
1771                                 continue;
1772                         }
1773                         if (!check_range(p, "bsrange", &ul1, &ul2)) {
1774                                 td->min_bs = ul1;
1775                                 td->max_bs = ul2;
1776                                 fgetpos(f, &off);
1777                                 continue;
1778                         }
1779                         if (!check_strcnv(p, "bs", &ull)) {
1780                                 td->bs = ull;
1781                                 fgetpos(f, &off);
1782                                 continue;
1783                         }
1784                         if (!check_strcnv(p, "size", &td->file_size)) {
1785                                 fgetpos(f, &off);
1786                                 continue;
1787                         }
1788                         if (!check_strcnv(p, "offset", &td->file_offset)) {
1789                                 fgetpos(f, &off);
1790                                 continue;
1791                         }
1792                         if (!check_str(p, "mem", "malloc")) {
1793                                 td->mem_type = MEM_MALLOC;
1794                                 fgetpos(f, &off);
1795                                 continue;
1796                         }
1797                         if (!check_str(p, "mem", "shm")) {
1798                                 td->mem_type = MEM_SHM;
1799                                 fgetpos(f, &off);
1800                                 continue;
1801                         }
1802                         if (!strncmp(p, "sequential", 10)) {
1803                                 td->sequential = 1;
1804                                 fgetpos(f, &off);
1805                                 continue;
1806                         }
1807                         if (!strncmp(p, "random", 6)) {
1808                                 td->sequential = 0;
1809                                 fgetpos(f, &off);
1810                                 continue;
1811                         }
1812                         if (!strncmp(p, "aio", 3)) {
1813                                 td->use_aio = 1;
1814                                 fgetpos(f, &off);
1815                                 continue;
1816                         }
1817                         if (!strncmp(p, "create", 6)) {
1818                                 td->create_file = 1;
1819                                 fgetpos(f, &off);
1820                                 continue;
1821                         }
1822                         if (!strncmp(p, "overwrite", 9)) {
1823                                 td->overwrite = 1;
1824                                 fgetpos(f, &off);
1825                                 continue;
1826                         }
1827                         printf("Client%d: bad option %s\n",td->thread_number,p);
1828                 }
1829                 fsetpos(f, &off);
1830
1831                 if (add_job(td, name, prioclass, prio))
1832                         put_job(td);
1833         }
1834
1835         free(string);
1836         free(name);
1837         fclose(f);
1838         return 0;
1839 }
1840
1841 static int parse_options(int argc, char *argv[])
1842 {
1843         int i;
1844
1845         for (i = 1; i < argc; i++) {
1846                 char *parm = argv[i];
1847
1848                 if (parm[0] != '-')
1849                         break;
1850
1851                 parm++;
1852                 switch (*parm) {
1853                         case 's':
1854                                 parm++;
1855                                 def_thread.sequential = !!atoi(parm);
1856                                 break;
1857                         case 'b':
1858                                 parm++;
1859                                 def_thread.bs = atoi(parm);
1860                                 def_thread.bs <<= 10;
1861                                 if (!def_thread.bs) {
1862                                         printf("bad block size\n");
1863                                         def_thread.bs = DEF_BS;
1864                                 }
1865                                 break;
1866                         case 't':
1867                                 parm++;
1868                                 def_thread.timeout = atoi(parm);
1869                                 break;
1870                         case 'r':
1871                                 parm++;
1872                                 repeatable = !!atoi(parm);
1873                                 break;
1874                         case 'R':
1875                                 parm++;
1876                                 rate_quit = !!atoi(parm);
1877                                 break;
1878                         case 'o':
1879                                 parm++;
1880                                 def_thread.odirect = !!atoi(parm);
1881                                 break;
1882                         case 'f':
1883                                 if (i + 1 >= argc) {
1884                                         printf("-f needs file as arg\n");
1885                                         break;
1886                                 }
1887                                 ini_file = strdup(argv[i+1]);
1888                                 i++;
1889                                 break;
1890                         case 'l':
1891                                 write_lat_log = 1;
1892                                 break;
1893                         case 'w':
1894                                 write_bw_log = 1;
1895                                 break;
1896                         default:
1897                                 printf("bad option %s\n", argv[i]);
1898                                 break;
1899                 }
1900         }
1901
1902         return i;
1903 }
1904
1905 static void print_thread_status(struct thread_data *td, int nr_running,
1906                                 int t_rate, int m_rate)
1907 {
1908         printf("Threads now running: %d", nr_running);
1909         if (m_rate || t_rate)
1910                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
1911         printf(" : [%s]\r", run_str);
1912         fflush(stdout);
1913 }
1914
1915 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1916 {
1917         int i;
1918
1919         /*
1920          * reap exited threads (TD_EXITED -> TD_REAPED)
1921          */
1922         for (i = 0; i < thread_number; i++) {
1923                 struct thread_data *td = &threads[i];
1924
1925                 if (td->runstate != TD_EXITED)
1926                         continue;
1927
1928                 td->runstate = TD_REAPED;
1929                 run_str[td->thread_number - 1] = '_';
1930                 waitpid(td->pid, NULL, 0);
1931                 (*nr_running)--;
1932                 (*m_rate) -= td->ratemin;
1933                 (*t_rate) -= td->rate;
1934
1935                 if (td->terminate)
1936                         continue;
1937
1938                 print_thread_status(td, *nr_running, *t_rate, *m_rate);
1939         }
1940 }
1941
1942 static void run_threads(char *argv[])
1943 {
1944         struct timeval genesis;
1945         struct thread_data *td;
1946         unsigned long spent;
1947         int i, todo, nr_running, m_rate, t_rate;
1948
1949         gettimeofday(&genesis, NULL);
1950
1951         printf("Starting %d threads\n", thread_number);
1952         fflush(stdout);
1953
1954         signal(SIGINT, sig_handler);
1955
1956         todo = thread_number;
1957         nr_running = 0;
1958         m_rate = t_rate = 0;
1959
1960         while (todo) {
1961                 /*
1962                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1963                  */
1964                 for (i = 0; i < thread_number; i++) {
1965                         td = &threads[i];
1966
1967                         if (td->runstate != TD_NOT_CREATED)
1968                                 continue;
1969
1970                         /*
1971                          * never got a chance to start, killed by other
1972                          * thread for some reason
1973                          */
1974                         if (td->terminate) {
1975                                 todo--;
1976                                 continue;
1977                         }
1978
1979                         if (td->start_delay) {
1980                                 spent = mtime_since_now(&genesis);
1981
1982                                 if (td->start_delay * 1000 > spent)
1983                                         continue;
1984                         }
1985
1986                         /*
1987                          * do file setup here so it happens sequentially,
1988                          * we don't want X number of threads getting their
1989                          * client data interspersed on disk
1990                          */
1991                         if (setup_file(td)) {
1992                                 td->terminate = 1;
1993                                 continue;
1994                         }
1995
1996                         td->runstate = TD_CREATED;
1997                         run_str[td->thread_number - 1] = 'C';
1998                         sem_init(&startup_sem, 1, 1);
1999                         todo--;
2000
2001                         if (fork())
2002                                 sem_wait(&startup_sem);
2003                         else {
2004                                 thread_main(shm_id, i, argv);
2005                                 exit(0);
2006                         }
2007                 }
2008
2009                 /*
2010                  * start created threads (TD_CREATED -> TD_STARTED)
2011                  */
2012                 for (i = 0; i < thread_number; i++) {
2013                         struct thread_data *td = &threads[i];
2014
2015                         if (td->runstate != TD_CREATED)
2016                                 continue;
2017
2018                         td->runstate = TD_STARTED;
2019                         run_str[td->thread_number - 1] = '+';
2020                         nr_running++;
2021                         m_rate += td->ratemin;
2022                         t_rate += td->rate;
2023                         sem_post(&td->mutex);
2024
2025                         print_thread_status(td, nr_running, t_rate, m_rate);
2026                 }
2027
2028                 reap_threads(&nr_running, &t_rate, &m_rate);
2029
2030                 if (todo)
2031                         usleep(100000);
2032         }
2033
2034         while (nr_running) {
2035                 reap_threads(&nr_running, &t_rate, &m_rate);
2036                 usleep(10000);
2037         }
2038 }
2039
2040 int setup_thread_area(void)
2041 {
2042         /*
2043          * 1024 is too much on some machines, scale max_jobs if
2044          * we get a failure that looks like too large a shm segment
2045          */
2046         do {
2047                 int s = max_jobs * sizeof(struct thread_data);
2048
2049                 shm_id = shmget(0, s, IPC_CREAT | 0600);
2050                 if (shm_id != -1)
2051                         break;
2052                 if (errno != EINVAL) {
2053                         perror("shmget");
2054                         break;
2055                 }
2056
2057                 max_jobs >>= 1;
2058         } while (max_jobs);
2059
2060         if (shm_id == -1)
2061                 return 1;
2062
2063         threads = shmat(shm_id, NULL, 0);
2064         if (threads == (void *) -1) {
2065                 perror("shmat");
2066                 return 1;
2067         }
2068
2069         atexit(free_shm);
2070         return 0;
2071 }
2072
2073 int main(int argc, char *argv[])
2074 {
2075         static unsigned long max_run[2], min_run[2];
2076         static unsigned long max_bw[2], min_bw[2];
2077         static unsigned long read_mb, write_mb, read_agg, write_agg;
2078         int i;
2079
2080         if (setup_thread_area())
2081                 return 1;
2082
2083         if (sched_getaffinity(getpid(), sizeof(cpu_set_t), &def_thread.cpumask) == -1) {
2084                 perror("sched_getaffinity");
2085                 return 1;
2086         }
2087
2088         /*
2089          * fill globals
2090          */
2091         def_thread.ddir = DDIR_READ;
2092         def_thread.bs = DEF_BS;
2093         def_thread.min_bs = -1;
2094         def_thread.max_bs = -1;
2095         def_thread.odirect = DEF_ODIRECT;
2096         def_thread.ratecycle = DEF_RATE_CYCLE;
2097         def_thread.sequential = DEF_SEQUENTIAL;
2098         def_thread.timeout = DEF_TIMEOUT;
2099         def_thread.create_file = DEF_CREATE;
2100         def_thread.overwrite = DEF_OVERWRITE;
2101         def_thread.invalidate_cache = DEF_INVALIDATE;
2102         def_thread.sync_io = DEF_SYNCIO;
2103         def_thread.mem_type = MEM_MALLOC;
2104
2105         i = parse_options(argc, argv);
2106
2107         if (ini_file) {
2108                 if (parse_jobs_ini(ini_file))
2109                         return 1;
2110         } else
2111                 parse_jobs_cmd(argc, argv, i);
2112
2113         if (!thread_number) {
2114                 printf("Nothing to do\n");
2115                 return 1;
2116         }
2117
2118         run_threads(argv);
2119
2120         min_bw[0] = min_run[0] = ~0UL;
2121         min_bw[1] = min_run[1] = ~0UL;
2122         for (i = 0; i < thread_number; i++) {
2123                 struct thread_data *td = &threads[i];
2124                 unsigned long bw = 0;
2125
2126                 if (td->error)
2127                         goto show_stat;
2128
2129                 if (td->runtime < min_run[td->ddir])
2130                         min_run[td->ddir] = td->runtime;
2131                 if (td->runtime > max_run[td->ddir])
2132                         max_run[td->ddir] = td->runtime;
2133
2134                 if (td->runtime)
2135                         bw = td->io_kb * 1024 / td->runtime;
2136                 if (bw < min_bw[td->ddir])
2137                         min_bw[td->ddir] = bw;
2138                 if (bw > max_bw[td->ddir])
2139                         max_bw[td->ddir] = bw;
2140
2141                 if (td_read(td)) {
2142                         read_mb += td->io_kb >> 10;
2143                         if (td->runtime)
2144                                 read_agg += td->io_kb * 1024 / td->runtime;
2145                 } else {
2146                         write_mb += td->io_kb >> 10;
2147                         if (td->runtime)
2148                                 write_agg += td->io_kb * 1024 / td->runtime;
2149                 }
2150
2151 show_stat:
2152                 show_thread_status(td);
2153         }
2154
2155         printf("\nRun status:\n");
2156         if (max_run[DDIR_READ])
2157                 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]);
2158         if (max_run[DDIR_WRITE])
2159                 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]);
2160
2161         return 0;
2162 }