[PATCH] String and thread inherit fixes
[fio.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 <math.h>
30 #include <assert.h>
31 #include <dirent.h>
32 #include <libgen.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <sys/wait.h>
36 #include <sys/ipc.h>
37 #include <sys/shm.h>
38 #include <sys/ioctl.h>
39 #include <sys/mman.h>
40
41 #include "fio.h"
42 #include "os.h"
43
44 #define MASK    (4095)
45
46 #define ALIGN(buf)      (char *) (((unsigned long) (buf) + MASK) & ~(MASK))
47
48 int groupid = 0;
49 int thread_number = 0;
50 static char run_str[MAX_JOBS + 1];
51 int shm_id = 0;
52 static LIST_HEAD(disk_list);
53 static struct itimerval itimer;
54 static struct timeval genesis;
55
56 static void update_io_ticks(void);
57 static void disk_util_timer_arm(void);
58 static void print_thread_status(void);
59
60 /*
61  * thread life cycle
62  */
63 enum {
64         TD_NOT_CREATED = 0,
65         TD_CREATED,
66         TD_RUNNING,
67         TD_VERIFYING,
68         TD_EXITED,
69         TD_REAPED,
70 };
71
72 #define should_fsync(td)        ((td_write(td) || td_rw(td)) && (!(td)->odirect || (td)->override_sync))
73
74 static sem_t startup_sem;
75
76 #define TERMINATE_ALL           (-1)
77
78 static void terminate_threads(int group_id)
79 {
80         int i;
81
82         for (i = 0; i < thread_number; i++) {
83                 struct thread_data *td = &threads[i];
84
85                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
86                         td->terminate = 1;
87                         td->start_delay = 0;
88                 }
89         }
90 }
91
92 static void sig_handler(int sig)
93 {
94         switch (sig) {
95                 case SIGALRM:
96                         update_io_ticks();
97                         disk_util_timer_arm();
98                         print_thread_status();
99                         break;
100                 default:
101                         printf("\nfio: terminating on signal\n");
102                         fflush(stdout);
103                         terminate_threads(TERMINATE_ALL);
104                         break;
105         }
106 }
107
108 static unsigned long utime_since(struct timeval *s, struct timeval *e)
109 {
110         double sec, usec;
111
112         sec = e->tv_sec - s->tv_sec;
113         usec = e->tv_usec - s->tv_usec;
114         if (sec > 0 && usec < 0) {
115                 sec--;
116                 usec += 1000000;
117         }
118
119         sec *= (double) 1000000;
120
121         return sec + usec;
122 }
123
124 static unsigned long utime_since_now(struct timeval *s)
125 {
126         struct timeval t;
127
128         gettimeofday(&t, NULL);
129         return utime_since(s, &t);
130 }
131
132 static unsigned long mtime_since(struct timeval *s, struct timeval *e)
133 {
134         double sec, usec;
135
136         sec = e->tv_sec - s->tv_sec;
137         usec = e->tv_usec - s->tv_usec;
138         if (sec > 0 && usec < 0) {
139                 sec--;
140                 usec += 1000000;
141         }
142
143         sec *= (double) 1000;
144         usec /= (double) 1000;
145
146         return sec + usec;
147 }
148
149 static unsigned long mtime_since_now(struct timeval *s)
150 {
151         struct timeval t;
152
153         gettimeofday(&t, NULL);
154         return mtime_since(s, &t);
155 }
156
157 static inline unsigned long msec_now(struct timeval *s)
158 {
159         return s->tv_sec * 1000 + s->tv_usec / 1000;
160 }
161
162 static unsigned long time_since_now(struct timeval *s)
163 {
164         return mtime_since_now(s) / 1000;
165 }
166
167 static int random_map_free(struct thread_data *td, unsigned long long block)
168 {
169         unsigned int idx = RAND_MAP_IDX(td, block);
170         unsigned int bit = RAND_MAP_BIT(td, block);
171
172         return (td->file_map[idx] & (1UL << bit)) == 0;
173 }
174
175 static int get_next_free_block(struct thread_data *td, unsigned long long *b)
176 {
177         int i;
178
179         *b = 0;
180         i = 0;
181         while ((*b) * td->min_bs < td->io_size) {
182                 if (td->file_map[i] != -1UL) {
183                         *b += ffz(td->file_map[i]);
184                         return 0;
185                 }
186
187                 *b += BLOCKS_PER_MAP;
188                 i++;
189         }
190
191         return 1;
192 }
193
194 static void mark_random_map(struct thread_data *td, struct io_u *io_u)
195 {
196         unsigned long block = io_u->offset / td->min_bs;
197         unsigned int blocks = 0;
198
199         while (blocks < (io_u->buflen / td->min_bs)) {
200                 unsigned int idx, bit;
201
202                 if (!random_map_free(td, block))
203                         break;
204
205                 idx = RAND_MAP_IDX(td, block);
206                 bit = RAND_MAP_BIT(td, block);
207
208                 assert(idx < td->num_maps);
209
210                 td->file_map[idx] |= (1UL << bit);
211                 block++;
212                 blocks++;
213         }
214
215         if ((blocks * td->min_bs) < io_u->buflen)
216                 io_u->buflen = blocks * td->min_bs;
217 }
218
219 static inline void add_stat_sample(struct io_stat *is, unsigned long val)
220 {
221         if (val > is->max_val)
222                 is->max_val = val;
223         if (val < is->min_val)
224                 is->min_val = val;
225
226         is->val += val;
227         is->val_sq += val * val;
228         is->samples++;
229 }
230
231 static void add_log_sample(struct thread_data *td, struct io_log *iolog,
232                            unsigned long val, int ddir)
233 {
234         if (iolog->nr_samples == iolog->max_samples) {
235                 int new_size = sizeof(struct io_sample) * iolog->max_samples*2;
236
237                 iolog->log = realloc(iolog->log, new_size);
238                 iolog->max_samples <<= 1;
239         }
240
241         iolog->log[iolog->nr_samples].val = val;
242         iolog->log[iolog->nr_samples].time = mtime_since_now(&td->epoch);
243         iolog->log[iolog->nr_samples].ddir = ddir;
244         iolog->nr_samples++;
245 }
246
247 static void add_clat_sample(struct thread_data *td, int ddir,unsigned long msec)
248 {
249         add_stat_sample(&td->clat_stat[ddir], msec);
250
251         if (td->clat_log)
252                 add_log_sample(td, td->clat_log, msec, ddir);
253 }
254
255 static void add_slat_sample(struct thread_data *td, int ddir,unsigned long msec)
256 {
257         add_stat_sample(&td->slat_stat[ddir], msec);
258
259         if (td->slat_log)
260                 add_log_sample(td, td->slat_log, msec, ddir);
261 }
262
263 static void add_bw_sample(struct thread_data *td, int ddir)
264 {
265         unsigned long spent = mtime_since_now(&td->stat_sample_time[ddir]);
266         unsigned long rate;
267
268         if (spent < td->bw_avg_time)
269                 return;
270
271         rate = (td->this_io_bytes[ddir] - td->stat_io_bytes[ddir]) / spent;
272         add_stat_sample(&td->bw_stat[ddir], rate);
273
274         if (td->bw_log)
275                 add_log_sample(td, td->bw_log, rate, ddir);
276
277         gettimeofday(&td->stat_sample_time[ddir], NULL);
278         td->stat_io_bytes[ddir] = td->this_io_bytes[ddir];
279 }
280
281 static int get_next_offset(struct thread_data *td, unsigned long long *offset)
282 {
283         unsigned long long b, rb;
284         long r;
285
286         if (!td->sequential) {
287                 unsigned long max_blocks = td->io_size / td->min_bs;
288                 int loops = 50;
289
290                 do {
291                         lrand48_r(&td->random_state, &r);
292                         b = ((max_blocks - 1) * r / (RAND_MAX+1.0));
293                         rb = b + (td->file_offset / td->min_bs);
294                         loops--;
295                 } while (!random_map_free(td, rb) && loops);
296
297                 if (!loops) {
298                         if (get_next_free_block(td, &b))
299                                 return 1;
300                 }
301         } else
302                 b = td->last_pos / td->min_bs;
303
304         *offset = (b * td->min_bs) + td->file_offset;
305         if (*offset > td->real_file_size)
306                 return 1;
307
308         return 0;
309 }
310
311 static unsigned int get_next_buflen(struct thread_data *td)
312 {
313         unsigned int buflen;
314         long r;
315
316         if (td->min_bs == td->max_bs)
317                 buflen = td->min_bs;
318         else {
319                 lrand48_r(&td->bsrange_state, &r);
320                 buflen = (1 + (double) (td->max_bs - 1) * r / (RAND_MAX + 1.0));
321                 buflen = (buflen + td->min_bs - 1) & ~(td->min_bs - 1);
322         }
323
324         if (buflen > td->io_size - td->this_io_bytes[td->ddir])
325                 buflen = td->io_size - td->this_io_bytes[td->ddir];
326
327         return buflen;
328 }
329
330 /*
331  * busy looping version for the last few usec
332  */
333 static void __usec_sleep(unsigned int usec)
334 {
335         struct timeval start;
336
337         gettimeofday(&start, NULL);
338         while (utime_since_now(&start) < usec)
339                 nop;
340 }
341
342 static void usec_sleep(struct thread_data *td, unsigned long usec)
343 {
344         struct timespec req, rem;
345
346         req.tv_sec = usec / 1000000;
347         req.tv_nsec = usec * 1000 - req.tv_sec * 1000000;
348
349         do {
350                 if (usec < 5000) {
351                         __usec_sleep(usec);
352                         break;
353                 }
354
355                 rem.tv_sec = rem.tv_nsec = 0;
356                 if (nanosleep(&req, &rem) < 0)
357                         break;
358
359                 if ((rem.tv_sec + rem.tv_nsec) == 0)
360                         break;
361
362                 req.tv_nsec = rem.tv_nsec;
363                 req.tv_sec = rem.tv_sec;
364
365                 usec = rem.tv_sec * 1000000 + rem.tv_nsec / 1000;
366         } while (!td->terminate);
367 }
368
369 static void rate_throttle(struct thread_data *td, unsigned long time_spent,
370                           unsigned int bytes)
371 {
372         unsigned long usec_cycle;
373
374         if (!td->rate)
375                 return;
376
377         usec_cycle = td->rate_usec_cycle * (bytes / td->min_bs);
378
379         if (time_spent < usec_cycle) {
380                 unsigned long s = usec_cycle - time_spent;
381
382                 td->rate_pending_usleep += s;
383                 if (td->rate_pending_usleep >= 100000) {
384                         usec_sleep(td, td->rate_pending_usleep);
385                         td->rate_pending_usleep = 0;
386                 }
387         } else {
388                 long overtime = time_spent - usec_cycle;
389
390                 td->rate_pending_usleep -= overtime;
391         }
392 }
393
394 static int check_min_rate(struct thread_data *td, struct timeval *now)
395 {
396         unsigned long spent;
397         unsigned long rate;
398         int ddir = td->ddir;
399
400         /*
401          * allow a 2 second settle period in the beginning
402          */
403         if (mtime_since(&td->start, now) < 2000)
404                 return 0;
405
406         /*
407          * if rate blocks is set, sample is running
408          */
409         if (td->rate_bytes) {
410                 spent = mtime_since(&td->lastrate, now);
411                 if (spent < td->ratecycle)
412                         return 0;
413
414                 rate = (td->this_io_bytes[ddir] - td->rate_bytes) / spent;
415                 if (rate < td->ratemin) {
416                         printf("Client%d: min rate %d not met, got %ldKiB/sec\n", td->thread_number, td->ratemin, rate);
417                         if (rate_quit)
418                                 terminate_threads(td->groupid);
419                         return 1;
420                 }
421         }
422
423         td->rate_bytes = td->this_io_bytes[ddir];
424         memcpy(&td->lastrate, now, sizeof(*now));
425         return 0;
426 }
427
428 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
429 {
430         if (!td->timeout)
431                 return 0;
432         if (mtime_since(&td->epoch, t) >= td->timeout * 1000)
433                 return 1;
434
435         return 0;
436 }
437
438 static void fill_random_bytes(struct thread_data *td,
439                               unsigned char *p, unsigned int len)
440 {
441         unsigned int todo;
442         double r;
443
444         while (len) {
445                 drand48_r(&td->verify_state, &r);
446
447                 /*
448                  * lrand48_r seems to be broken and only fill the bottom
449                  * 32-bits, even on 64-bit archs with 64-bit longs
450                  */
451                 todo = sizeof(r);
452                 if (todo > len)
453                         todo = len;
454
455                 memcpy(p, &r, todo);
456
457                 len -= todo;
458                 p += todo;
459         }
460 }
461
462 static void hexdump(void *buffer, int len)
463 {
464         unsigned char *p = buffer;
465         int i;
466
467         for (i = 0; i < len; i++)
468                 printf("%02x", p[i]);
469         printf("\n");
470 }
471
472 static int verify_io_u_crc32(struct verify_header *hdr, struct io_u *io_u)
473 {
474         unsigned char *p = (unsigned char *) io_u->buf;
475         unsigned long c;
476         int ret;
477
478         p += sizeof(*hdr);
479         c = crc32(p, hdr->len - sizeof(*hdr));
480         ret = c != hdr->crc32;
481
482         if (ret) {
483                 fprintf(stderr, "crc32: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
484                 fprintf(stderr, "crc32: wanted %lx, got %lx\n", hdr->crc32, c);
485         }
486
487         return ret;
488 }
489
490 static int verify_io_u_md5(struct verify_header *hdr, struct io_u *io_u)
491 {
492         unsigned char *p = (unsigned char *) io_u->buf;
493         struct md5_ctx md5_ctx;
494         int ret;
495
496         memset(&md5_ctx, 0, sizeof(md5_ctx));
497         p += sizeof(*hdr);
498         md5_update(&md5_ctx, p, hdr->len - sizeof(*hdr));
499
500         ret = memcmp(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
501         if (ret) {
502                 fprintf(stderr, "md5: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
503                 hexdump(hdr->md5_digest, sizeof(hdr->md5_digest));
504                 hexdump(md5_ctx.hash, sizeof(md5_ctx.hash));
505         }
506
507         return ret;
508 }
509
510 static int verify_io_u(struct io_u *io_u)
511 {
512         struct verify_header *hdr = (struct verify_header *) io_u->buf;
513         int ret;
514
515         if (hdr->fio_magic != FIO_HDR_MAGIC)
516                 return 1;
517
518         if (hdr->verify_type == VERIFY_MD5)
519                 ret = verify_io_u_md5(hdr, io_u);
520         else if (hdr->verify_type == VERIFY_CRC32)
521                 ret = verify_io_u_crc32(hdr, io_u);
522         else {
523                 fprintf(stderr, "Bad verify type %d\n", hdr->verify_type);
524                 ret = 1;
525         }
526
527         return ret;
528 }
529
530 static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
531 {
532         hdr->crc32 = crc32(p, len);
533 }
534
535 static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
536 {
537         struct md5_ctx md5_ctx;
538
539         memset(&md5_ctx, 0, sizeof(md5_ctx));
540         md5_update(&md5_ctx, p, len);
541         memcpy(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
542 }
543
544 unsigned int hweight32(unsigned int w)
545 {
546         unsigned int res = w - ((w >> 1) & 0x55555555);
547
548         res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
549         res = (res + (res >> 4)) & 0x0F0F0F0F;
550         res = res + (res >> 8);
551
552         return (res + (res >> 16)) & 0x000000FF;
553 }
554
555 unsigned long hweight64(unsigned long long w)
556 {
557 #if __WORDSIZE == 32
558         return hweight32((unsigned int)(w >> 32)) + hweight32((unsigned int)w);
559 #elif __WORDSIZE == 64
560         unsigned long long v = w - ((w >> 1) & 0x5555555555555555ul);
561
562         v = (v & 0x3333333333333333ul) + ((v >> 2) & 0x3333333333333333ul);
563         v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
564         v = v + (v >> 8);
565         v = v + (v >> 16);
566
567         return (v + (v >> 32)) & 0x00000000000000FFul;
568 #else
569 #error __WORDSIZE not defined
570 #endif
571 }
572
573 static int get_rw_ddir(struct thread_data *td)
574 {
575         /*
576          * perhaps cheasy, but use the hamming weight of the position
577          * as a randomizer for data direction.
578          */
579         if (td_rw(td))
580                 return hweight64(td->last_pos) & 1;
581         else if (td_read(td))
582                 return DDIR_READ;
583         else
584                 return DDIR_WRITE;
585 }
586
587 /*
588  * fill body of io_u->buf with random data and add a header with the
589  * (eg) sha1sum of that data.
590  */
591 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
592 {
593         unsigned char *p = (unsigned char *) io_u->buf;
594         struct verify_header hdr;
595
596         hdr.fio_magic = FIO_HDR_MAGIC;
597         hdr.len = io_u->buflen;
598         p += sizeof(hdr);
599         fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
600
601         if (td->verify == VERIFY_MD5) {
602                 fill_md5(&hdr, p, io_u->buflen - sizeof(hdr));
603                 hdr.verify_type = VERIFY_MD5;
604         } else {
605                 fill_crc32(&hdr, p, io_u->buflen - sizeof(hdr));
606                 hdr.verify_type = VERIFY_CRC32;
607         }
608
609         memcpy(io_u->buf, &hdr, sizeof(hdr));
610 }
611
612 static int td_io_prep(struct thread_data *td, struct io_u *io_u)
613 {
614         if (td->io_prep && td->io_prep(td, io_u))
615                 return 1;
616
617         return 0;
618 }
619
620 void put_io_u(struct thread_data *td, struct io_u *io_u)
621 {
622         list_del(&io_u->list);
623         list_add(&io_u->list, &td->io_u_freelist);
624         td->cur_depth--;
625 }
626
627 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
628 {
629         /*
630          * If using an iolog, grab next piece if any available.
631          */
632         if (td->iolog) {
633                 struct io_piece *ipo;
634
635                 if (list_empty(&td->io_log_list))
636                         return 1;
637
638                 ipo = list_entry(td->io_log_list.next, struct io_piece, list);
639                 list_del(&ipo->list);
640                 io_u->offset = ipo->offset;
641                 io_u->buflen = ipo->len;
642                 io_u->ddir = ipo->ddir;
643                 free(ipo);
644                 return 0;
645         }
646
647         /*
648          * No log, let the seq/rand engine retrieve the next position.
649          */
650         if (!get_next_offset(td, &io_u->offset)) {
651                 io_u->buflen = get_next_buflen(td);
652
653                 if (io_u->buflen) {
654                         io_u->ddir = get_rw_ddir(td);
655                         return 0;
656                 }
657         }
658
659         return 1;
660 }
661
662 #define queue_full(td)  (list_empty(&(td)->io_u_freelist))
663
664 struct io_u *__get_io_u(struct thread_data *td)
665 {
666         struct io_u *io_u;
667
668         if (queue_full(td))
669                 return NULL;
670
671         io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
672         io_u->error = 0;
673         io_u->resid = 0;
674         list_del(&io_u->list);
675         list_add(&io_u->list, &td->io_u_busylist);
676         td->cur_depth++;
677         return io_u;
678 }
679
680 static struct io_u *get_io_u(struct thread_data *td)
681 {
682         struct io_u *io_u;
683
684         io_u = __get_io_u(td);
685         if (!io_u)
686                 return NULL;
687
688         if (td->zone_bytes >= td->zone_size) {
689                 td->zone_bytes = 0;
690                 td->last_pos += td->zone_skip;
691         }
692
693         if (fill_io_u(td, io_u)) {
694                 put_io_u(td, io_u);
695                 return NULL;
696         }
697
698         if (io_u->buflen + io_u->offset > td->real_file_size)
699                 io_u->buflen = td->real_file_size - io_u->offset;
700
701         if (!io_u->buflen) {
702                 put_io_u(td, io_u);
703                 return NULL;
704         }
705
706         if (!td->iolog && !td->sequential)
707                 mark_random_map(td, io_u);
708
709         td->last_pos += io_u->buflen;
710
711         if (td->verify != VERIFY_NONE)
712                 populate_io_u(td, io_u);
713
714         if (td_io_prep(td, io_u)) {
715                 put_io_u(td, io_u);
716                 return NULL;
717         }
718
719         gettimeofday(&io_u->start_time, NULL);
720         return io_u;
721 }
722
723 static inline void td_set_runstate(struct thread_data *td, int runstate)
724 {
725         td->old_runstate = td->runstate;
726         td->runstate = runstate;
727 }
728
729 static int get_next_verify(struct thread_data *td, struct io_u *io_u)
730 {
731         struct io_piece *ipo;
732
733         if (list_empty(&td->io_hist_list))
734                 return 1;
735
736         ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
737         list_del(&ipo->list);
738
739         io_u->offset = ipo->offset;
740         io_u->buflen = ipo->len;
741         io_u->ddir = DDIR_READ;
742         free(ipo);
743         return 0;
744 }
745
746 static void prune_io_piece_log(struct thread_data *td)
747 {
748         struct io_piece *ipo;
749
750         while (!list_empty(&td->io_hist_list)) {
751                 ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
752
753                 list_del(&ipo->list);
754                 free(ipo);
755         }
756 }
757
758 /*
759  * log a succesful write, so we can unwind the log for verify
760  */
761 static void log_io_piece(struct thread_data *td, struct io_u *io_u)
762 {
763         struct io_piece *ipo = malloc(sizeof(struct io_piece));
764         struct list_head *entry;
765
766         INIT_LIST_HEAD(&ipo->list);
767         ipo->offset = io_u->offset;
768         ipo->len = io_u->buflen;
769
770         /*
771          * for random io where the writes extend the file, it will typically
772          * be laid out with the block scattered as written. it's faster to
773          * read them in in that order again, so don't sort
774          */
775         if (td->sequential || !td->overwrite) {
776                 list_add_tail(&ipo->list, &td->io_hist_list);
777                 return;
778         }
779
780         /*
781          * for random io, sort the list so verify will run faster
782          */
783         entry = &td->io_hist_list;
784         while ((entry = entry->prev) != &td->io_hist_list) {
785                 struct io_piece *__ipo = list_entry(entry, struct io_piece, list);
786
787                 if (__ipo->offset < ipo->offset)
788                         break;
789         }
790
791         list_add(&ipo->list, entry);
792 }
793
794 static int init_iolog(struct thread_data *td)
795 {
796         unsigned long long offset;
797         unsigned int bytes;
798         char *str, *p;
799         FILE *f;
800         int rw, i, reads, writes;
801
802         if (!td->iolog)
803                 return 0;
804
805         f = fopen(td->iolog_file, "r");
806         if (!f) {
807                 perror("fopen iolog");
808                 return 1;
809         }
810
811         str = malloc(4096);
812         reads = writes = i = 0;
813         while ((p = fgets(str, 4096, f)) != NULL) {
814                 struct io_piece *ipo;
815
816                 if (sscanf(p, "%d,%llu,%u", &rw, &offset, &bytes) != 3) {
817                         fprintf(stderr, "bad iolog: %s\n", p);
818                         continue;
819                 }
820                 if (rw == DDIR_READ)
821                         reads++;
822                 else if (rw == DDIR_WRITE)
823                         writes++;
824                 else {
825                         fprintf(stderr, "bad ddir: %d\n", rw);
826                         continue;
827                 }
828
829                 ipo = malloc(sizeof(*ipo));
830                 INIT_LIST_HEAD(&ipo->list);
831                 ipo->offset = offset;
832                 ipo->len = bytes;
833                 if (bytes > td->max_bs)
834                         td->max_bs = bytes;
835                 ipo->ddir = rw;
836                 list_add_tail(&ipo->list, &td->io_log_list);
837                 i++;
838         }
839
840         free(str);
841         fclose(f);
842
843         if (!i)
844                 return 1;
845
846         if (reads && !writes)
847                 td->ddir = DDIR_READ;
848         else if (!reads && writes)
849                 td->ddir = DDIR_READ;
850         else
851                 td->iomix = 1;
852
853         return 0;
854 }
855
856 static int sync_td(struct thread_data *td)
857 {
858         if (td->io_sync)
859                 return td->io_sync(td);
860
861         return 0;
862 }
863
864 static int io_u_getevents(struct thread_data *td, int min, int max,
865                           struct timespec *t)
866 {
867         return td->io_getevents(td, min, max, t);
868 }
869
870 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
871 {
872         gettimeofday(&io_u->issue_time, NULL);
873
874         return td->io_queue(td, io_u);
875 }
876
877 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
878
879 static void io_completed(struct thread_data *td, struct io_u *io_u,
880                          struct io_completion_data *icd)
881 {
882         struct timeval e;
883         unsigned long msec;
884
885         gettimeofday(&e, NULL);
886
887         if (!io_u->error) {
888                 unsigned int bytes = io_u->buflen - io_u->resid;
889                 const int idx = io_u->ddir;
890
891                 td->io_blocks[idx]++;
892                 td->io_bytes[idx] += bytes;
893                 td->zone_bytes += bytes;
894                 td->this_io_bytes[idx] += bytes;
895
896                 msec = mtime_since(&io_u->issue_time, &e);
897
898                 add_clat_sample(td, idx, msec);
899                 add_bw_sample(td, idx);
900
901                 if ((td_rw(td) || td_write(td)) && idx == DDIR_WRITE)
902                         log_io_piece(td, io_u);
903
904                 icd->bytes_done[idx] += bytes;
905         } else
906                 icd->error = io_u->error;
907 }
908
909 static void ios_completed(struct thread_data *td,struct io_completion_data *icd)
910 {
911         struct io_u *io_u;
912         int i;
913
914         icd->error = 0;
915         icd->bytes_done[0] = icd->bytes_done[1] = 0;
916
917         for (i = 0; i < icd->nr; i++) {
918                 io_u = td->io_event(td, i);
919
920                 io_completed(td, io_u, icd);
921                 put_io_u(td, io_u);
922         }
923 }
924
925 static void cleanup_pending_aio(struct thread_data *td)
926 {
927         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
928         struct list_head *entry, *n;
929         struct io_completion_data icd;
930         struct io_u *io_u;
931         int r;
932
933         /*
934          * get immediately available events, if any
935          */
936         r = io_u_getevents(td, 0, td->cur_depth, &ts);
937         if (r > 0) {
938                 icd.nr = r;
939                 ios_completed(td, &icd);
940         }
941
942         /*
943          * now cancel remaining active events
944          */
945         if (td->io_cancel) {
946                 list_for_each_safe(entry, n, &td->io_u_busylist) {
947                         io_u = list_entry(entry, struct io_u, list);
948
949                         r = td->io_cancel(td, io_u);
950                         if (!r)
951                                 put_io_u(td, io_u);
952                 }
953         }
954
955         if (td->cur_depth) {
956                 r = io_u_getevents(td, td->cur_depth, td->cur_depth, NULL);
957                 if (r > 0) {
958                         icd.nr = r;
959                         ios_completed(td, &icd);
960                 }
961         }
962 }
963
964 static int do_io_u_verify(struct thread_data *td, struct io_u **io_u)
965 {
966         struct io_u *v_io_u = *io_u;
967         int ret = 0;
968
969         if (v_io_u) {
970                 ret = verify_io_u(v_io_u);
971                 put_io_u(td, v_io_u);
972                 *io_u = NULL;
973         }
974
975         return ret;
976 }
977
978 static void do_verify(struct thread_data *td)
979 {
980         struct timeval t;
981         struct io_u *io_u, *v_io_u = NULL;
982         struct io_completion_data icd;
983         int ret;
984
985         td_set_runstate(td, TD_VERIFYING);
986
987         do {
988                 if (td->terminate)
989                         break;
990
991                 gettimeofday(&t, NULL);
992                 if (runtime_exceeded(td, &t))
993                         break;
994
995                 io_u = __get_io_u(td);
996                 if (!io_u)
997                         break;
998
999                 if (get_next_verify(td, io_u)) {
1000                         put_io_u(td, io_u);
1001                         break;
1002                 }
1003
1004                 if (td_io_prep(td, io_u)) {
1005                         put_io_u(td, io_u);
1006                         break;
1007                 }
1008
1009                 ret = io_u_queue(td, io_u);
1010                 if (ret) {
1011                         put_io_u(td, io_u);
1012                         td_verror(td, ret);
1013                         break;
1014                 }
1015
1016                 /*
1017                  * we have one pending to verify, do that while
1018                  * we are doing io on the next one
1019                  */
1020                 if (do_io_u_verify(td, &v_io_u))
1021                         break;
1022
1023                 ret = io_u_getevents(td, 1, 1, NULL);
1024                 if (ret != 1) {
1025                         if (ret < 0)
1026                                 td_verror(td, ret);
1027                         break;
1028                 }
1029
1030                 v_io_u = td->io_event(td, 0);
1031                 icd.nr = 1;
1032                 icd.error = 0;
1033                 io_completed(td, v_io_u, &icd);
1034
1035                 if (icd.error) {
1036                         td_verror(td, icd.error);
1037                         put_io_u(td, v_io_u);
1038                         v_io_u = NULL;
1039                         break;
1040                 }
1041
1042                 /*
1043                  * if we can't submit more io, we need to verify now
1044                  */
1045                 if (queue_full(td) && do_io_u_verify(td, &v_io_u))
1046                         break;
1047
1048         } while (1);
1049
1050         do_io_u_verify(td, &v_io_u);
1051
1052         if (td->cur_depth)
1053                 cleanup_pending_aio(td);
1054
1055         td_set_runstate(td, TD_RUNNING);
1056 }
1057
1058 static void do_io(struct thread_data *td)
1059 {
1060         struct io_completion_data icd;
1061         struct timeval s, e;
1062         unsigned long usec;
1063
1064         while (td->this_io_bytes[td->ddir] < td->io_size) {
1065                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
1066                 struct timespec *timeout;
1067                 int ret, min_evts = 0;
1068                 struct io_u *io_u;
1069
1070                 if (td->terminate)
1071                         break;
1072
1073                 io_u = get_io_u(td);
1074                 if (!io_u)
1075                         break;
1076
1077                 memcpy(&s, &io_u->start_time, sizeof(s));
1078
1079                 ret = io_u_queue(td, io_u);
1080                 if (ret) {
1081                         put_io_u(td, io_u);
1082                         td_verror(td, ret);
1083                         break;
1084                 }
1085
1086                 add_slat_sample(td, io_u->ddir, mtime_since(&io_u->start_time, &io_u->issue_time));
1087
1088                 if (td->cur_depth < td->iodepth) {
1089                         timeout = &ts;
1090                         min_evts = 0;
1091                 } else {
1092                         timeout = NULL;
1093                         min_evts = 1;
1094                 }
1095
1096                 ret = io_u_getevents(td, min_evts, td->cur_depth, timeout);
1097                 if (ret < 0) {
1098                         td_verror(td, ret);
1099                         break;
1100                 } else if (!ret)
1101                         continue;
1102
1103                 icd.nr = ret;
1104                 ios_completed(td, &icd);
1105                 if (icd.error) {
1106                         td_verror(td, icd.error);
1107                         break;
1108                 }
1109
1110                 /*
1111                  * the rate is batched for now, it should work for batches
1112                  * of completions except the very first one which may look
1113                  * a little bursty
1114                  */
1115                 gettimeofday(&e, NULL);
1116                 usec = utime_since(&s, &e);
1117
1118                 rate_throttle(td, usec, icd.bytes_done[td->ddir]);
1119
1120                 if (check_min_rate(td, &e)) {
1121                         td_verror(td, ENOMEM);
1122                         break;
1123                 }
1124
1125                 if (runtime_exceeded(td, &e))
1126                         break;
1127
1128                 if (td->thinktime)
1129                         usec_sleep(td, td->thinktime);
1130
1131                 if (should_fsync(td) && td->fsync_blocks &&
1132                     (td->io_blocks[DDIR_WRITE] % td->fsync_blocks) == 0)
1133                         sync_td(td);
1134         }
1135
1136         if (td->cur_depth)
1137                 cleanup_pending_aio(td);
1138
1139         if (should_fsync(td) && td->end_fsync)
1140                 sync_td(td);
1141 }
1142
1143 static void cleanup_io(struct thread_data *td)
1144 {
1145         if (td->io_cleanup)
1146                 td->io_cleanup(td);
1147 }
1148
1149 static int init_io(struct thread_data *td)
1150 {
1151         if (td->io_engine == FIO_SYNCIO)
1152                 return fio_syncio_init(td);
1153         else if (td->io_engine == FIO_MMAPIO)
1154                 return fio_mmapio_init(td);
1155         else if (td->io_engine == FIO_LIBAIO)
1156                 return fio_libaio_init(td);
1157         else if (td->io_engine == FIO_POSIXAIO)
1158                 return fio_posixaio_init(td);
1159         else if (td->io_engine == FIO_SGIO)
1160                 return fio_sgio_init(td);
1161         else if (td->io_engine == FIO_SPLICEIO)
1162                 return fio_spliceio_init(td);
1163         else {
1164                 fprintf(stderr, "bad io_engine %d\n", td->io_engine);
1165                 return 1;
1166         }
1167 }
1168
1169 static void cleanup_io_u(struct thread_data *td)
1170 {
1171         struct list_head *entry, *n;
1172         struct io_u *io_u;
1173
1174         list_for_each_safe(entry, n, &td->io_u_freelist) {
1175                 io_u = list_entry(entry, struct io_u, list);
1176
1177                 list_del(&io_u->list);
1178                 free(io_u);
1179         }
1180
1181         if (td->mem_type == MEM_MALLOC)
1182                 free(td->orig_buffer);
1183         else if (td->mem_type == MEM_SHM) {
1184                 struct shmid_ds sbuf;
1185
1186                 shmdt(td->orig_buffer);
1187                 shmctl(td->shm_id, IPC_RMID, &sbuf);
1188         } else if (td->mem_type == MEM_MMAP)
1189                 munmap(td->orig_buffer, td->orig_buffer_size);
1190         else
1191                 fprintf(stderr, "Bad memory type %d\n", td->mem_type);
1192
1193         td->orig_buffer = NULL;
1194 }
1195
1196 static int init_io_u(struct thread_data *td)
1197 {
1198         struct io_u *io_u;
1199         int i, max_units;
1200         char *p;
1201
1202         if (td->io_engine & FIO_SYNCIO)
1203                 max_units = 1;
1204         else
1205                 max_units = td->iodepth;
1206
1207         td->orig_buffer_size = td->max_bs * max_units + MASK;
1208
1209         if (td->mem_type == MEM_MALLOC)
1210                 td->orig_buffer = malloc(td->orig_buffer_size);
1211         else if (td->mem_type == MEM_SHM) {
1212                 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
1213                 if (td->shm_id < 0) {
1214                         td_verror(td, errno);
1215                         perror("shmget");
1216                         return 1;
1217                 }
1218
1219                 td->orig_buffer = shmat(td->shm_id, NULL, 0);
1220                 if (td->orig_buffer == (void *) -1) {
1221                         td_verror(td, errno);
1222                         perror("shmat");
1223                         td->orig_buffer = NULL;
1224                         return 1;
1225                 }
1226         } else if (td->mem_type == MEM_MMAP) {
1227                 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
1228                 if (td->orig_buffer == MAP_FAILED) {
1229                         td_verror(td, errno);
1230                         perror("mmap");
1231                         td->orig_buffer = NULL;
1232                         return 1;
1233                 }
1234         }
1235
1236         p = ALIGN(td->orig_buffer);
1237         for (i = 0; i < max_units; i++) {
1238                 io_u = malloc(sizeof(*io_u));
1239                 memset(io_u, 0, sizeof(*io_u));
1240                 INIT_LIST_HEAD(&io_u->list);
1241
1242                 io_u->buf = p + td->max_bs * i;
1243                 io_u->index = i;
1244                 list_add(&io_u->list, &td->io_u_freelist);
1245         }
1246
1247         return 0;
1248 }
1249
1250 static int create_file(struct thread_data *td, unsigned long long size,
1251                        int extend)
1252 {
1253         unsigned long long left;
1254         unsigned int bs;
1255         int r, oflags;
1256         char *b;
1257
1258         /*
1259          * unless specifically asked for overwrite, let normal io extend it
1260          */
1261         if (td_write(td) && !td->overwrite)
1262                 return 0;
1263
1264         if (!size) {
1265                 fprintf(stderr, "Need size for create\n");
1266                 td_verror(td, EINVAL);
1267                 return 1;
1268         }
1269
1270         if (!extend) {
1271                 oflags = O_CREAT | O_TRUNC;
1272                 printf("Client%d: Laying out IO file (%LuMiB)\n", td->thread_number, size >> 20);
1273         } else {
1274                 oflags = O_APPEND;
1275                 printf("Client%d: Extending IO file (%Lu -> %LuMiB)\n", td->thread_number, (td->file_size - size) >> 20, td->file_size >> 20);
1276         }
1277
1278         td->fd = open(td->file_name, O_WRONLY | oflags, 0644);
1279         if (td->fd < 0) {
1280                 td_verror(td, errno);
1281                 return 1;
1282         }
1283
1284         if (!extend && ftruncate(td->fd, td->file_size) == -1) {
1285                 td_verror(td, errno);
1286                 return 1;
1287         }
1288
1289         td->io_size = td->file_size;
1290         b = malloc(td->max_bs);
1291         memset(b, 0, td->max_bs);
1292
1293         left = size;
1294         while (left && !td->terminate) {
1295                 bs = td->max_bs;
1296                 if (bs > left)
1297                         bs = left;
1298
1299                 r = write(td->fd, b, bs);
1300
1301                 if (r == (int) bs) {
1302                         left -= bs;
1303                         continue;
1304                 } else {
1305                         if (r < 0)
1306                                 td_verror(td, errno);
1307                         else
1308                                 td_verror(td, EIO);
1309
1310                         break;
1311                 }
1312         }
1313
1314         if (td->terminate)
1315                 unlink(td->file_name);
1316         else if (td->create_fsync)
1317                 fsync(td->fd);
1318
1319         close(td->fd);
1320         td->fd = -1;
1321         free(b);
1322         return 0;
1323 }
1324
1325 static int file_size(struct thread_data *td)
1326 {
1327         struct stat st;
1328
1329         if (fstat(td->fd, &st) == -1) {
1330                 td_verror(td, errno);
1331                 return 1;
1332         }
1333
1334         td->real_file_size = st.st_size;
1335
1336         if (!td->file_size || td->file_size > td->real_file_size)
1337                 td->file_size = td->real_file_size;
1338
1339         td->file_size -= td->file_offset;
1340         return 0;
1341 }
1342
1343 static int bdev_size(struct thread_data *td)
1344 {
1345         unsigned long long bytes;
1346         int r;
1347
1348         r = blockdev_size(td->fd, &bytes);
1349         if (r) {
1350                 td_verror(td, r);
1351                 return 1;
1352         }
1353
1354         td->real_file_size = bytes;
1355
1356         /*
1357          * no extend possibilities, so limit size to device size if too large
1358          */
1359         if (!td->file_size || td->file_size > td->real_file_size)
1360                 td->file_size = td->real_file_size;
1361
1362         td->file_size -= td->file_offset;
1363         return 0;
1364 }
1365
1366 static int get_file_size(struct thread_data *td)
1367 {
1368         int ret = 0;
1369
1370         if (td->filetype == FIO_TYPE_FILE)
1371                 ret = file_size(td);
1372         else if (td->filetype == FIO_TYPE_BD)
1373                 ret = bdev_size(td);
1374         else
1375                 td->real_file_size = -1;
1376
1377         if (ret)
1378                 return ret;
1379
1380         if (td->file_offset > td->real_file_size) {
1381                 fprintf(stderr, "Client%d: offset extends end (%Lu > %Lu)\n", td->thread_number, td->file_offset, td->real_file_size);
1382                 return 1;
1383         }
1384
1385         td->io_size = td->file_size;
1386         if (td->io_size == 0) {
1387                 fprintf(stderr, "Client%d: no io blocks\n", td->thread_number);
1388                 td_verror(td, EINVAL);
1389                 return 1;
1390         }
1391
1392         if (!td->zone_size)
1393                 td->zone_size = td->io_size;
1394
1395         td->total_io_size = td->io_size * td->loops;
1396         return 0;
1397 }
1398
1399 static int setup_file_mmap(struct thread_data *td)
1400 {
1401         int flags;
1402
1403         if (td_rw(td))
1404                 flags = PROT_READ | PROT_WRITE;
1405         else if (td_write(td)) {
1406                 flags = PROT_WRITE;
1407
1408                 if (td->verify != VERIFY_NONE)
1409                         flags |= PROT_READ;
1410         } else
1411                 flags = PROT_READ;
1412
1413         td->mmap = mmap(NULL, td->file_size, flags, MAP_SHARED, td->fd, td->file_offset);
1414         if (td->mmap == MAP_FAILED) {
1415                 td->mmap = NULL;
1416                 td_verror(td, errno);
1417                 return 1;
1418         }
1419
1420         if (td->invalidate_cache) {
1421                 if (madvise(td->mmap, td->file_size, MADV_DONTNEED) < 0) {
1422                         td_verror(td, errno);
1423                         return 1;
1424                 }
1425         }
1426
1427         if (td->sequential) {
1428                 if (madvise(td->mmap, td->file_size, MADV_SEQUENTIAL) < 0) {
1429                         td_verror(td, errno);
1430                         return 1;
1431                 }
1432         } else {
1433                 if (madvise(td->mmap, td->file_size, MADV_RANDOM) < 0) {
1434                         td_verror(td, errno);
1435                         return 1;
1436                 }
1437         }
1438
1439         return 0;
1440 }
1441
1442 static int setup_file_plain(struct thread_data *td)
1443 {
1444         if (td->invalidate_cache) {
1445                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_DONTNEED) < 0) {
1446                         td_verror(td, errno);
1447                         return 1;
1448                 }
1449         }
1450
1451         if (td->sequential) {
1452                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_SEQUENTIAL) < 0) {
1453                         td_verror(td, errno);
1454                         return 1;
1455                 }
1456         } else {
1457                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_RANDOM) < 0) {
1458                         td_verror(td, errno);
1459                         return 1;
1460                 }
1461         }
1462
1463         return 0;
1464 }
1465
1466 static int setup_file(struct thread_data *td)
1467 {
1468         struct stat st;
1469         int flags = 0;
1470
1471         if (stat(td->file_name, &st) == -1) {
1472                 if (errno != ENOENT) {
1473                         td_verror(td, errno);
1474                         return 1;
1475                 }
1476                 if (!td->create_file) {
1477                         td_verror(td, ENOENT);
1478                         return 1;
1479                 }
1480                 if (create_file(td, td->file_size, 0))
1481                         return 1;
1482         } else if (td->filetype == FIO_TYPE_FILE) {
1483                 if (st.st_size < (off_t) td->file_size) {
1484                         if (create_file(td, td->file_size - st.st_size, 1))
1485                                 return 1;
1486                 }
1487         }
1488
1489         if (td->odirect)
1490                 flags |= O_DIRECT;
1491
1492         if (td_write(td) || td_rw(td)) {
1493                 if (td->filetype == FIO_TYPE_FILE) {
1494                         if (!td->overwrite)
1495                                 flags |= O_TRUNC;
1496
1497                         flags |= O_CREAT;
1498                 }
1499                 if (td->sync_io)
1500                         flags |= O_SYNC;
1501
1502                 flags |= O_RDWR;
1503
1504                 td->fd = open(td->file_name, flags, 0600);
1505         } else {
1506                 if (td->filetype == FIO_TYPE_CHAR)
1507                         flags |= O_RDWR;
1508                 else
1509                         flags |= O_RDONLY;
1510
1511                 td->fd = open(td->file_name, flags);
1512         }
1513
1514         if (td->fd == -1) {
1515                 td_verror(td, errno);
1516                 return 1;
1517         }
1518
1519         if (get_file_size(td))
1520                 return 1;
1521
1522         if (td->io_engine != FIO_MMAPIO)
1523                 return setup_file_plain(td);
1524         else
1525                 return setup_file_mmap(td);
1526 }
1527
1528 static int check_dev_match(dev_t dev, char *path)
1529 {
1530         unsigned int major, minor;
1531         char line[256], *p;
1532         FILE *f;
1533
1534         f = fopen(path, "r");
1535         if (!f) {
1536                 perror("open path");
1537                 return 1;
1538         }
1539
1540         p = fgets(line, sizeof(line), f);
1541         if (!p) {
1542                 fclose(f);
1543                 return 1;
1544         }
1545
1546         if (sscanf(p, "%u:%u", &major, &minor) != 2) {
1547                 fclose(f);
1548                 return 1;
1549         }
1550
1551         if (((major << 8) | minor) == dev) {
1552                 fclose(f);
1553                 return 0;
1554         }
1555
1556         fclose(f);
1557         return 1;
1558 }
1559
1560 static int find_block_dir(dev_t dev, char *path)
1561 {
1562         struct dirent *dir;
1563         struct stat st;
1564         int found = 0;
1565         DIR *D;
1566
1567         D = opendir(path);
1568         if (!D)
1569                 return 0;
1570
1571         while ((dir = readdir(D)) != NULL) {
1572                 char full_path[256];
1573
1574                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1575                         continue;
1576                 if (!strcmp(dir->d_name, "device"))
1577                         continue;
1578
1579                 sprintf(full_path, "%s/%s", path, dir->d_name);
1580
1581                 if (!strcmp(dir->d_name, "dev")) {
1582                         if (!check_dev_match(dev, full_path)) {
1583                                 found = 1;
1584                                 break;
1585                         }
1586                 }
1587
1588                 if (stat(full_path, &st) == -1) {
1589                         perror("stat");
1590                         break;
1591                 }
1592
1593                 if (!S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))
1594                         continue;
1595
1596                 found = find_block_dir(dev, full_path);
1597                 if (found) {
1598                         strcpy(path, full_path);
1599                         break;
1600                 }
1601         }
1602
1603         closedir(D);
1604         return found;
1605 }
1606
1607 static int get_io_ticks(struct disk_util *du, struct disk_util_stat *dus)
1608 {
1609         unsigned in_flight;
1610         char line[256];
1611         FILE *f;
1612         char *p;
1613
1614         f = fopen(du->path, "r");
1615         if (!f)
1616                 return 1;
1617
1618         p = fgets(line, sizeof(line), f);
1619         if (!p) {
1620                 fclose(f);
1621                 return 1;
1622         }
1623
1624         if (sscanf(p, "%u %u %llu %u %u %u %llu %u %u %u %u\n", &dus->ios[0], &dus->merges[0], &dus->sectors[0], &dus->ticks[0], &dus->ios[1], &dus->merges[1], &dus->sectors[1], &dus->ticks[1], &in_flight, &dus->io_ticks, &dus->time_in_queue) != 11) {
1625                 fclose(f);
1626                 return 1;
1627         }
1628
1629         fclose(f);
1630         return 0;
1631 }
1632
1633 static void update_io_tick_disk(struct disk_util *du)
1634 {
1635         struct disk_util_stat __dus, *dus, *ldus;
1636         struct timeval t;
1637
1638         if (get_io_ticks(du, &__dus))
1639                 return;
1640
1641         dus = &du->dus;
1642         ldus = &du->last_dus;
1643
1644         dus->sectors[0] += (__dus.sectors[0] - ldus->sectors[0]);
1645         dus->sectors[1] += (__dus.sectors[1] - ldus->sectors[1]);
1646         dus->ios[0] += (__dus.ios[0] - ldus->ios[0]);
1647         dus->ios[1] += (__dus.ios[1] - ldus->ios[1]);
1648         dus->merges[0] += (__dus.merges[0] - ldus->merges[0]);
1649         dus->merges[1] += (__dus.merges[1] - ldus->merges[1]);
1650         dus->ticks[0] += (__dus.ticks[0] - ldus->ticks[0]);
1651         dus->ticks[1] += (__dus.ticks[1] - ldus->ticks[1]);
1652         dus->io_ticks += (__dus.io_ticks - ldus->io_ticks);
1653         dus->time_in_queue += (__dus.time_in_queue - ldus->time_in_queue);
1654
1655         gettimeofday(&t, NULL);
1656         du->msec += mtime_since(&du->time, &t);
1657         memcpy(&du->time, &t, sizeof(t));
1658         memcpy(ldus, &__dus, sizeof(__dus));
1659 }
1660
1661 static void update_io_ticks(void)
1662 {
1663         struct list_head *entry;
1664         struct disk_util *du;
1665
1666         list_for_each(entry, &disk_list) {
1667                 du = list_entry(entry, struct disk_util, list);
1668                 update_io_tick_disk(du);
1669         }
1670 }
1671
1672 static int disk_util_exists(dev_t dev)
1673 {
1674         struct list_head *entry;
1675         struct disk_util *du;
1676
1677         list_for_each(entry, &disk_list) {
1678                 du = list_entry(entry, struct disk_util, list);
1679
1680                 if (du->dev == dev)
1681                         return 1;
1682         }
1683
1684         return 0;
1685 }
1686
1687 static void disk_util_add(dev_t dev, char *path)
1688 {
1689         struct disk_util *du = malloc(sizeof(*du));
1690
1691         memset(du, 0, sizeof(*du));
1692         INIT_LIST_HEAD(&du->list);
1693         sprintf(du->path, "%s/stat", path);
1694         du->name = strdup(basename(path));
1695         du->dev = dev;
1696
1697         gettimeofday(&du->time, NULL);
1698         get_io_ticks(du, &du->last_dus);
1699
1700         list_add_tail(&du->list, &disk_list);
1701 }
1702
1703 static void init_disk_util(struct thread_data *td)
1704 {
1705         struct stat st;
1706         char foo[256], tmp[256];
1707         dev_t dev;
1708         char *p;
1709
1710         if (!td->do_disk_util)
1711                 return;
1712
1713         if (!stat(td->file_name, &st)) {
1714                 if (S_ISBLK(st.st_mode))
1715                         dev = st.st_rdev;
1716                 else
1717                         dev = st.st_dev;
1718         } else {
1719                 /*
1720                  * must be a file, open "." in that path
1721                  */
1722                 strcpy(foo, td->file_name);
1723                 p = dirname(foo);
1724                 if (stat(p, &st)) {
1725                         perror("disk util stat");
1726                         return;
1727                 }
1728
1729                 dev = st.st_dev;
1730         }
1731
1732         if (disk_util_exists(dev))
1733                 return;
1734                 
1735         sprintf(foo, "/sys/block");
1736         if (!find_block_dir(dev, foo))
1737                 return;
1738
1739         /*
1740          * for md/dm, there's no queue dir. we already have the right place
1741          */
1742         sprintf(tmp, "%s/stat", foo);
1743         if (stat(tmp, &st)) {
1744                 /*
1745                  * if this is inside a partition dir, jump back to parent
1746                  */
1747                 sprintf(tmp, "%s/queue", foo);
1748                 if (stat(tmp, &st)) {
1749                         p = dirname(foo);
1750                         sprintf(tmp, "%s/queue", p);
1751                         if (stat(tmp, &st)) {
1752                                 fprintf(stderr, "unknown sysfs layout\n");
1753                                 return;
1754                         }
1755                         sprintf(foo, "%s", p);
1756                 }
1757         }
1758
1759         disk_util_add(dev, foo);
1760 }
1761
1762 static void disk_util_timer_arm(void)
1763 {
1764         itimer.it_value.tv_sec = 0;
1765         itimer.it_value.tv_usec = DISK_UTIL_MSEC * 1000;
1766         setitimer(ITIMER_REAL, &itimer, NULL);
1767 }
1768
1769 static void clear_io_state(struct thread_data *td)
1770 {
1771         if (td->io_engine == FIO_SYNCIO)
1772                 lseek(td->fd, SEEK_SET, 0);
1773
1774         td->last_pos = 0;
1775         td->stat_io_bytes[0] = td->stat_io_bytes[1] = 0;
1776         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
1777         td->zone_bytes = 0;
1778
1779         if (td->file_map)
1780                 memset(td->file_map, 0, td->num_maps * sizeof(long));
1781 }
1782
1783 static void update_rusage_stat(struct thread_data *td)
1784 {
1785         if (!(td->runtime[0] + td->runtime[1]))
1786                 return;
1787
1788         getrusage(RUSAGE_SELF, &td->ru_end);
1789
1790         td->usr_time += mtime_since(&td->ru_start.ru_utime, &td->ru_end.ru_utime);
1791         td->sys_time += mtime_since(&td->ru_start.ru_stime, &td->ru_end.ru_stime);
1792         td->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
1793
1794         
1795         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
1796 }
1797
1798 static void *thread_main(void *data)
1799 {
1800         struct thread_data *td = data;
1801         int ret = 1;
1802
1803         if (!td->use_thread)
1804                 setsid();
1805
1806         td->pid = getpid();
1807
1808         INIT_LIST_HEAD(&td->io_u_freelist);
1809         INIT_LIST_HEAD(&td->io_u_busylist);
1810         INIT_LIST_HEAD(&td->io_hist_list);
1811         INIT_LIST_HEAD(&td->io_log_list);
1812
1813         if (init_io_u(td))
1814                 goto err;
1815
1816         if (fio_setaffinity(td) == -1) {
1817                 td_verror(td, errno);
1818                 goto err;
1819         }
1820
1821         if (init_io(td))
1822                 goto err;
1823
1824         if (init_iolog(td))
1825                 goto err;
1826
1827         if (td->ioprio) {
1828                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1829                         td_verror(td, errno);
1830                         goto err;
1831                 }
1832         }
1833
1834         sem_post(&startup_sem);
1835         sem_wait(&td->mutex);
1836
1837         if (!td->create_serialize && setup_file(td))
1838                 goto err;
1839
1840         if (init_random_state(td))
1841                 goto err;
1842
1843         gettimeofday(&td->epoch, NULL);
1844
1845         while (td->loops--) {
1846                 getrusage(RUSAGE_SELF, &td->ru_start);
1847                 gettimeofday(&td->start, NULL);
1848                 memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1849
1850                 if (td->ratemin)
1851                         memcpy(&td->lastrate, &td->stat_sample_time, sizeof(td->lastrate));
1852
1853                 clear_io_state(td);
1854                 prune_io_piece_log(td);
1855
1856                 do_io(td);
1857
1858                 td->runtime[td->ddir] += mtime_since_now(&td->start);
1859                 if (td_rw(td) && td->io_bytes[td->ddir ^ 1])
1860                         td->runtime[td->ddir ^ 1] = td->runtime[td->ddir];
1861
1862                 update_rusage_stat(td);
1863
1864                 if (td->error || td->terminate)
1865                         break;
1866
1867                 if (td->verify == VERIFY_NONE)
1868                         continue;
1869
1870                 clear_io_state(td);
1871                 gettimeofday(&td->start, NULL);
1872
1873                 do_verify(td);
1874
1875                 td->runtime[DDIR_READ] += mtime_since_now(&td->start);
1876
1877                 if (td->error || td->terminate)
1878                         break;
1879         }
1880
1881         ret = 0;
1882
1883         if (td->bw_log)
1884                 finish_log(td, td->bw_log, "bw");
1885         if (td->slat_log)
1886                 finish_log(td, td->slat_log, "slat");
1887         if (td->clat_log)
1888                 finish_log(td, td->clat_log, "clat");
1889
1890         if (exitall_on_terminate)
1891                 terminate_threads(td->groupid);
1892
1893 err:
1894         if (td->fd != -1) {
1895                 close(td->fd);
1896                 td->fd = -1;
1897         }
1898         if (td->mmap)
1899                 munmap(td->mmap, td->file_size);
1900         cleanup_io(td);
1901         cleanup_io_u(td);
1902         if (ret) {
1903                 sem_post(&startup_sem);
1904                 sem_wait(&td->mutex);
1905         }
1906         td_set_runstate(td, TD_EXITED);
1907         return NULL;
1908
1909 }
1910
1911 static void *fork_main(int shmid, int offset)
1912 {
1913         struct thread_data *td;
1914         void *data;
1915
1916         data = shmat(shmid, NULL, 0);
1917         if (data == (void *) -1) {
1918                 perror("shmat");
1919                 return NULL;
1920         }
1921
1922         td = data + offset * sizeof(struct thread_data);
1923         thread_main(td);
1924         shmdt(data);
1925         return NULL;
1926 }
1927
1928 static int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
1929                     double *mean, double *dev)
1930 {
1931         double n;
1932
1933         if (is->samples == 0)
1934                 return 0;
1935
1936         *min = is->min_val;
1937         *max = is->max_val;
1938
1939         n = (double) is->samples;
1940         *mean = (double) is->val / n;
1941         *dev = sqrt(((double) is->val_sq - (*mean * *mean) / n) / (n - 1));
1942         if (!(*min + *max) && !(*mean + *dev))
1943                 return 0;
1944
1945         return 1;
1946 }
1947
1948 static void show_ddir_status(struct thread_data *td, struct group_run_stats *rs,
1949                              int ddir)
1950 {
1951         char *ddir_str[] = { "read ", "write" };
1952         unsigned long min, max, bw;
1953         double mean, dev;
1954
1955         if (!td->runtime[ddir])
1956                 return;
1957
1958         bw = td->io_bytes[ddir] / td->runtime[ddir];
1959         printf("  %s: io=%6lluMiB, bw=%6luKiB/s, runt=%6lumsec\n", ddir_str[ddir], td->io_bytes[ddir] >> 20, bw, td->runtime[ddir]);
1960
1961         if (calc_lat(&td->slat_stat[ddir], &min, &max, &mean, &dev))
1962                 printf("    slat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1963
1964         if (calc_lat(&td->clat_stat[ddir], &min, &max, &mean, &dev))
1965                 printf("    clat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1966
1967         if (calc_lat(&td->bw_stat[ddir], &min, &max, &mean, &dev)) {
1968                 double p_of_agg;
1969
1970                 p_of_agg = mean * 100 / (double) rs->agg[ddir];
1971                 printf("    bw (KiB/s) : min=%5lu, max=%5lu, per=%3.2f%%, avg=%5.02f, dev=%5.02f\n", min, max, p_of_agg, mean, dev);
1972         }
1973 }
1974
1975 static void show_thread_status(struct thread_data *td,
1976                                struct group_run_stats *rs)
1977 {
1978         double usr_cpu, sys_cpu;
1979
1980         if (!(td->io_bytes[0] + td->io_bytes[1]) && !td->error)
1981                 return;
1982
1983         printf("Client%d (groupid=%d): err=%2d:\n", td->thread_number, td->groupid, td->error);
1984
1985         show_ddir_status(td, rs, td->ddir);
1986         if (td->io_bytes[td->ddir ^ 1])
1987                 show_ddir_status(td, rs, td->ddir ^ 1);
1988
1989         if (td->runtime[0] + td->runtime[1]) {
1990                 double runt = td->runtime[0] + td->runtime[1];
1991
1992                 usr_cpu = (double) td->usr_time * 100 / runt;
1993                 sys_cpu = (double) td->sys_time * 100 / runt;
1994         } else {
1995                 usr_cpu = 0;
1996                 sys_cpu = 0;
1997         }
1998
1999         printf("  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%lu\n", usr_cpu, sys_cpu, td->ctx);
2000 }
2001
2002 static void check_str_update(struct thread_data *td)
2003 {
2004         char c = run_str[td->thread_number - 1];
2005
2006         if (td->runstate == td->old_runstate)
2007                 return;
2008
2009         switch (td->runstate) {
2010                 case TD_REAPED:
2011                         c = '_';
2012                         break;
2013                 case TD_EXITED:
2014                         c = 'E';
2015                         break;
2016                 case TD_RUNNING:
2017                         if (td_rw(td)) {
2018                                 if (td->sequential)
2019                                         c = 'M';
2020                                 else
2021                                         c = 'm';
2022                         } else if (td_read(td)) {
2023                                 if (td->sequential)
2024                                         c = 'R';
2025                                 else
2026                                         c = 'r';
2027                         } else {
2028                                 if (td->sequential)
2029                                         c = 'W';
2030                                 else
2031                                         c = 'w';
2032                         }
2033                         break;
2034                 case TD_VERIFYING:
2035                         c = 'V';
2036                         break;
2037                 case TD_CREATED:
2038                         c = 'C';
2039                         break;
2040                 case TD_NOT_CREATED:
2041                         c = 'P';
2042                         break;
2043                 default:
2044                         printf("state %d\n", td->runstate);
2045         }
2046
2047         run_str[td->thread_number - 1] = c;
2048         td->old_runstate = td->runstate;
2049 }
2050
2051 static void eta_to_str(char *str, int eta_sec)
2052 {
2053         unsigned int d, h, m, s;
2054         static int always_d, always_h;
2055
2056         d = h = m = s = 0;
2057
2058         s = eta_sec % 60;
2059         eta_sec /= 60;
2060         m = eta_sec % 60;
2061         eta_sec /= 60;
2062         h = eta_sec % 24;
2063         eta_sec /= 24;
2064         d = eta_sec;
2065
2066         if (d || always_d) {
2067                 always_d = 1;
2068                 str += sprintf(str, "%02dd:", d);
2069         }
2070         if (h || always_h) {
2071                 always_h = 1;
2072                 str += sprintf(str, "%02dh:", h);
2073         }
2074
2075         str += sprintf(str, "%02dm:", m);
2076         str += sprintf(str, "%02ds", s);
2077 }
2078
2079 static int thread_eta(struct thread_data *td, unsigned long elapsed)
2080 {
2081         unsigned long long bytes_total, bytes_done;
2082         unsigned int eta_sec = 0;
2083
2084         bytes_total = td->total_io_size;
2085
2086         /*
2087          * if writing, bytes_total will be twice the size. If mixing,
2088          * assume a 50/50 split and thus bytes_total will be 50% larger.
2089          */
2090         if (td->verify) {
2091                 if (td_rw(td))
2092                         bytes_total = bytes_total * 3 / 2;
2093                 else
2094                         bytes_total <<= 1;
2095         }
2096         if (td->zone_size && td->zone_skip)
2097                 bytes_total /= (td->zone_skip / td->zone_size);
2098
2099         if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING) {
2100                 double perc;
2101
2102                 bytes_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE];
2103                 perc = (double) bytes_done / (double) bytes_total;
2104                 if (perc > 1.0)
2105                         perc = 1.0;
2106
2107                 eta_sec = (elapsed * (1.0 / perc)) - elapsed;
2108
2109                 if (td->timeout && eta_sec > (td->timeout - elapsed))
2110                         eta_sec = td->timeout - elapsed;
2111         } else if (td->runstate == TD_NOT_CREATED || td->runstate == TD_CREATED) {
2112                 int t_eta = 0, r_eta = 0;
2113
2114                 /*
2115                  * We can only guess - assume it'll run the full timeout
2116                  * if given, otherwise assume it'll run at the specified rate.
2117                  */
2118                 if (td->timeout)
2119                         t_eta = td->timeout + td->start_delay - elapsed;
2120                 if (td->rate) {
2121                         r_eta = (bytes_total / 1024) / td->rate;
2122                         r_eta += td->start_delay - elapsed;
2123                 }
2124
2125                 if (r_eta && t_eta)
2126                         eta_sec = min(r_eta, t_eta);
2127                 else if (r_eta)
2128                         eta_sec = r_eta;
2129                 else if (t_eta)
2130                         eta_sec = t_eta;
2131                 else
2132                         eta_sec = INT_MAX;
2133         } else {
2134                 /*
2135                  * thread is already done
2136                  */
2137                 eta_sec = 0;
2138         }
2139
2140         return eta_sec;
2141 }
2142
2143 static void print_thread_status(void)
2144 {
2145         unsigned long elapsed = time_since_now(&genesis);
2146         int i, nr_running, t_rate, m_rate, *eta_secs, eta_sec;
2147         char eta_str[32];
2148         double perc = 0.0;
2149
2150         eta_secs = malloc(thread_number * sizeof(int));
2151         memset(eta_secs, 0, thread_number * sizeof(int));
2152
2153         nr_running = t_rate = m_rate = 0;
2154         for (i = 0; i < thread_number; i++) {
2155                 struct thread_data *td = &threads[i];
2156
2157                 if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING){
2158                         nr_running++;
2159                         t_rate += td->rate;
2160                         m_rate += td->ratemin;
2161                 }
2162
2163                 if (elapsed >= 3)
2164                         eta_secs[i] = thread_eta(td, elapsed);
2165                 else
2166                         eta_secs[i] = INT_MAX;
2167
2168                 check_str_update(td);
2169         }
2170
2171         if (exitall_on_terminate)
2172                 eta_sec = INT_MAX;
2173         else
2174                 eta_sec = 0;
2175
2176         for (i = 0; i < thread_number; i++) {
2177                 if (exitall_on_terminate) {
2178                         if (eta_secs[i] < eta_sec)
2179                                 eta_sec = eta_secs[i];
2180                 } else {
2181                         if (eta_secs[i] > eta_sec)
2182                                 eta_sec = eta_secs[i];
2183                 }
2184         }
2185
2186         if (eta_sec != INT_MAX && elapsed) {
2187                 perc = (double) elapsed / (double) (elapsed + eta_sec);
2188                 eta_to_str(eta_str, eta_sec);
2189         }
2190
2191         printf("Threads now running (%d)", nr_running);
2192         if (m_rate || t_rate)
2193                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
2194         if (eta_sec != INT_MAX) {
2195                 perc *= 100.0;
2196                 printf(": [%s] [%3.2f%% done] [eta %s]", run_str, perc,eta_str);
2197         }
2198         printf("\r");
2199         fflush(stdout);
2200         free(eta_secs);
2201 }
2202
2203 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
2204 {
2205         int i;
2206
2207         /*
2208          * reap exited threads (TD_EXITED -> TD_REAPED)
2209          */
2210         for (i = 0; i < thread_number; i++) {
2211                 struct thread_data *td = &threads[i];
2212
2213                 if (td->runstate != TD_EXITED)
2214                         continue;
2215
2216                 td_set_runstate(td, TD_REAPED);
2217
2218                 if (td->use_thread) {
2219                         long ret;
2220
2221                         if (pthread_join(td->thread, (void *) &ret))
2222                                 perror("thread_join");
2223                 } else
2224                         waitpid(td->pid, NULL, 0);
2225
2226                 (*nr_running)--;
2227                 (*m_rate) -= td->ratemin;
2228                 (*t_rate) -= td->rate;
2229         }
2230 }
2231
2232 static void run_threads(void)
2233 {
2234         struct thread_data *td;
2235         unsigned long spent;
2236         int i, todo, nr_running, m_rate, t_rate, nr_started;
2237
2238         printf("Starting %d thread%s\n", thread_number, thread_number > 1 ? "s" : "");
2239         fflush(stdout);
2240
2241         signal(SIGINT, sig_handler);
2242         signal(SIGALRM, sig_handler);
2243
2244         todo = thread_number;
2245         nr_running = 0;
2246         nr_started = 0;
2247         m_rate = t_rate = 0;
2248
2249         for (i = 0; i < thread_number; i++) {
2250                 td = &threads[i];
2251
2252                 run_str[td->thread_number - 1] = 'P';
2253
2254                 init_disk_util(td);
2255
2256                 if (!td->create_serialize)
2257                         continue;
2258
2259                 /*
2260                  * do file setup here so it happens sequentially,
2261                  * we don't want X number of threads getting their
2262                  * client data interspersed on disk
2263                  */
2264                 if (setup_file(td)) {
2265                         td_set_runstate(td, TD_REAPED);
2266                         todo--;
2267                 }
2268         }
2269
2270         gettimeofday(&genesis, NULL);
2271
2272         while (todo) {
2273                 /*
2274                  * create threads (TD_NOT_CREATED -> TD_CREATED)
2275                  */
2276                 for (i = 0; i < thread_number; i++) {
2277                         td = &threads[i];
2278
2279                         if (td->runstate != TD_NOT_CREATED)
2280                                 continue;
2281
2282                         /*
2283                          * never got a chance to start, killed by other
2284                          * thread for some reason
2285                          */
2286                         if (td->terminate) {
2287                                 todo--;
2288                                 continue;
2289                         }
2290
2291                         if (td->start_delay) {
2292                                 spent = mtime_since_now(&genesis);
2293
2294                                 if (td->start_delay * 1000 > spent)
2295                                         continue;
2296                         }
2297
2298                         if (td->stonewall && (nr_started || nr_running))
2299                                 break;
2300
2301                         td_set_runstate(td, TD_CREATED);
2302                         sem_init(&startup_sem, 0, 1);
2303                         todo--;
2304                         nr_started++;
2305
2306                         if (td->use_thread) {
2307                                 if (pthread_create(&td->thread, NULL, thread_main, td)) {
2308                                         perror("thread_create");
2309                                         nr_started--;
2310                                 }
2311                         } else {
2312                                 if (fork())
2313                                         sem_wait(&startup_sem);
2314                                 else {
2315                                         fork_main(shm_id, i);
2316                                         exit(0);
2317                                 }
2318                         }
2319                 }
2320
2321                 /*
2322                  * start created threads (TD_CREATED -> TD_RUNNING)
2323                  */
2324                 for (i = 0; i < thread_number; i++) {
2325                         td = &threads[i];
2326
2327                         if (td->runstate != TD_CREATED)
2328                                 continue;
2329
2330                         td_set_runstate(td, TD_RUNNING);
2331                         nr_running++;
2332                         nr_started--;
2333                         m_rate += td->ratemin;
2334                         t_rate += td->rate;
2335                         sem_post(&td->mutex);
2336                 }
2337
2338                 reap_threads(&nr_running, &t_rate, &m_rate);
2339
2340                 if (todo)
2341                         usleep(100000);
2342         }
2343
2344         while (nr_running) {
2345                 reap_threads(&nr_running, &t_rate, &m_rate);
2346                 usleep(10000);
2347         }
2348
2349         update_io_ticks();
2350 }
2351
2352 static void show_group_stats(struct group_run_stats *rs, int id)
2353 {
2354         printf("\nRun status group %d (all jobs):\n", id);
2355
2356         if (rs->max_run[DDIR_READ])
2357                 printf("   READ: io=%lluMiB, aggrb=%llu, minb=%llu, maxb=%llu, mint=%llumsec, maxt=%llumsec\n", rs->io_mb[0], rs->agg[0], rs->min_bw[0], rs->max_bw[0], rs->min_run[0], rs->max_run[0]);
2358         if (rs->max_run[DDIR_WRITE])
2359                 printf("  WRITE: io=%lluMiB, aggrb=%llu, minb=%llu, maxb=%llu, mint=%llumsec, maxt=%llumsec\n", rs->io_mb[1], rs->agg[1], rs->min_bw[1], rs->max_bw[1], rs->min_run[1], rs->max_run[1]);
2360 }
2361
2362 static void show_disk_util(void)
2363 {
2364         struct disk_util_stat *dus;
2365         struct list_head *entry;
2366         struct disk_util *du;
2367         double util;
2368
2369         printf("\nDisk stats (read/write):\n");
2370
2371         list_for_each(entry, &disk_list) {
2372                 du = list_entry(entry, struct disk_util, list);
2373                 dus = &du->dus;
2374
2375                 util = (double) 100 * du->dus.io_ticks / (double) du->msec;
2376                 if (util > 100.0)
2377                         util = 100.0;
2378
2379                 printf("  %s: ios=%u/%u, merge=%u/%u, ticks=%u/%u, in_queue=%u, util=%3.2f%%\n", du->name, dus->ios[0], dus->ios[1], dus->merges[0], dus->merges[1], dus->ticks[0], dus->ticks[1], dus->time_in_queue, util);
2380         }
2381 }
2382
2383 static void show_run_stats(void)
2384 {
2385         struct group_run_stats *runstats, *rs;
2386         struct thread_data *td;
2387         int i;
2388
2389         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
2390
2391         for (i = 0; i < groupid + 1; i++) {
2392                 rs = &runstats[i];
2393
2394                 memset(rs, 0, sizeof(*rs));
2395                 rs->min_bw[0] = rs->min_run[0] = ~0UL;
2396                 rs->min_bw[1] = rs->min_run[1] = ~0UL;
2397         }
2398
2399         for (i = 0; i < thread_number; i++) {
2400                 unsigned long rbw, wbw;
2401
2402                 td = &threads[i];
2403
2404                 if (td->error) {
2405                         printf("Client%d: %s\n", td->thread_number, td->verror);
2406                         continue;
2407                 }
2408
2409                 rs = &runstats[td->groupid];
2410
2411                 if (td->runtime[0] < rs->min_run[0] || !rs->min_run[0])
2412                         rs->min_run[0] = td->runtime[0];
2413                 if (td->runtime[0] > rs->max_run[0])
2414                         rs->max_run[0] = td->runtime[0];
2415                 if (td->runtime[1] < rs->min_run[1] || !rs->min_run[1])
2416                         rs->min_run[1] = td->runtime[1];
2417                 if (td->runtime[1] > rs->max_run[1])
2418                         rs->max_run[1] = td->runtime[1];
2419
2420                 rbw = wbw = 0;
2421                 if (td->runtime[0])
2422                         rbw = td->io_bytes[0] / td->runtime[0];
2423                 if (td->runtime[1])
2424                         wbw = td->io_bytes[1] / td->runtime[1];
2425
2426                 if (rbw < rs->min_bw[0])
2427                         rs->min_bw[0] = rbw;
2428                 if (wbw < rs->min_bw[1])
2429                         rs->min_bw[1] = wbw;
2430                 if (rbw > rs->max_bw[0])
2431                         rs->max_bw[0] = rbw;
2432                 if (wbw > rs->max_bw[1])
2433                         rs->max_bw[1] = wbw;
2434
2435                 rs->io_mb[0] += td->io_bytes[0] >> 20;
2436                 rs->io_mb[1] += td->io_bytes[1] >> 20;
2437         }
2438
2439         for (i = 0; i < groupid + 1; i++) {
2440                 rs = &runstats[i];
2441
2442                 if (rs->max_run[0])
2443                         rs->agg[0] = (rs->io_mb[0]*1024*1000) / rs->max_run[0];
2444                 if (rs->max_run[1])
2445                         rs->agg[1] = (rs->io_mb[1]*1024*1000) / rs->max_run[1];
2446         }
2447
2448         /*
2449          * don't overwrite last signal output
2450          */
2451         printf("\n");
2452
2453         for (i = 0; i < thread_number; i++) {
2454                 td = &threads[i];
2455                 rs = &runstats[td->groupid];
2456
2457                 show_thread_status(td, rs);
2458         }
2459
2460         for (i = 0; i < groupid + 1; i++)
2461                 show_group_stats(&runstats[i], i);
2462
2463         show_disk_util();
2464 }
2465
2466 int main(int argc, char *argv[])
2467 {
2468         if (parse_options(argc, argv))
2469                 return 1;
2470
2471         if (!thread_number) {
2472                 printf("Nothing to do\n");
2473                 return 1;
2474         }
2475
2476         disk_util_timer_arm();
2477
2478         run_threads();
2479         show_run_stats();
2480
2481         return 0;
2482 }