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