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