[PATCH] fio: Add option for using crc32 for verifies.
[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 <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/wait.h>
35 #include <sys/ipc.h>
36 #include <sys/shm.h>
37 #include <sys/ioctl.h>
38 #include <sys/mman.h>
39 #include <asm/unistd.h>
40
41 #include "fio.h"
42
43 #define MASK    (4095)
44
45 #define ALIGN(buf)      (char *) (((unsigned long) (buf) + MASK) & ~(MASK))
46
47 int groupid = 0;
48 int thread_number = 0;
49 char run_str[MAX_JOBS + 1];
50 int shm_id = 0;
51
52 /*
53  * thread life cycle
54  */
55 enum {
56         TD_NOT_CREATED = 0,
57         TD_CREATED,
58         TD_RUNNING,
59         TD_VERIFYING,
60         TD_EXITED,
61         TD_REAPED,
62 };
63
64 /*
65  * The io unit
66  */
67 struct io_u {
68         struct iocb iocb;
69         struct timeval start_time;
70         struct timeval issue_time;
71
72         char *buf;
73         unsigned int buflen;
74         unsigned long long offset;
75
76         struct list_head list;
77 };
78
79 #define should_fsync(td)        (td_write(td) && !(td)->odirect)
80
81 static sem_t startup_sem;
82
83 #define TERMINATE_ALL           (-1)
84
85 static void terminate_threads(int groupid)
86 {
87         int i;
88
89         for (i = 0; i < thread_number; i++) {
90                 struct thread_data *td = &threads[i];
91
92                 if (groupid == TERMINATE_ALL || groupid == td->groupid) {
93                         td->terminate = 1;
94                         td->start_delay = 0;
95                 }
96         }
97 }
98
99 static void sig_handler(int sig)
100 {
101         terminate_threads(TERMINATE_ALL);
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                 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 thread_data *td, struct io_stat *is,
260                                    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 *log,
273                            unsigned long val)
274 {
275         if (log->nr_samples == log->max_samples) {
276                 int new_size = sizeof(struct io_sample) * log->max_samples * 2;
277
278                 log->log = realloc(log->log, new_size);
279                 log->max_samples <<= 1;
280         }
281
282         log->log[log->nr_samples].val = val;
283         log->log[log->nr_samples].time = mtime_since_now(&td->start);
284         log->nr_samples++;
285 }
286
287 static void add_clat_sample(struct thread_data *td, unsigned long msec)
288 {
289         add_stat_sample(td, &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, &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, &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(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(int usec)
331 {
332         struct timespec req = { .tv_sec = 0, .tv_nsec = usec * 1000 };
333         struct timespec rem;
334
335         do {
336                 if (usec < 5000) {
337                         __usec_sleep(usec);
338                         break;
339                 }
340                 rem.tv_sec = rem.tv_nsec = 0;
341                 nanosleep(&req, &rem);
342                 if (!rem.tv_nsec)
343                         break;
344
345                 req.tv_nsec = rem.tv_nsec;
346                 usec = rem.tv_nsec * 1000;
347         } while (1);
348 }
349
350 static void rate_throttle(struct thread_data *td, unsigned long time_spent,
351                           unsigned int bytes)
352 {
353         unsigned long usec_cycle;
354
355         if (!td->rate)
356                 return;
357
358         usec_cycle = td->rate_usec_cycle * (bytes / td->min_bs);
359
360         if (time_spent < usec_cycle) {
361                 unsigned long s = usec_cycle - time_spent;
362
363                 td->rate_pending_usleep += s;
364                 if (td->rate_pending_usleep >= 100000) {
365                         usec_sleep(td->rate_pending_usleep);
366                         td->rate_pending_usleep = 0;
367                 }
368         } else {
369                 long overtime = time_spent - usec_cycle;
370
371                 td->rate_pending_usleep -= overtime;
372         }
373 }
374
375 static int check_min_rate(struct thread_data *td, struct timeval *now)
376 {
377         unsigned long spent;
378         unsigned long rate;
379
380         /*
381          * allow a 2 second settle period in the beginning
382          */
383         if (mtime_since(&td->start, now) < 2000)
384                 return 0;
385
386         /*
387          * if rate blocks is set, sample is running
388          */
389         if (td->rate_bytes) {
390                 spent = mtime_since(&td->lastrate, now);
391                 if (spent < td->ratecycle)
392                         return 0;
393
394                 rate = (td->this_io_bytes - td->rate_bytes) / spent;
395                 if (rate < td->ratemin) {
396                         printf("Client%d: min rate %d not met, got %ldKiB/sec\n", td->thread_number, td->ratemin, rate);
397                         if (rate_quit)
398                                 terminate_threads(td->groupid);
399                         return 1;
400                 }
401         }
402
403         td->rate_bytes = td->this_io_bytes;
404         memcpy(&td->lastrate, now, sizeof(*now));
405         return 0;
406 }
407
408 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
409 {
410         if (!td->timeout)
411                 return 0;
412         if (mtime_since(&td->start, t) >= td->timeout * 1000)
413                 return 1;
414
415         return 0;
416 }
417
418 static void fill_random_bytes(struct thread_data *td,
419                               unsigned char *p, unsigned int len)
420 {
421         unsigned int todo;
422         double r;
423
424         while (len) {
425                 drand48_r(&td->verify_state, &r);
426
427                 /*
428                  * lrand48_r seems to be broken and only fill the bottom
429                  * 32-bits, even on 64-bit archs with 64-bit longs
430                  */
431                 todo = sizeof(r);
432                 if (todo > len)
433                         todo = len;
434
435                 memcpy(p, &r, todo);
436
437                 len -= todo;
438                 p += todo;
439         }
440 }
441
442 static void hexdump(void *buffer, int len)
443 {
444         unsigned char *p = buffer;
445         int i;
446
447         for (i = 0; i < len; i++)
448                 printf("%02x", p[i]);
449         printf("\n");
450 }
451
452 static int verify_io_u_crc32(struct verify_header *hdr, struct io_u *io_u)
453 {
454         unsigned char *p = (unsigned char *) io_u->buf;
455         unsigned long c;
456
457         p += sizeof(*hdr);
458         c = crc32(p, hdr->len - sizeof(*hdr));
459
460         return c != hdr->crc32;
461 }
462
463 static int verify_io_u_md5(struct verify_header *hdr, struct io_u *io_u)
464 {
465         unsigned char *p = (unsigned char *) io_u->buf;
466         struct md5_ctx md5_ctx;
467         int ret;
468
469         memset(&md5_ctx, 0, sizeof(md5_ctx));
470         p += sizeof(*hdr);
471         md5_update(&md5_ctx, p, hdr->len - sizeof(*hdr));
472
473         ret = memcmp(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
474         if (ret) {
475                 hexdump(hdr->md5_digest, sizeof(hdr->md5_digest));
476                 hexdump(md5_ctx.hash, sizeof(md5_ctx.hash));
477         }
478
479         return ret;
480 }
481
482 static int verify_io_u(struct io_u *io_u)
483 {
484         struct verify_header *hdr = (struct verify_header *) io_u->buf;
485         int ret;
486
487         if (hdr->fio_magic != FIO_HDR_MAGIC)
488                 return 1;
489
490         if (hdr->verify_type == VERIFY_MD5)
491                 ret = verify_io_u_md5(hdr, io_u);
492         else if (hdr->verify_type == VERIFY_CRC32)
493                 ret = verify_io_u_crc32(hdr, io_u);
494         else {
495                 fprintf(stderr, "Bad verify type %d\n", hdr->verify_type);
496                 ret = 1;
497         }
498
499         return ret;
500 }
501
502 static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
503 {
504         hdr->crc32 = crc32(p, len);
505 }
506
507 static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
508 {
509         struct md5_ctx md5_ctx;
510
511         memset(&md5_ctx, 0, sizeof(md5_ctx));
512         md5_update(&md5_ctx, p, len);
513         memcpy(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
514 }
515
516 /*
517  * fill body of io_u->buf with random data and add a header with the
518  * (eg) sha1sum of that data.
519  */
520 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
521 {
522         unsigned char *p = (unsigned char *) io_u->buf;
523         struct verify_header hdr;
524
525         hdr.fio_magic = FIO_HDR_MAGIC;
526         hdr.len = io_u->buflen;
527         p += sizeof(hdr);
528         fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
529
530         if (td->verify == VERIFY_MD5) {
531                 fill_md5(&hdr, p, io_u->buflen - sizeof(hdr));
532                 hdr.verify_type = VERIFY_MD5;
533         } else {
534                 fill_crc32(&hdr, p, io_u->buflen - sizeof(hdr));
535                 hdr.verify_type = VERIFY_CRC32;
536         }
537
538         memcpy(io_u->buf, &hdr, sizeof(hdr));
539 }
540
541 static void put_io_u(struct thread_data *td, struct io_u *io_u)
542 {
543         list_del(&io_u->list);
544         list_add(&io_u->list, &td->io_u_freelist);
545         td->cur_depth--;
546 }
547
548 #define queue_full(td)  (list_empty(&(td)->io_u_freelist))
549
550 static struct io_u *__get_io_u(struct thread_data *td)
551 {
552         struct io_u *io_u;
553
554         if (queue_full(td))
555                 return NULL;
556
557         io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
558         list_del(&io_u->list);
559         list_add(&io_u->list, &td->io_u_busylist);
560         td->cur_depth++;
561         return io_u;
562 }
563
564 static struct io_u *get_io_u(struct thread_data *td)
565 {
566         struct io_u *io_u;
567
568         io_u = __get_io_u(td);
569         if (!io_u)
570                 return NULL;
571
572         if (get_next_offset(td, &io_u->offset)) {
573                 put_io_u(td, io_u);
574                 return NULL;
575         }
576
577         io_u->buflen = get_next_buflen(td);
578         if (!io_u->buflen) {
579                 put_io_u(td, io_u);
580                 return NULL;
581         }
582
583         if (io_u->buflen + io_u->offset > td->file_size)
584                 io_u->buflen = td->file_size - io_u->offset;
585
586         if (!td->sequential)
587                 mark_random_map(td, io_u);
588
589         td->last_bytes += io_u->buflen;
590
591         if (td->verify != VERIFY_NONE)
592                 populate_io_u(td, io_u);
593
594         if (td->use_aio) {
595                 if (td_read(td))
596                         io_prep_pread(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
597                 else
598                         io_prep_pwrite(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
599         }
600
601         gettimeofday(&io_u->start_time, NULL);
602         return io_u;
603 }
604
605 static inline void td_set_runstate(struct thread_data *td, int runstate)
606 {
607         td->old_runstate = td->runstate;
608         td->runstate = runstate;
609 }
610
611 static int get_next_verify(struct thread_data *td,
612                            unsigned long long *offset, unsigned int *len)
613 {
614         struct io_piece *ipo;
615
616         if (list_empty(&td->io_hist_list))
617                 return 1;
618
619         ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
620         list_del(&ipo->list);
621
622         *offset = ipo->offset;
623         *len = ipo->len;
624         free(ipo);
625         return 0;
626 }
627
628 static void prune_io_piece_log(struct thread_data *td)
629 {
630         struct io_piece *ipo;
631
632         while (!list_empty(&td->io_hist_list)) {
633                 ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
634
635                 list_del(&ipo->list);
636                 free(ipo);
637         }
638 }
639
640 /*
641  * log a succesful write, so we can unwind the log for verify
642  */
643 static void log_io_piece(struct thread_data *td, struct io_u *io_u)
644 {
645         struct io_piece *ipo = malloc(sizeof(struct io_piece));
646         struct list_head *entry;
647
648         INIT_LIST_HEAD(&ipo->list);
649         ipo->offset = io_u->offset;
650         ipo->len = io_u->buflen;
651
652         /*
653          * for random io where the writes extend the file, it will typically
654          * be laid out with the block scattered as written. it's faster to
655          * read them in in that order again, so don't sort
656          */
657         if (td->sequential || !td->overwrite) {
658                 list_add_tail(&ipo->list, &td->io_hist_list);
659                 return;
660         }
661
662         /*
663          * for random io, sort the list so verify will run faster
664          */
665         entry = &td->io_hist_list;
666         while ((entry = entry->prev) != &td->io_hist_list) {
667                 struct io_piece *__ipo = list_entry(entry, struct io_piece, list);
668
669                 if (__ipo->offset < ipo->offset)
670                         break;
671         }
672
673         list_add(&ipo->list, entry);
674 }
675
676 static void do_sync_verify(struct thread_data *td)
677 {
678         struct timeval t;
679         struct io_u *io_u = NULL;
680         int ret;
681
682         td_set_runstate(td, TD_VERIFYING);
683
684         io_u = __get_io_u(td);
685
686         if (!td->odirect) {
687                 if (!td->use_mmap) {
688                         if (fadvise(td->fd, td->file_offset, td->io_size, POSIX_FADV_DONTNEED) < 0) {
689                                 td->error = errno;
690                                 goto out;
691                         }
692                 } else {
693                         if (madvise(td->mmap, td->io_size, MADV_DONTNEED)) {
694                                 td->error = errno;
695                                 goto out;
696                         }
697                 }
698         }
699
700         do {
701                 if (td->terminate)
702                         break;
703
704                 gettimeofday(&t, NULL);
705                 if (runtime_exceeded(td, &t))
706                         break;
707
708                 if (get_next_verify(td, &io_u->offset, &io_u->buflen))
709                         break;
710
711                 if (td->cur_off != io_u->offset) {
712                         if (lseek(td->fd, io_u->offset, SEEK_SET) == -1) {
713                                 td->error = errno;
714                                 break;
715                         }
716                 }
717
718                 ret = read(td->fd, io_u->buf, io_u->buflen);
719                 if (ret < (int) io_u->buflen) {
720                         if (ret == -1) {
721                                 td->error = errno;
722                                 break;
723                         } else if (!ret)
724                                 break;
725                         else
726                                 io_u->buflen = ret;
727                 }
728
729                 if (verify_io_u(io_u))
730                         break;
731
732                 td->cur_off = io_u->offset + io_u->buflen;
733         } while (1);
734
735 out:
736         td_set_runstate(td, TD_RUNNING);
737         put_io_u(td, io_u);
738 }
739
740 static int __do_sync_mmap(struct thread_data *td, struct io_u *io_u)
741 {
742         unsigned long long real_off = io_u->offset - td->file_offset;
743
744         if (td_read(td))
745                 memcpy(io_u->buf, td->mmap + real_off, io_u->buflen);
746         else
747                 memcpy(td->mmap + real_off, io_u->buf, io_u->buflen);
748         
749         /*
750          * not really direct, but should drop the pages from the cache
751          */
752         if (td->odirect) {
753                 msync(td->mmap + real_off, io_u->buflen, MS_SYNC);
754                 madvise(td->mmap + real_off, io_u->buflen,  MADV_DONTNEED);
755         }
756
757         return io_u->buflen;
758 }
759
760 static int __do_sync_rw(struct thread_data *td, struct io_u *io_u)
761 {
762         if (td->cur_off != io_u->offset) {
763                 if (lseek(td->fd, io_u->offset, SEEK_SET) == -1) {
764                         td->error = errno;
765                         return 1;
766                 }
767         }
768
769         if (td_read(td))
770                 return read(td->fd, io_u->buf, io_u->buflen);
771         else
772                 return write(td->fd, io_u->buf, io_u->buflen);
773 }
774
775 static void sync_td(struct thread_data *td)
776 {
777         if (!td->use_mmap)
778                 fsync(td->fd);
779         else
780                 msync(td->mmap, td->file_size, MS_SYNC);
781 }
782
783 static void do_sync_io(struct thread_data *td)
784 {
785         unsigned long msec, usec;
786         struct io_u *io_u = NULL;
787         struct timeval e;
788
789         while (td->this_io_bytes < td->io_size) {
790                 int ret;
791
792                 if (td->terminate)
793                         break;
794
795                 io_u = get_io_u(td);
796                 if (!io_u)
797                         break;
798
799                 if (!td->use_mmap)
800                         ret = __do_sync_rw(td, io_u);
801                 else
802                         ret = __do_sync_mmap(td, io_u);
803
804                 if (ret < (int) io_u->buflen) {
805                         if (ret == -1)
806                                 td->error = errno;
807                         break;
808                 }
809
810                 if (td_write(td))
811                         log_io_piece(td, io_u);
812
813                 td->io_blocks++;
814                 td->io_bytes += io_u->buflen;
815                 td->this_io_bytes += io_u->buflen;
816                 td->cur_off = io_u->offset + io_u->buflen;
817
818                 gettimeofday(&e, NULL);
819
820                 usec = utime_since(&io_u->start_time, &e);
821
822                 rate_throttle(td, usec, io_u->buflen);
823
824                 if (check_min_rate(td, &e)) {
825                         td->error = ENODATA;
826                         break;
827                 }
828
829                 msec = usec / 1000;
830                 add_clat_sample(td, msec);
831                 add_bw_sample(td);
832
833                 if (runtime_exceeded(td, &e))
834                         break;
835
836                 put_io_u(td, io_u);
837                 io_u = NULL;
838
839                 if (td->thinktime)
840                         usec_sleep(td->thinktime);
841
842                 if (should_fsync(td) && td->fsync_blocks &&
843                     (td->io_blocks % td->fsync_blocks) == 0)
844                         sync_td(td);
845         }
846
847         if (io_u)
848                 put_io_u(td, io_u);
849
850         if (should_fsync(td))
851                 sync_td(td);
852 }
853
854 static int io_u_getevents(struct thread_data *td, int min, int max,
855                           struct timespec *t)
856 {
857         int r;
858
859         do {
860                 r = io_getevents(td->aio_ctx, min, max, td->aio_events, t);
861                 if (r != -EAGAIN && r != -EINTR)
862                         break;
863         } while (1);
864
865         return r;
866 }
867
868 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
869 {
870         struct iocb *iocb = &io_u->iocb;
871         int ret;
872
873         do {
874                 ret = io_submit(td->aio_ctx, 1, &iocb);
875                 if (ret == 1)
876                         return 0;
877                 else if (ret == -EAGAIN)
878                         usleep(100);
879                 else if (ret == -EINTR)
880                         continue;
881                 else
882                         break;
883         } while (1);
884
885         return ret;
886 }
887
888 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
889 #define ev_to_iou(ev)   (struct io_u *) ((unsigned long) (ev)->obj)
890
891 static int ios_completed(struct thread_data *td, int nr)
892 {
893         unsigned long msec;
894         struct io_u *io_u;
895         struct timeval e;
896         int i, bytes_done;
897
898         gettimeofday(&e, NULL);
899
900         for (i = 0, bytes_done = 0; i < nr; i++) {
901                 io_u = ev_to_iou(td->aio_events + i);
902
903                 td->io_blocks++;
904                 td->io_bytes += io_u->buflen;
905                 td->this_io_bytes += io_u->buflen;
906
907                 msec = mtime_since(&io_u->issue_time, &e);
908
909                 add_clat_sample(td, msec);
910                 add_bw_sample(td);
911
912                 if (td_write(td))
913                         log_io_piece(td, io_u);
914
915                 bytes_done += io_u->buflen;
916                 put_io_u(td, io_u);
917         }
918
919         return bytes_done;
920 }
921
922 static void cleanup_pending_aio(struct thread_data *td)
923 {
924         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
925         struct list_head *entry, *n;
926         struct io_u *io_u;
927         int r;
928
929         /*
930          * get immediately available events, if any
931          */
932         r = io_u_getevents(td, 0, td->cur_depth, &ts);
933         if (r > 0)
934                 ios_completed(td, r);
935
936         /*
937          * now cancel remaining active events
938          */
939         list_for_each_safe(entry, n, &td->io_u_busylist) {
940                 io_u = list_entry(entry, struct io_u, list);
941
942                 r = io_cancel(td->aio_ctx, &io_u->iocb, td->aio_events);
943                 if (!r)
944                         put_io_u(td, io_u);
945         }
946
947         if (td->cur_depth) {
948                 r = io_u_getevents(td, td->cur_depth, td->cur_depth, NULL);
949                 if (r > 0)
950                         ios_completed(td, r);
951         }
952 }
953
954 static int async_do_verify(struct thread_data *td, struct io_u **io_u)
955 {
956         struct io_u *v_io_u = *io_u;
957         int ret = 0;
958
959         if (v_io_u) {
960                 ret = verify_io_u(v_io_u);
961                 put_io_u(td, v_io_u);
962                 *io_u = NULL;
963         }
964
965         return ret;
966 }
967
968 static void do_async_verify(struct thread_data *td)
969 {
970         struct timeval t;
971         struct io_u *io_u, *v_io_u = NULL;
972         int ret;
973
974         td_set_runstate(td, TD_VERIFYING);
975
976         do {
977                 if (td->terminate)
978                         break;
979
980                 gettimeofday(&t, NULL);
981                 if (runtime_exceeded(td, &t))
982                         break;
983
984                 io_u = __get_io_u(td);
985                 if (!io_u)
986                         break;
987
988                 if (get_next_verify(td, &io_u->offset, &io_u->buflen)) {
989                         put_io_u(td, io_u);
990                         break;
991                 }
992
993                 io_prep_pread(&io_u->iocb, td->fd, io_u->buf, io_u->buflen, io_u->offset);
994                 ret = io_u_queue(td, io_u);
995                 if (ret) {
996                         put_io_u(td, io_u);
997                         td->error = ret;
998                         break;
999                 }
1000
1001                 /*
1002                  * we have one pending to verify, do that while the next
1003                  * we are doing io on the next one
1004                  */
1005                 if (async_do_verify(td, &v_io_u))
1006                         break;
1007
1008                 ret = io_u_getevents(td, 1, 1, NULL);
1009                 if (ret != 1) {
1010                         if (ret < 0)
1011                                 td->error = ret;
1012                         break;
1013                 }
1014
1015                 v_io_u = ev_to_iou(td->aio_events);
1016
1017                 td->cur_off = v_io_u->offset + v_io_u->buflen;
1018
1019                 /*
1020                  * if we can't submit more io, we need to verify now
1021                  */
1022                 if (queue_full(td) && async_do_verify(td, &v_io_u))
1023                         break;
1024
1025         } while (1);
1026
1027         async_do_verify(td, &v_io_u);
1028
1029         if (td->cur_depth)
1030                 cleanup_pending_aio(td);
1031
1032         td_set_runstate(td, TD_RUNNING);
1033 }
1034
1035 static void do_async_io(struct thread_data *td)
1036 {
1037         struct timeval s, e;
1038         unsigned long usec;
1039
1040         while (td->this_io_bytes < td->io_size) {
1041                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
1042                 struct timespec *timeout;
1043                 int ret, min_evts = 0;
1044                 struct io_u *io_u;
1045                 unsigned int bytes_done;
1046
1047                 if (td->terminate)
1048                         break;
1049
1050                 io_u = get_io_u(td);
1051                 if (!io_u)
1052                         break;
1053
1054                 memcpy(&s, &io_u->start_time, sizeof(s));
1055
1056                 ret = io_u_queue(td, io_u);
1057                 if (ret) {
1058                         put_io_u(td, io_u);
1059                         td->error = ret;
1060                         break;
1061                 }
1062
1063                 gettimeofday(&io_u->issue_time, NULL);
1064                 add_slat_sample(td, mtime_since(&io_u->start_time, &io_u->issue_time));
1065                 if (td->cur_depth < td->aio_depth) {
1066                         timeout = &ts;
1067                         min_evts = 0;
1068                 } else {
1069                         timeout = NULL;
1070                         min_evts = 1;
1071                 }
1072
1073                 ret = io_u_getevents(td, min_evts, td->cur_depth, timeout);
1074                 if (ret < 0) {
1075                         td->error = ret;
1076                         break;
1077                 } else if (!ret)
1078                         continue;
1079
1080                 bytes_done = ios_completed(td, ret);
1081
1082                 /*
1083                  * the rate is batched for now, it should work for batches
1084                  * of completions except the very first one which may look
1085                  * a little bursty
1086                  */
1087                 gettimeofday(&e, NULL);
1088                 usec = utime_since(&s, &e);
1089
1090                 rate_throttle(td, usec, bytes_done);
1091
1092                 if (check_min_rate(td, &e)) {
1093                         td->error = ENODATA;
1094                         break;
1095                 }
1096
1097                 if (runtime_exceeded(td, &e))
1098                         break;
1099
1100                 if (td->thinktime)
1101                         usec_sleep(td->thinktime);
1102
1103                 if (should_fsync(td) && td->fsync_blocks &&
1104                     (td->io_blocks % td->fsync_blocks) == 0)
1105                         fsync(td->fd);
1106         }
1107
1108         if (td->cur_depth)
1109                 cleanup_pending_aio(td);
1110
1111         if (should_fsync(td))
1112                 fsync(td->fd);
1113 }
1114
1115 static void cleanup_aio(struct thread_data *td)
1116 {
1117         io_destroy(td->aio_ctx);
1118
1119         if (td->aio_events)
1120                 free(td->aio_events);
1121 }
1122
1123 static int init_aio(struct thread_data *td)
1124 {
1125         if (io_queue_init(td->aio_depth, &td->aio_ctx)) {
1126                 td->error = errno;
1127                 return 1;
1128         }
1129
1130         td->aio_events = malloc(td->aio_depth * sizeof(struct io_event));
1131         return 0;
1132 }
1133
1134 static void cleanup_io_u(struct thread_data *td)
1135 {
1136         struct list_head *entry, *n;
1137         struct io_u *io_u;
1138
1139         list_for_each_safe(entry, n, &td->io_u_freelist) {
1140                 io_u = list_entry(entry, struct io_u, list);
1141
1142                 list_del(&io_u->list);
1143                 free(io_u);
1144         }
1145
1146         if (td->mem_type == MEM_MALLOC)
1147                 free(td->orig_buffer);
1148         else if (td->mem_type == MEM_SHM) {
1149                 struct shmid_ds sbuf;
1150
1151                 shmdt(td->orig_buffer);
1152                 shmctl(td->shm_id, IPC_RMID, &sbuf);
1153         } else if (td->mem_type == MEM_MMAP)
1154                 munmap(td->orig_buffer, td->orig_buffer_size);
1155         else
1156                 fprintf(stderr, "Bad memory type %d\n", td->mem_type);
1157
1158         td->orig_buffer = NULL;
1159 }
1160
1161 static int init_io_u(struct thread_data *td)
1162 {
1163         struct io_u *io_u;
1164         int i, max_units;
1165         char *p;
1166
1167         if (!td->use_aio)
1168                 max_units = 1;
1169         else
1170                 max_units = td->aio_depth;
1171
1172         td->orig_buffer_size = td->max_bs * max_units + MASK;
1173
1174         if (td->mem_type == MEM_MALLOC)
1175                 td->orig_buffer = malloc(td->orig_buffer_size);
1176         else if (td->mem_type == MEM_SHM) {
1177                 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
1178                 if (td->shm_id < 0) {
1179                         td->error = errno;
1180                         perror("shmget");
1181                         return 1;
1182                 }
1183
1184                 td->orig_buffer = shmat(td->shm_id, NULL, 0);
1185                 if (td->orig_buffer == (void *) -1) {
1186                         td->error = errno;
1187                         perror("shmat");
1188                         td->orig_buffer = NULL;
1189                         return 1;
1190                 }
1191         } else if (td->mem_type == MEM_MMAP) {
1192                 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
1193                 if (td->orig_buffer == MAP_FAILED) {
1194                         td->error = errno;
1195                         perror("mmap");
1196                         td->orig_buffer = NULL;
1197                         return 1;
1198                 }
1199         }
1200
1201         INIT_LIST_HEAD(&td->io_u_freelist);
1202         INIT_LIST_HEAD(&td->io_u_busylist);
1203         INIT_LIST_HEAD(&td->io_hist_list);
1204
1205         p = ALIGN(td->orig_buffer);
1206         for (i = 0; i < max_units; i++) {
1207                 io_u = malloc(sizeof(*io_u));
1208                 memset(io_u, 0, sizeof(*io_u));
1209                 INIT_LIST_HEAD(&io_u->list);
1210
1211                 io_u->buf = p + td->max_bs * i;
1212                 list_add(&io_u->list, &td->io_u_freelist);
1213         }
1214
1215         return 0;
1216 }
1217
1218 static int create_file(struct thread_data *td)
1219 {
1220         unsigned long long left;
1221         unsigned int bs;
1222         char *b;
1223         int r;
1224
1225         /*
1226          * unless specifically asked for overwrite, let normal io extend it
1227          */
1228         if (td_write(td) && !td->overwrite)
1229                 return 0;
1230
1231         if (!td->file_size) {
1232                 fprintf(stderr, "Need size for create\n");
1233                 td->error = EINVAL;
1234                 return 1;
1235         }
1236
1237         printf("Client%d: Laying out IO file\n", td->thread_number);
1238
1239         td->fd = open(td->file_name, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1240         if (td->fd < 0) {
1241                 td->error = errno;
1242                 return 1;
1243         }
1244
1245         if (ftruncate(td->fd, td->file_size) == -1) {
1246                 td->error = errno;
1247                 return 1;
1248         }
1249
1250         td->io_size = td->file_size;
1251         b = malloc(td->max_bs);
1252         memset(b, 0, td->max_bs);
1253
1254         left = td->file_size;
1255         while (left) {
1256                 bs = td->max_bs;
1257                 if (bs > left)
1258                         bs = left;
1259
1260                 r = write(td->fd, b, bs);
1261
1262                 if (r == (int) bs) {
1263                         left -= bs;
1264                         continue;
1265                 } else {
1266                         if (r < 0)
1267                                 td->error = errno;
1268                         else
1269                                 td->error = EIO;
1270
1271                         break;
1272                 }
1273         }
1274
1275         if (td->create_fsync)
1276                 fsync(td->fd);
1277
1278         close(td->fd);
1279         td->fd = -1;
1280         free(b);
1281         return 0;
1282 }
1283
1284 static int file_exists(struct thread_data *td)
1285 {
1286         struct stat st;
1287
1288         if (stat(td->file_name, &st) != -1)
1289                 return 1;
1290
1291         return errno != ENOENT;
1292 }
1293
1294 static int file_size(struct thread_data *td)
1295 {
1296         struct stat st;
1297
1298         if (fstat(td->fd, &st) == -1) {
1299                 td->error = errno;
1300                 return 1;
1301         }
1302
1303         if (td_read(td)) {
1304                 if (!td->file_size || td->file_size > st.st_size)
1305                         td->file_size = st.st_size;
1306         } else {
1307                 if (!td->file_size)
1308                         td->file_size = 1024 * 1024 * 1024;
1309         }
1310
1311         return 0;
1312 }
1313
1314 static int bdev_size(struct thread_data *td)
1315 {
1316         size_t bytes;
1317
1318         if (ioctl(td->fd, BLKGETSIZE64, &bytes) < 0) {
1319                 td->error = errno;
1320                 return 1;
1321         }
1322
1323         if (!td->file_size || (td->file_size > bytes))
1324                 td->file_size = bytes;
1325
1326         return 0;
1327 }
1328
1329 static int get_file_size(struct thread_data *td)
1330 {
1331         int ret;
1332
1333         if (td->filetype == FIO_TYPE_FILE)
1334                 ret = file_size(td);
1335         else
1336                 ret = bdev_size(td);
1337
1338         if (ret)
1339                 return ret;
1340
1341         if (td->file_offset > td->file_size) {
1342                 fprintf(stderr, "Client%d: offset larger than length\n", td->thread_number);
1343                 return 1;
1344         }
1345
1346         td->io_size = td->file_size - td->file_offset;
1347         if (td->io_size == 0) {
1348                 fprintf(stderr, "Client%d: no io blocks\n", td->thread_number);
1349                 td->error = EINVAL;
1350                 return 1;
1351         }
1352
1353         return 0;
1354 }
1355
1356 static int setup_file_mmap(struct thread_data *td)
1357 {
1358         int flags;
1359
1360         if (td_read(td))
1361                 flags = PROT_READ;
1362         else {
1363                 flags = PROT_WRITE;
1364
1365                 if (td->verify != VERIFY_NONE)
1366                         flags |= PROT_READ;
1367         }
1368
1369         td->mmap = mmap(NULL, td->file_size, flags, MAP_SHARED, td->fd, td->file_offset);
1370         if (td->mmap == MAP_FAILED) {
1371                 td->mmap = NULL;
1372                 td->error = errno;
1373                 return 1;
1374         }
1375
1376         if (td->invalidate_cache) {
1377                 if (madvise(td->mmap, td->file_size, MADV_DONTNEED) < 0) {
1378                         td->error = errno;
1379                         return 1;
1380                 }
1381         }
1382
1383         if (td->sequential) {
1384                 if (madvise(td->mmap, td->file_size, MADV_SEQUENTIAL) < 0) {
1385                         td->error = errno;
1386                         return 1;
1387                 }
1388         } else {
1389                 if (madvise(td->mmap, td->file_size, MADV_RANDOM) < 0) {
1390                         td->error = errno;
1391                         return 1;
1392                 }
1393         }
1394
1395         return 0;
1396 }
1397
1398 static int setup_file_plain(struct thread_data *td)
1399 {
1400         if (td->invalidate_cache) {
1401                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_DONTNEED) < 0) {
1402                         td->error = errno;
1403                         return 1;
1404                 }
1405         }
1406
1407         if (td->sequential) {
1408                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_SEQUENTIAL) < 0) {
1409                         td->error = errno;
1410                         return 1;
1411                 }
1412         } else {
1413                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_RANDOM) < 0) {
1414                         td->error = errno;
1415                         return 1;
1416                 }
1417         }
1418
1419         return 0;
1420 }
1421
1422 static int setup_file(struct thread_data *td)
1423 {
1424         int flags = 0;
1425
1426         if (!file_exists(td)) {
1427                 if (!td->create_file) {
1428                         td->error = ENOENT;
1429                         return 1;
1430                 }
1431                 if (create_file(td))
1432                         return 1;
1433         }
1434
1435         if (td->odirect)
1436                 flags |= O_DIRECT;
1437
1438         if (td_read(td))
1439                 td->fd = open(td->file_name, flags | O_RDONLY);
1440         else {
1441                 if (!td->overwrite)
1442                         flags |= O_TRUNC;
1443                 if (td->sync_io)
1444                         flags |= O_SYNC;
1445
1446                 flags |= O_RDWR;
1447
1448                 td->fd = open(td->file_name, flags | O_CREAT, 0600);
1449         }
1450
1451         if (td->fd == -1) {
1452                 td->error = errno;
1453                 return 1;
1454         }
1455
1456         if (get_file_size(td))
1457                 return 1;
1458
1459         if (td_write(td) && ftruncate(td->fd, td->file_size) == -1) {
1460                 td->error = errno;
1461                 return 1;
1462         }
1463
1464         if (!td->use_mmap)
1465                 return setup_file_plain(td);
1466         else
1467                 return setup_file_mmap(td);
1468 }
1469
1470 static void clear_io_state(struct thread_data *td)
1471 {
1472         if (!td->use_aio)
1473                 lseek(td->fd, SEEK_SET, 0);
1474
1475         td->cur_off = 0;
1476         td->last_bytes = 0;
1477         td->stat_io_bytes = 0;
1478         td->this_io_bytes = 0;
1479
1480         if (td->file_map)
1481                 memset(td->file_map, 0, td->num_maps * sizeof(long));
1482 }
1483
1484 static void update_rusage_stat(struct thread_data *td)
1485 {
1486         if (!td->runtime)
1487                 return;
1488
1489         getrusage(RUSAGE_SELF, &td->ru_end);
1490
1491         td->usr_time += mtime_since(&td->ru_start.ru_utime, &td->ru_end.ru_utime);
1492         td->sys_time += mtime_since(&td->ru_start.ru_stime, &td->ru_end.ru_stime);
1493         td->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
1494
1495         
1496         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
1497 }
1498
1499 static void *thread_main(void *data)
1500 {
1501         struct thread_data *td = data;
1502         int ret = 1;
1503
1504         setsid();
1505         td->pid = getpid();
1506
1507         if (init_io_u(td))
1508                 goto err;
1509
1510         if (sched_setaffinity(td->pid, sizeof(td->cpumask), &td->cpumask) == -1) {
1511                 td->error = errno;
1512                 goto err;
1513         }
1514
1515         if (td->use_aio && init_aio(td))
1516                 goto err;
1517
1518         if (td->ioprio) {
1519                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1520                         td->error = errno;
1521                         goto err;
1522                 }
1523         }
1524
1525         sem_post(&startup_sem);
1526         sem_wait(&td->mutex);
1527
1528         if (!td->create_serialize && setup_file(td))
1529                 goto err;
1530
1531         if (init_random_state(td))
1532                 goto err;
1533
1534         while (td->loops--) {
1535                 getrusage(RUSAGE_SELF, &td->ru_start);
1536                 gettimeofday(&td->start, NULL);
1537                 memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1538
1539                 if (td->ratemin)
1540                         memcpy(&td->lastrate, &td->stat_sample_time, sizeof(td->lastrate));
1541
1542                 clear_io_state(td);
1543                 prune_io_piece_log(td);
1544
1545                 if (!td->use_aio)
1546                         do_sync_io(td);
1547                 else
1548                         do_async_io(td);
1549
1550                 if (td->error)
1551                         break;
1552
1553                 td->runtime += mtime_since_now(&td->start);
1554                 update_rusage_stat(td);
1555
1556                 if (td->verify == VERIFY_NONE)
1557                         continue;
1558
1559                 clear_io_state(td);
1560
1561                 if (!td->use_aio)
1562                         do_sync_verify(td);
1563                 else
1564                         do_async_verify(td);
1565
1566                 if (td->error)
1567                         break;
1568         }
1569
1570         ret = 0;
1571
1572         if (td->bw_log)
1573                 finish_log(td, td->bw_log, "bw");
1574         if (td->lat_log)
1575                 finish_log(td, td->lat_log, "lat");
1576
1577         if (exitall_on_terminate)
1578                 terminate_threads(td->groupid);
1579
1580 err:
1581         if (td->fd != -1) {
1582                 close(td->fd);
1583                 td->fd = -1;
1584         }
1585         if (td->mmap)
1586                 munmap(td->mmap, td->file_size);
1587         if (td->use_aio)
1588                 cleanup_aio(td);
1589         cleanup_io_u(td);
1590         if (ret) {
1591                 sem_post(&startup_sem);
1592                 sem_wait(&td->mutex);
1593         }
1594         td_set_runstate(td, TD_EXITED);
1595         return NULL;
1596
1597 }
1598
1599 static void *fork_main(int shm_id, int offset)
1600 {
1601         struct thread_data *td;
1602         void *data;
1603
1604         data = shmat(shm_id, NULL, 0);
1605         if (data == (void *) -1) {
1606                 perror("shmat");
1607                 return NULL;
1608         }
1609
1610         td = data + offset * sizeof(struct thread_data);
1611         thread_main(td);
1612         shmdt(data);
1613         return NULL;
1614 }
1615
1616 static int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
1617                     double *mean, double *dev)
1618 {
1619         double n;
1620
1621         if (is->samples == 0)
1622                 return 0;
1623
1624         *min = is->min_val;
1625         *max = is->max_val;
1626
1627         n = (double) is->samples;
1628         *mean = (double) is->val / n;
1629         *dev = sqrt(((double) is->val_sq - (*mean * *mean) / n) / (n - 1));
1630         return 1;
1631 }
1632
1633 static void show_thread_status(struct thread_data *td,
1634                                struct group_run_stats *rs)
1635 {
1636         int prio, prio_class;
1637         unsigned long min, max, bw = 0;
1638         double mean, dev, usr_cpu, sys_cpu;
1639
1640         if (!td->io_bytes && !td->error)
1641                 return;
1642
1643         if (td->runtime)
1644                 bw = td->io_bytes / td->runtime;
1645
1646         prio = td->ioprio & 0xff;
1647         prio_class = td->ioprio >> IOPRIO_CLASS_SHIFT;
1648
1649         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);
1650
1651         if (calc_lat(&td->slat_stat, &min, &max, &mean, &dev))
1652                 printf("  slat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1653         if (calc_lat(&td->clat_stat, &min, &max, &mean, &dev))
1654                 printf("  clat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1655         if (calc_lat(&td->bw_stat, &min, &max, &mean, &dev)) {
1656                 double p_of_agg;
1657
1658                 p_of_agg = mean * 100 / (double) rs->agg[td->ddir];
1659                 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);
1660         }
1661
1662         if (td->runtime) {
1663                 usr_cpu = (double) td->usr_time * 100 / (double) td->runtime;
1664                 sys_cpu = (double) td->sys_time * 100 / (double) td->runtime;
1665         } else {
1666                 usr_cpu = 0;
1667                 sys_cpu = 0;
1668         }
1669
1670         printf("  cpu        : usr=%3.2f%%, sys=%3.2f%%, ctx=%lu\n", usr_cpu, sys_cpu, td->ctx);
1671 }
1672
1673 static void print_thread_status(struct thread_data *td, int nr_running,
1674                                 int t_rate, int m_rate)
1675 {
1676         printf("Threads now running: %d", nr_running);
1677         if (m_rate || t_rate)
1678                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
1679         printf(" : [%s]\r", run_str);
1680         fflush(stdout);
1681 }
1682
1683 static void check_str_update(struct thread_data *td, int n, int t, int m)
1684 {
1685         char c = run_str[td->thread_number - 1];
1686
1687         if (td->runstate == td->old_runstate)
1688                 return;
1689
1690         switch (td->runstate) {
1691                 case TD_REAPED:
1692                         c = '_';
1693                         break;
1694                 case TD_EXITED:
1695                         c = 'E';
1696                         break;
1697                 case TD_RUNNING:
1698                         if (td_read(td)) {
1699                                 if (td->sequential)
1700                                         c = 'R';
1701                                 else
1702                                         c = 'r';
1703                         } else {
1704                                 if (td->sequential)
1705                                         c = 'W';
1706                                 else
1707                                         c = 'w';
1708                         }
1709                         break;
1710                 case TD_VERIFYING:
1711                         c = 'V';
1712                         break;
1713                 case TD_CREATED:
1714                         c = 'C';
1715                         break;
1716                 case TD_NOT_CREATED:
1717                         c = 'P';
1718                         break;
1719                 default:
1720                         printf("state %d\n", td->runstate);
1721         }
1722
1723         run_str[td->thread_number - 1] = c;
1724         print_thread_status(td, n, t, m);
1725         td->old_runstate = td->runstate;
1726 }
1727
1728 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1729 {
1730         int i;
1731
1732         /*
1733          * reap exited threads (TD_EXITED -> TD_REAPED)
1734          */
1735         for (i = 0; i < thread_number; i++) {
1736                 struct thread_data *td = &threads[i];
1737
1738                 check_str_update(td, *nr_running, *t_rate, *m_rate);
1739
1740                 if (td->runstate != TD_EXITED)
1741                         continue;
1742
1743                 td_set_runstate(td, TD_REAPED);
1744
1745                 if (td->use_thread) {
1746                         long ret;
1747
1748                         if (pthread_join(td->thread, (void *) &ret))
1749                                 perror("thread_join");
1750                 } else
1751                         waitpid(td->pid, NULL, 0);
1752
1753                 (*nr_running)--;
1754                 (*m_rate) -= td->ratemin;
1755                 (*t_rate) -= td->rate;
1756                 check_str_update(td, *nr_running, *t_rate, *m_rate);
1757         }
1758 }
1759
1760 static void run_threads(char *argv[])
1761 {
1762         struct timeval genesis;
1763         struct thread_data *td;
1764         unsigned long spent;
1765         int i, todo, nr_running, m_rate, t_rate, nr_started;
1766
1767         printf("Starting %d threads\n", thread_number);
1768         fflush(stdout);
1769
1770         signal(SIGINT, sig_handler);
1771
1772         todo = thread_number;
1773         nr_running = 0;
1774         nr_started = 0;
1775         m_rate = t_rate = 0;
1776
1777         for (i = 0; i < thread_number; i++) {
1778                 td = &threads[i];
1779
1780                 if (!td->create_serialize)
1781                         continue;
1782
1783                 /*
1784                  * do file setup here so it happens sequentially,
1785                  * we don't want X number of threads getting their
1786                  * client data interspersed on disk
1787                  */
1788                 if (setup_file(td)) {
1789                         td_set_runstate(td, TD_REAPED);
1790                         todo--;
1791                 }
1792         }
1793
1794         gettimeofday(&genesis, NULL);
1795
1796         while (todo) {
1797                 /*
1798                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1799                  */
1800                 for (i = 0; i < thread_number; i++) {
1801                         td = &threads[i];
1802
1803                         if (td->runstate != TD_NOT_CREATED)
1804                                 continue;
1805
1806                         /*
1807                          * never got a chance to start, killed by other
1808                          * thread for some reason
1809                          */
1810                         if (td->terminate) {
1811                                 todo--;
1812                                 continue;
1813                         }
1814
1815                         if (td->start_delay) {
1816                                 spent = mtime_since_now(&genesis);
1817
1818                                 if (td->start_delay * 1000 > spent)
1819                                         continue;
1820                         }
1821
1822                         if (td->stonewall && (nr_started || nr_running))
1823                                 break;
1824
1825                         td_set_runstate(td, TD_CREATED);
1826                         check_str_update(td, nr_running, t_rate, m_rate);
1827                         sem_init(&startup_sem, 1, 1);
1828                         todo--;
1829                         nr_started++;
1830
1831                         if (td->use_thread) {
1832                                 if (pthread_create(&td->thread, NULL, thread_main, td)) {
1833                                         perror("thread_create");
1834                                         nr_started--;
1835                                 }
1836                         } else {
1837                                 if (fork())
1838                                         sem_wait(&startup_sem);
1839                                 else {
1840                                         fork_main(shm_id, i);
1841                                         exit(0);
1842                                 }
1843                         }
1844                 }
1845
1846                 /*
1847                  * start created threads (TD_CREATED -> TD_RUNNING)
1848                  */
1849                 for (i = 0; i < thread_number; i++) {
1850                         struct thread_data *td = &threads[i];
1851
1852                         if (td->runstate != TD_CREATED)
1853                                 continue;
1854
1855                         td_set_runstate(td, TD_RUNNING);
1856                         nr_running++;
1857                         nr_started--;
1858                         m_rate += td->ratemin;
1859                         t_rate += td->rate;
1860                         check_str_update(td, nr_running, t_rate, m_rate);
1861                         sem_post(&td->mutex);
1862                 }
1863
1864                 for (i = 0; i < thread_number; i++) {
1865                         struct thread_data *td = &threads[i];
1866
1867                         if (td->runstate != TD_RUNNING &&
1868                             td->runstate != TD_VERIFYING)
1869                                 continue;
1870
1871                         check_str_update(td, nr_running, t_rate, m_rate);
1872                 }
1873
1874                 reap_threads(&nr_running, &t_rate, &m_rate);
1875
1876                 if (todo)
1877                         usleep(100000);
1878         }
1879
1880         while (nr_running) {
1881                 reap_threads(&nr_running, &t_rate, &m_rate);
1882                 usleep(10000);
1883         }
1884 }
1885
1886 static void show_group_stats(struct group_run_stats *rs, int id)
1887 {
1888         printf("\nRun status group %d:\n", id);
1889
1890         if (rs->max_run[DDIR_READ])
1891                 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]);
1892         if (rs->max_run[DDIR_WRITE])
1893                 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]);
1894 }
1895
1896 static void show_run_stats(void)
1897 {
1898         struct group_run_stats *runstats, *rs;
1899         struct thread_data *td;
1900         int i;
1901
1902         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
1903
1904         for (i = 0; i < groupid + 1; i++) {
1905                 rs = &runstats[i];
1906
1907                 memset(rs, 0, sizeof(*rs));
1908                 rs->min_bw[0] = rs->min_run[0] = ~0UL;
1909                 rs->min_bw[1] = rs->min_run[1] = ~0UL;
1910         }
1911
1912         for (i = 0; i < thread_number; i++) {
1913                 unsigned long bw = 0;
1914
1915                 td = &threads[i];
1916
1917                 if (td->error)
1918                         continue;
1919
1920                 rs = &runstats[td->groupid];
1921
1922                 if (td->runtime < rs->min_run[td->ddir])
1923                         rs->min_run[td->ddir] = td->runtime;
1924                 if (td->runtime > rs->max_run[td->ddir])
1925                         rs->max_run[td->ddir] = td->runtime;
1926
1927                 if (td->runtime)
1928                         bw = td->io_bytes / td->runtime;
1929                 if (bw < rs->min_bw[td->ddir])
1930                         rs->min_bw[td->ddir] = bw;
1931                 if (bw > rs->max_bw[td->ddir])
1932                         rs->max_bw[td->ddir] = bw;
1933
1934                 rs->io_mb[td->ddir] += td->io_bytes >> 20;
1935         }
1936
1937         for (i = 0; i < groupid + 1; i++) {
1938                 rs = &runstats[i];
1939
1940                 if (rs->max_run[0])
1941                         rs->agg[0] = (rs->io_mb[0]*1024*1000) / rs->max_run[0];
1942                 if (rs->max_run[1])
1943                         rs->agg[1] = (rs->io_mb[1]*1024*1000) / rs->max_run[1];
1944         }
1945
1946         for (i = 0; i < thread_number; i++) {
1947                 td = &threads[i];
1948                 rs = &runstats[td->groupid];
1949
1950                 show_thread_status(td, rs);
1951         }
1952
1953         for (i = 0; i < groupid + 1; i++)
1954                 show_group_stats(&runstats[i], i);
1955 }
1956
1957 int main(int argc, char *argv[])
1958 {
1959         memset(run_str, 0, sizeof(run_str));
1960
1961         if (parse_options(argc, argv))
1962                 return 1;
1963
1964         if (!thread_number) {
1965                 printf("Nothing to do\n");
1966                 return 1;
1967         }
1968
1969         run_threads(argv);
1970         show_run_stats();
1971
1972         return 0;
1973 }