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