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