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