[PATCH] Add support for specifying job nice value with nice=x
[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 static int get_rw_ddir(struct thread_data *td)
549 {
550         if (td_rw(td)) {
551                 struct timeval now;
552                 unsigned long elapsed;
553
554                 gettimeofday(&now, NULL);
555                 elapsed = mtime_since_now(&td->rwmix_switch);
556
557                 /*
558                  * Check if it's time to seed a new data direction.
559                  */
560                 if (elapsed >= td->rwmixcycle) {
561                         unsigned long v;
562                         long r;
563
564                         lrand48_r(&td->random_state, &r);
565                         v = 100UL * r / (unsigned long) (RAND_MAX + 1.0);
566                         if (v < td->rwmixread)
567                                 td->rwmix_ddir = DDIR_READ;
568                         else
569                                 td->rwmix_ddir = DDIR_WRITE;
570                         memcpy(&td->rwmix_switch, &now, sizeof(now));
571                 }
572                 return td->rwmix_ddir;
573         } else if (td_read(td))
574                 return DDIR_READ;
575         else
576                 return DDIR_WRITE;
577 }
578
579 /*
580  * fill body of io_u->buf with random data and add a header with the
581  * (eg) sha1sum of that data.
582  */
583 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
584 {
585         unsigned char *p = (unsigned char *) io_u->buf;
586         struct verify_header hdr;
587
588         hdr.fio_magic = FIO_HDR_MAGIC;
589         hdr.len = io_u->buflen;
590         p += sizeof(hdr);
591         fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
592
593         if (td->verify == VERIFY_MD5) {
594                 fill_md5(&hdr, p, io_u->buflen - sizeof(hdr));
595                 hdr.verify_type = VERIFY_MD5;
596         } else {
597                 fill_crc32(&hdr, p, io_u->buflen - sizeof(hdr));
598                 hdr.verify_type = VERIFY_CRC32;
599         }
600
601         memcpy(io_u->buf, &hdr, sizeof(hdr));
602 }
603
604 static int td_io_prep(struct thread_data *td, struct io_u *io_u)
605 {
606         if (td->io_prep && td->io_prep(td, io_u))
607                 return 1;
608
609         return 0;
610 }
611
612 void put_io_u(struct thread_data *td, struct io_u *io_u)
613 {
614         list_del(&io_u->list);
615         list_add(&io_u->list, &td->io_u_freelist);
616         td->cur_depth--;
617 }
618
619 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
620 {
621         /*
622          * If using an iolog, grab next piece if any available.
623          */
624         if (td->iolog) {
625                 struct io_piece *ipo;
626
627                 if (list_empty(&td->io_log_list))
628                         return 1;
629
630                 ipo = list_entry(td->io_log_list.next, struct io_piece, list);
631                 list_del(&ipo->list);
632                 io_u->offset = ipo->offset;
633                 io_u->buflen = ipo->len;
634                 io_u->ddir = ipo->ddir;
635                 free(ipo);
636                 return 0;
637         }
638
639         /*
640          * No log, let the seq/rand engine retrieve the next position.
641          */
642         if (!get_next_offset(td, &io_u->offset)) {
643                 io_u->buflen = get_next_buflen(td);
644
645                 if (io_u->buflen) {
646                         io_u->ddir = get_rw_ddir(td);
647                         return 0;
648                 }
649         }
650
651         return 1;
652 }
653
654 #define queue_full(td)  (list_empty(&(td)->io_u_freelist))
655
656 struct io_u *__get_io_u(struct thread_data *td)
657 {
658         struct io_u *io_u;
659
660         if (queue_full(td))
661                 return NULL;
662
663         io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
664         io_u->error = 0;
665         io_u->resid = 0;
666         list_del(&io_u->list);
667         list_add(&io_u->list, &td->io_u_busylist);
668         td->cur_depth++;
669         return io_u;
670 }
671
672 static struct io_u *get_io_u(struct thread_data *td)
673 {
674         struct io_u *io_u;
675
676         io_u = __get_io_u(td);
677         if (!io_u)
678                 return NULL;
679
680         if (td->zone_bytes >= td->zone_size) {
681                 td->zone_bytes = 0;
682                 td->last_pos += td->zone_skip;
683         }
684
685         if (fill_io_u(td, io_u)) {
686                 put_io_u(td, io_u);
687                 return NULL;
688         }
689
690         if (io_u->buflen + io_u->offset > td->real_file_size)
691                 io_u->buflen = td->real_file_size - io_u->offset;
692
693         if (!io_u->buflen) {
694                 put_io_u(td, io_u);
695                 return NULL;
696         }
697
698         if (!td->iolog && !td->sequential)
699                 mark_random_map(td, io_u);
700
701         td->last_pos += io_u->buflen;
702
703         if (td->verify != VERIFY_NONE)
704                 populate_io_u(td, io_u);
705
706         if (td_io_prep(td, io_u)) {
707                 put_io_u(td, io_u);
708                 return NULL;
709         }
710
711         gettimeofday(&io_u->start_time, NULL);
712         return io_u;
713 }
714
715 static inline void td_set_runstate(struct thread_data *td, int runstate)
716 {
717         td->old_runstate = td->runstate;
718         td->runstate = runstate;
719 }
720
721 static int get_next_verify(struct thread_data *td, struct io_u *io_u)
722 {
723         struct io_piece *ipo;
724
725         if (list_empty(&td->io_hist_list))
726                 return 1;
727
728         ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
729         list_del(&ipo->list);
730
731         io_u->offset = ipo->offset;
732         io_u->buflen = ipo->len;
733         io_u->ddir = DDIR_READ;
734         free(ipo);
735         return 0;
736 }
737
738 static void prune_io_piece_log(struct thread_data *td)
739 {
740         struct io_piece *ipo;
741
742         while (!list_empty(&td->io_hist_list)) {
743                 ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
744
745                 list_del(&ipo->list);
746                 free(ipo);
747         }
748 }
749
750 /*
751  * log a succesful write, so we can unwind the log for verify
752  */
753 static void log_io_piece(struct thread_data *td, struct io_u *io_u)
754 {
755         struct io_piece *ipo = malloc(sizeof(struct io_piece));
756         struct list_head *entry;
757
758         INIT_LIST_HEAD(&ipo->list);
759         ipo->offset = io_u->offset;
760         ipo->len = io_u->buflen;
761
762         /*
763          * for random io where the writes extend the file, it will typically
764          * be laid out with the block scattered as written. it's faster to
765          * read them in in that order again, so don't sort
766          */
767         if (td->sequential || !td->overwrite) {
768                 list_add_tail(&ipo->list, &td->io_hist_list);
769                 return;
770         }
771
772         /*
773          * for random io, sort the list so verify will run faster
774          */
775         entry = &td->io_hist_list;
776         while ((entry = entry->prev) != &td->io_hist_list) {
777                 struct io_piece *__ipo = list_entry(entry, struct io_piece, list);
778
779                 if (__ipo->offset < ipo->offset)
780                         break;
781         }
782
783         list_add(&ipo->list, entry);
784 }
785
786 static int init_iolog(struct thread_data *td)
787 {
788         unsigned long long offset;
789         unsigned int bytes;
790         char *str, *p;
791         FILE *f;
792         int rw, i, reads, writes;
793
794         if (!td->iolog)
795                 return 0;
796
797         f = fopen(td->iolog_file, "r");
798         if (!f) {
799                 perror("fopen iolog");
800                 return 1;
801         }
802
803         str = malloc(4096);
804         reads = writes = i = 0;
805         while ((p = fgets(str, 4096, f)) != NULL) {
806                 struct io_piece *ipo;
807
808                 if (sscanf(p, "%d,%llu,%u", &rw, &offset, &bytes) != 3) {
809                         fprintf(stderr, "bad iolog: %s\n", p);
810                         continue;
811                 }
812                 if (rw == DDIR_READ)
813                         reads++;
814                 else if (rw == DDIR_WRITE)
815                         writes++;
816                 else {
817                         fprintf(stderr, "bad ddir: %d\n", rw);
818                         continue;
819                 }
820
821                 ipo = malloc(sizeof(*ipo));
822                 INIT_LIST_HEAD(&ipo->list);
823                 ipo->offset = offset;
824                 ipo->len = bytes;
825                 if (bytes > td->max_bs)
826                         td->max_bs = bytes;
827                 ipo->ddir = rw;
828                 list_add_tail(&ipo->list, &td->io_log_list);
829                 i++;
830         }
831
832         free(str);
833         fclose(f);
834
835         if (!i)
836                 return 1;
837
838         if (reads && !writes)
839                 td->ddir = DDIR_READ;
840         else if (!reads && writes)
841                 td->ddir = DDIR_READ;
842         else
843                 td->iomix = 1;
844
845         return 0;
846 }
847
848 static int sync_td(struct thread_data *td)
849 {
850         if (td->io_sync)
851                 return td->io_sync(td);
852
853         return 0;
854 }
855
856 static int io_u_getevents(struct thread_data *td, int min, int max,
857                           struct timespec *t)
858 {
859         return td->io_getevents(td, min, max, t);
860 }
861
862 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
863 {
864         gettimeofday(&io_u->issue_time, NULL);
865
866         return td->io_queue(td, io_u);
867 }
868
869 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
870
871 static void io_completed(struct thread_data *td, struct io_u *io_u,
872                          struct io_completion_data *icd)
873 {
874         struct timeval e;
875         unsigned long msec;
876
877         gettimeofday(&e, NULL);
878
879         if (!io_u->error) {
880                 unsigned int bytes = io_u->buflen - io_u->resid;
881                 const int idx = io_u->ddir;
882
883                 td->io_blocks[idx]++;
884                 td->io_bytes[idx] += bytes;
885                 td->zone_bytes += bytes;
886                 td->this_io_bytes[idx] += bytes;
887
888                 msec = mtime_since(&io_u->issue_time, &e);
889
890                 add_clat_sample(td, idx, msec);
891                 add_bw_sample(td, idx);
892
893                 if ((td_rw(td) || td_write(td)) && idx == DDIR_WRITE)
894                         log_io_piece(td, io_u);
895
896                 icd->bytes_done[idx] += bytes;
897         } else
898                 icd->error = io_u->error;
899 }
900
901 static void ios_completed(struct thread_data *td,struct io_completion_data *icd)
902 {
903         struct io_u *io_u;
904         int i;
905
906         icd->error = 0;
907         icd->bytes_done[0] = icd->bytes_done[1] = 0;
908
909         for (i = 0; i < icd->nr; i++) {
910                 io_u = td->io_event(td, i);
911
912                 io_completed(td, io_u, icd);
913                 put_io_u(td, io_u);
914         }
915 }
916
917 static void cleanup_pending_aio(struct thread_data *td)
918 {
919         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
920         struct list_head *entry, *n;
921         struct io_completion_data icd;
922         struct io_u *io_u;
923         int r;
924
925         /*
926          * get immediately available events, if any
927          */
928         r = io_u_getevents(td, 0, td->cur_depth, &ts);
929         if (r > 0) {
930                 icd.nr = r;
931                 ios_completed(td, &icd);
932         }
933
934         /*
935          * now cancel remaining active events
936          */
937         if (td->io_cancel) {
938                 list_for_each_safe(entry, n, &td->io_u_busylist) {
939                         io_u = list_entry(entry, struct io_u, list);
940
941                         r = td->io_cancel(td, io_u);
942                         if (!r)
943                                 put_io_u(td, io_u);
944                 }
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                         icd.nr = r;
951                         ios_completed(td, &icd);
952                 }
953         }
954 }
955
956 static int do_io_u_verify(struct thread_data *td, struct io_u **io_u)
957 {
958         struct io_u *v_io_u = *io_u;
959         int ret = 0;
960
961         if (v_io_u) {
962                 ret = verify_io_u(v_io_u);
963                 put_io_u(td, v_io_u);
964                 *io_u = NULL;
965         }
966
967         return ret;
968 }
969
970 static void do_verify(struct thread_data *td)
971 {
972         struct timeval t;
973         struct io_u *io_u, *v_io_u = NULL;
974         struct io_completion_data icd;
975         int ret;
976
977         td_set_runstate(td, TD_VERIFYING);
978
979         do {
980                 if (td->terminate)
981                         break;
982
983                 gettimeofday(&t, NULL);
984                 if (runtime_exceeded(td, &t))
985                         break;
986
987                 io_u = __get_io_u(td);
988                 if (!io_u)
989                         break;
990
991                 if (get_next_verify(td, io_u)) {
992                         put_io_u(td, io_u);
993                         break;
994                 }
995
996                 if (td_io_prep(td, io_u)) {
997                         put_io_u(td, io_u);
998                         break;
999                 }
1000
1001                 ret = io_u_queue(td, io_u);
1002                 if (ret) {
1003                         put_io_u(td, io_u);
1004                         td_verror(td, ret);
1005                         break;
1006                 }
1007
1008                 /*
1009                  * we have one pending to verify, do that while
1010                  * we are doing io on the next one
1011                  */
1012                 if (do_io_u_verify(td, &v_io_u))
1013                         break;
1014
1015                 ret = io_u_getevents(td, 1, 1, NULL);
1016                 if (ret != 1) {
1017                         if (ret < 0)
1018                                 td_verror(td, ret);
1019                         break;
1020                 }
1021
1022                 v_io_u = td->io_event(td, 0);
1023                 icd.nr = 1;
1024                 icd.error = 0;
1025                 io_completed(td, v_io_u, &icd);
1026
1027                 if (icd.error) {
1028                         td_verror(td, icd.error);
1029                         put_io_u(td, v_io_u);
1030                         v_io_u = NULL;
1031                         break;
1032                 }
1033
1034                 /*
1035                  * if we can't submit more io, we need to verify now
1036                  */
1037                 if (queue_full(td) && do_io_u_verify(td, &v_io_u))
1038                         break;
1039
1040         } while (1);
1041
1042         do_io_u_verify(td, &v_io_u);
1043
1044         if (td->cur_depth)
1045                 cleanup_pending_aio(td);
1046
1047         td_set_runstate(td, TD_RUNNING);
1048 }
1049
1050 static void do_io(struct thread_data *td)
1051 {
1052         struct io_completion_data icd;
1053         struct timeval s, e;
1054         unsigned long usec;
1055
1056         while (td->this_io_bytes[td->ddir] < td->io_size) {
1057                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
1058                 struct timespec *timeout;
1059                 int ret, min_evts = 0;
1060                 struct io_u *io_u;
1061
1062                 if (td->terminate)
1063                         break;
1064
1065                 io_u = get_io_u(td);
1066                 if (!io_u)
1067                         break;
1068
1069                 memcpy(&s, &io_u->start_time, sizeof(s));
1070
1071                 ret = io_u_queue(td, io_u);
1072                 if (ret) {
1073                         put_io_u(td, io_u);
1074                         td_verror(td, ret);
1075                         break;
1076                 }
1077
1078                 add_slat_sample(td, io_u->ddir, mtime_since(&io_u->start_time, &io_u->issue_time));
1079
1080                 if (td->cur_depth < td->iodepth) {
1081                         timeout = &ts;
1082                         min_evts = 0;
1083                 } else {
1084                         timeout = NULL;
1085                         min_evts = 1;
1086                 }
1087
1088                 ret = io_u_getevents(td, min_evts, td->cur_depth, timeout);
1089                 if (ret < 0) {
1090                         td_verror(td, ret);
1091                         break;
1092                 } else if (!ret)
1093                         continue;
1094
1095                 icd.nr = ret;
1096                 ios_completed(td, &icd);
1097                 if (icd.error) {
1098                         td_verror(td, icd.error);
1099                         break;
1100                 }
1101
1102                 /*
1103                  * the rate is batched for now, it should work for batches
1104                  * of completions except the very first one which may look
1105                  * a little bursty
1106                  */
1107                 gettimeofday(&e, NULL);
1108                 usec = utime_since(&s, &e);
1109
1110                 rate_throttle(td, usec, icd.bytes_done[td->ddir]);
1111
1112                 if (check_min_rate(td, &e)) {
1113                         td_verror(td, ENOMEM);
1114                         break;
1115                 }
1116
1117                 if (runtime_exceeded(td, &e))
1118                         break;
1119
1120                 if (td->thinktime)
1121                         usec_sleep(td, td->thinktime);
1122
1123                 if (should_fsync(td) && td->fsync_blocks &&
1124                     (td->io_blocks[DDIR_WRITE] % td->fsync_blocks) == 0)
1125                         sync_td(td);
1126         }
1127
1128         if (td->cur_depth)
1129                 cleanup_pending_aio(td);
1130
1131         if (should_fsync(td) && td->end_fsync)
1132                 sync_td(td);
1133 }
1134
1135 static void cleanup_io(struct thread_data *td)
1136 {
1137         if (td->io_cleanup)
1138                 td->io_cleanup(td);
1139 }
1140
1141 static int init_io(struct thread_data *td)
1142 {
1143         if (td->io_engine == FIO_SYNCIO)
1144                 return fio_syncio_init(td);
1145         else if (td->io_engine == FIO_MMAPIO)
1146                 return fio_mmapio_init(td);
1147         else if (td->io_engine == FIO_LIBAIO)
1148                 return fio_libaio_init(td);
1149         else if (td->io_engine == FIO_POSIXAIO)
1150                 return fio_posixaio_init(td);
1151         else if (td->io_engine == FIO_SGIO)
1152                 return fio_sgio_init(td);
1153         else if (td->io_engine == FIO_SPLICEIO)
1154                 return fio_spliceio_init(td);
1155         else {
1156                 fprintf(stderr, "bad io_engine %d\n", td->io_engine);
1157                 return 1;
1158         }
1159 }
1160
1161 static void cleanup_io_u(struct thread_data *td)
1162 {
1163         struct list_head *entry, *n;
1164         struct io_u *io_u;
1165
1166         list_for_each_safe(entry, n, &td->io_u_freelist) {
1167                 io_u = list_entry(entry, struct io_u, list);
1168
1169                 list_del(&io_u->list);
1170                 free(io_u);
1171         }
1172
1173         if (td->mem_type == MEM_MALLOC)
1174                 free(td->orig_buffer);
1175         else if (td->mem_type == MEM_SHM) {
1176                 struct shmid_ds sbuf;
1177
1178                 shmdt(td->orig_buffer);
1179                 shmctl(td->shm_id, IPC_RMID, &sbuf);
1180         } else if (td->mem_type == MEM_MMAP)
1181                 munmap(td->orig_buffer, td->orig_buffer_size);
1182         else
1183                 fprintf(stderr, "Bad memory type %d\n", td->mem_type);
1184
1185         td->orig_buffer = NULL;
1186 }
1187
1188 static int init_io_u(struct thread_data *td)
1189 {
1190         struct io_u *io_u;
1191         int i, max_units;
1192         char *p;
1193
1194         if (td->io_engine & FIO_SYNCIO)
1195                 max_units = 1;
1196         else
1197                 max_units = td->iodepth;
1198
1199         td->orig_buffer_size = td->max_bs * max_units + MASK;
1200
1201         if (td->mem_type == MEM_MALLOC)
1202                 td->orig_buffer = malloc(td->orig_buffer_size);
1203         else if (td->mem_type == MEM_SHM) {
1204                 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
1205                 if (td->shm_id < 0) {
1206                         td_verror(td, errno);
1207                         perror("shmget");
1208                         return 1;
1209                 }
1210
1211                 td->orig_buffer = shmat(td->shm_id, NULL, 0);
1212                 if (td->orig_buffer == (void *) -1) {
1213                         td_verror(td, errno);
1214                         perror("shmat");
1215                         td->orig_buffer = NULL;
1216                         return 1;
1217                 }
1218         } else if (td->mem_type == MEM_MMAP) {
1219                 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
1220                 if (td->orig_buffer == MAP_FAILED) {
1221                         td_verror(td, errno);
1222                         perror("mmap");
1223                         td->orig_buffer = NULL;
1224                         return 1;
1225                 }
1226         }
1227
1228         p = ALIGN(td->orig_buffer);
1229         for (i = 0; i < max_units; i++) {
1230                 io_u = malloc(sizeof(*io_u));
1231                 memset(io_u, 0, sizeof(*io_u));
1232                 INIT_LIST_HEAD(&io_u->list);
1233
1234                 io_u->buf = p + td->max_bs * i;
1235                 io_u->index = i;
1236                 list_add(&io_u->list, &td->io_u_freelist);
1237         }
1238
1239         return 0;
1240 }
1241
1242 static int create_file(struct thread_data *td, unsigned long long size,
1243                        int extend)
1244 {
1245         unsigned long long left;
1246         unsigned int bs;
1247         int r, oflags;
1248         char *b;
1249
1250         /*
1251          * unless specifically asked for overwrite, let normal io extend it
1252          */
1253         if (td_write(td) && !td->overwrite)
1254                 return 0;
1255
1256         if (!size) {
1257                 fprintf(stderr, "Need size for create\n");
1258                 td_verror(td, EINVAL);
1259                 return 1;
1260         }
1261
1262         if (!extend) {
1263                 oflags = O_CREAT | O_TRUNC;
1264                 printf("Client%d: Laying out IO file (%LuMiB)\n", td->thread_number, size >> 20);
1265         } else {
1266                 oflags = O_APPEND;
1267                 printf("Client%d: Extending IO file (%Lu -> %LuMiB)\n", td->thread_number, (td->file_size - size) >> 20, td->file_size >> 20);
1268         }
1269
1270         td->fd = open(td->file_name, O_WRONLY | oflags, 0644);
1271         if (td->fd < 0) {
1272                 td_verror(td, errno);
1273                 return 1;
1274         }
1275
1276         if (!extend && ftruncate(td->fd, td->file_size) == -1) {
1277                 td_verror(td, errno);
1278                 return 1;
1279         }
1280
1281         td->io_size = td->file_size;
1282         b = malloc(td->max_bs);
1283         memset(b, 0, td->max_bs);
1284
1285         left = size;
1286         while (left && !td->terminate) {
1287                 bs = td->max_bs;
1288                 if (bs > left)
1289                         bs = left;
1290
1291                 r = write(td->fd, b, bs);
1292
1293                 if (r == (int) bs) {
1294                         left -= bs;
1295                         continue;
1296                 } else {
1297                         if (r < 0)
1298                                 td_verror(td, errno);
1299                         else
1300                                 td_verror(td, EIO);
1301
1302                         break;
1303                 }
1304         }
1305
1306         if (td->terminate)
1307                 unlink(td->file_name);
1308         else if (td->create_fsync)
1309                 fsync(td->fd);
1310
1311         close(td->fd);
1312         td->fd = -1;
1313         free(b);
1314         return 0;
1315 }
1316
1317 static int file_size(struct thread_data *td)
1318 {
1319         struct stat st;
1320
1321         if (fstat(td->fd, &st) == -1) {
1322                 td_verror(td, errno);
1323                 return 1;
1324         }
1325
1326         td->real_file_size = st.st_size;
1327
1328         if (!td->file_size || td->file_size > td->real_file_size)
1329                 td->file_size = td->real_file_size;
1330
1331         td->file_size -= td->file_offset;
1332         return 0;
1333 }
1334
1335 static int bdev_size(struct thread_data *td)
1336 {
1337         unsigned long long bytes;
1338         int r;
1339
1340         r = blockdev_size(td->fd, &bytes);
1341         if (r) {
1342                 td_verror(td, r);
1343                 return 1;
1344         }
1345
1346         td->real_file_size = bytes;
1347
1348         /*
1349          * no extend possibilities, so limit size to device size if too large
1350          */
1351         if (!td->file_size || td->file_size > td->real_file_size)
1352                 td->file_size = td->real_file_size;
1353
1354         td->file_size -= td->file_offset;
1355         return 0;
1356 }
1357
1358 static int get_file_size(struct thread_data *td)
1359 {
1360         int ret = 0;
1361
1362         if (td->filetype == FIO_TYPE_FILE)
1363                 ret = file_size(td);
1364         else if (td->filetype == FIO_TYPE_BD)
1365                 ret = bdev_size(td);
1366         else
1367                 td->real_file_size = -1;
1368
1369         if (ret)
1370                 return ret;
1371
1372         if (td->file_offset > td->real_file_size) {
1373                 fprintf(stderr, "Client%d: offset extends end (%Lu > %Lu)\n", td->thread_number, td->file_offset, td->real_file_size);
1374                 return 1;
1375         }
1376
1377         td->io_size = td->file_size;
1378         if (td->io_size == 0) {
1379                 fprintf(stderr, "Client%d: no io blocks\n", td->thread_number);
1380                 td_verror(td, EINVAL);
1381                 return 1;
1382         }
1383
1384         if (!td->zone_size)
1385                 td->zone_size = td->io_size;
1386
1387         td->total_io_size = td->io_size * td->loops;
1388         return 0;
1389 }
1390
1391 static int setup_file_mmap(struct thread_data *td)
1392 {
1393         int flags;
1394
1395         if (td_rw(td))
1396                 flags = PROT_READ | PROT_WRITE;
1397         else if (td_write(td)) {
1398                 flags = PROT_WRITE;
1399
1400                 if (td->verify != VERIFY_NONE)
1401                         flags |= PROT_READ;
1402         } else
1403                 flags = PROT_READ;
1404
1405         td->mmap = mmap(NULL, td->file_size, flags, MAP_SHARED, td->fd, td->file_offset);
1406         if (td->mmap == MAP_FAILED) {
1407                 td->mmap = NULL;
1408                 td_verror(td, errno);
1409                 return 1;
1410         }
1411
1412         if (td->invalidate_cache) {
1413                 if (madvise(td->mmap, td->file_size, MADV_DONTNEED) < 0) {
1414                         td_verror(td, errno);
1415                         return 1;
1416                 }
1417         }
1418
1419         if (td->sequential) {
1420                 if (madvise(td->mmap, td->file_size, MADV_SEQUENTIAL) < 0) {
1421                         td_verror(td, errno);
1422                         return 1;
1423                 }
1424         } else {
1425                 if (madvise(td->mmap, td->file_size, MADV_RANDOM) < 0) {
1426                         td_verror(td, errno);
1427                         return 1;
1428                 }
1429         }
1430
1431         return 0;
1432 }
1433
1434 static int setup_file_plain(struct thread_data *td)
1435 {
1436         if (td->invalidate_cache) {
1437                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_DONTNEED) < 0) {
1438                         td_verror(td, errno);
1439                         return 1;
1440                 }
1441         }
1442
1443         if (td->sequential) {
1444                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_SEQUENTIAL) < 0) {
1445                         td_verror(td, errno);
1446                         return 1;
1447                 }
1448         } else {
1449                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_RANDOM) < 0) {
1450                         td_verror(td, errno);
1451                         return 1;
1452                 }
1453         }
1454
1455         return 0;
1456 }
1457
1458 static int setup_file(struct thread_data *td)
1459 {
1460         struct stat st;
1461         int flags = 0;
1462
1463         if (stat(td->file_name, &st) == -1) {
1464                 if (errno != ENOENT) {
1465                         td_verror(td, errno);
1466                         return 1;
1467                 }
1468                 if (!td->create_file) {
1469                         td_verror(td, ENOENT);
1470                         return 1;
1471                 }
1472                 if (create_file(td, td->file_size, 0))
1473                         return 1;
1474         } else if (td->filetype == FIO_TYPE_FILE) {
1475                 if (st.st_size < (off_t) td->file_size) {
1476                         if (create_file(td, td->file_size - st.st_size, 1))
1477                                 return 1;
1478                 }
1479         }
1480
1481         if (td->odirect)
1482                 flags |= O_DIRECT;
1483
1484         if (td_write(td) || td_rw(td)) {
1485                 if (td->filetype == FIO_TYPE_FILE) {
1486                         if (!td->overwrite)
1487                                 flags |= O_TRUNC;
1488
1489                         flags |= O_CREAT;
1490                 }
1491                 if (td->sync_io)
1492                         flags |= O_SYNC;
1493
1494                 flags |= O_RDWR;
1495
1496                 td->fd = open(td->file_name, flags, 0600);
1497         } else {
1498                 if (td->filetype == FIO_TYPE_CHAR)
1499                         flags |= O_RDWR;
1500                 else
1501                         flags |= O_RDONLY;
1502
1503                 td->fd = open(td->file_name, flags);
1504         }
1505
1506         if (td->fd == -1) {
1507                 td_verror(td, errno);
1508                 return 1;
1509         }
1510
1511         if (get_file_size(td))
1512                 return 1;
1513
1514         if (td->io_engine != FIO_MMAPIO)
1515                 return setup_file_plain(td);
1516         else
1517                 return setup_file_mmap(td);
1518 }
1519
1520 static int check_dev_match(dev_t dev, char *path)
1521 {
1522         unsigned int major, minor;
1523         char line[256], *p;
1524         FILE *f;
1525
1526         f = fopen(path, "r");
1527         if (!f) {
1528                 perror("open path");
1529                 return 1;
1530         }
1531
1532         p = fgets(line, sizeof(line), f);
1533         if (!p) {
1534                 fclose(f);
1535                 return 1;
1536         }
1537
1538         if (sscanf(p, "%u:%u", &major, &minor) != 2) {
1539                 fclose(f);
1540                 return 1;
1541         }
1542
1543         if (((major << 8) | minor) == dev) {
1544                 fclose(f);
1545                 return 0;
1546         }
1547
1548         fclose(f);
1549         return 1;
1550 }
1551
1552 static int find_block_dir(dev_t dev, char *path)
1553 {
1554         struct dirent *dir;
1555         struct stat st;
1556         int found = 0;
1557         DIR *D;
1558
1559         D = opendir(path);
1560         if (!D)
1561                 return 0;
1562
1563         while ((dir = readdir(D)) != NULL) {
1564                 char full_path[256];
1565
1566                 if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, ".."))
1567                         continue;
1568                 if (!strcmp(dir->d_name, "device"))
1569                         continue;
1570
1571                 sprintf(full_path, "%s/%s", path, dir->d_name);
1572
1573                 if (!strcmp(dir->d_name, "dev")) {
1574                         if (!check_dev_match(dev, full_path)) {
1575                                 found = 1;
1576                                 break;
1577                         }
1578                 }
1579
1580                 if (stat(full_path, &st) == -1) {
1581                         perror("stat");
1582                         break;
1583                 }
1584
1585                 if (!S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode))
1586                         continue;
1587
1588                 found = find_block_dir(dev, full_path);
1589                 if (found) {
1590                         strcpy(path, full_path);
1591                         break;
1592                 }
1593         }
1594
1595         closedir(D);
1596         return found;
1597 }
1598
1599 static int get_io_ticks(struct disk_util *du, struct disk_util_stat *dus)
1600 {
1601         unsigned in_flight;
1602         char line[256];
1603         FILE *f;
1604         char *p;
1605
1606         f = fopen(du->path, "r");
1607         if (!f)
1608                 return 1;
1609
1610         p = fgets(line, sizeof(line), f);
1611         if (!p) {
1612                 fclose(f);
1613                 return 1;
1614         }
1615
1616         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) {
1617                 fclose(f);
1618                 return 1;
1619         }
1620
1621         fclose(f);
1622         return 0;
1623 }
1624
1625 static void update_io_tick_disk(struct disk_util *du)
1626 {
1627         struct disk_util_stat __dus, *dus, *ldus;
1628         struct timeval t;
1629
1630         if (get_io_ticks(du, &__dus))
1631                 return;
1632
1633         dus = &du->dus;
1634         ldus = &du->last_dus;
1635
1636         dus->sectors[0] += (__dus.sectors[0] - ldus->sectors[0]);
1637         dus->sectors[1] += (__dus.sectors[1] - ldus->sectors[1]);
1638         dus->ios[0] += (__dus.ios[0] - ldus->ios[0]);
1639         dus->ios[1] += (__dus.ios[1] - ldus->ios[1]);
1640         dus->merges[0] += (__dus.merges[0] - ldus->merges[0]);
1641         dus->merges[1] += (__dus.merges[1] - ldus->merges[1]);
1642         dus->ticks[0] += (__dus.ticks[0] - ldus->ticks[0]);
1643         dus->ticks[1] += (__dus.ticks[1] - ldus->ticks[1]);
1644         dus->io_ticks += (__dus.io_ticks - ldus->io_ticks);
1645         dus->time_in_queue += (__dus.time_in_queue - ldus->time_in_queue);
1646
1647         gettimeofday(&t, NULL);
1648         du->msec += mtime_since(&du->time, &t);
1649         memcpy(&du->time, &t, sizeof(t));
1650         memcpy(ldus, &__dus, sizeof(__dus));
1651 }
1652
1653 static void update_io_ticks(void)
1654 {
1655         struct list_head *entry;
1656         struct disk_util *du;
1657
1658         list_for_each(entry, &disk_list) {
1659                 du = list_entry(entry, struct disk_util, list);
1660                 update_io_tick_disk(du);
1661         }
1662 }
1663
1664 static int disk_util_exists(dev_t dev)
1665 {
1666         struct list_head *entry;
1667         struct disk_util *du;
1668
1669         list_for_each(entry, &disk_list) {
1670                 du = list_entry(entry, struct disk_util, list);
1671
1672                 if (du->dev == dev)
1673                         return 1;
1674         }
1675
1676         return 0;
1677 }
1678
1679 static void disk_util_add(dev_t dev, char *path)
1680 {
1681         struct disk_util *du = malloc(sizeof(*du));
1682
1683         memset(du, 0, sizeof(*du));
1684         INIT_LIST_HEAD(&du->list);
1685         sprintf(du->path, "%s/stat", path);
1686         du->name = strdup(basename(path));
1687         du->dev = dev;
1688
1689         gettimeofday(&du->time, NULL);
1690         get_io_ticks(du, &du->last_dus);
1691
1692         list_add_tail(&du->list, &disk_list);
1693 }
1694
1695 static void init_disk_util(struct thread_data *td)
1696 {
1697         struct stat st;
1698         char foo[256], tmp[256];
1699         dev_t dev;
1700         char *p;
1701
1702         if (!td->do_disk_util)
1703                 return;
1704
1705         if (!stat(td->file_name, &st)) {
1706                 if (S_ISBLK(st.st_mode))
1707                         dev = st.st_rdev;
1708                 else
1709                         dev = st.st_dev;
1710         } else {
1711                 /*
1712                  * must be a file, open "." in that path
1713                  */
1714                 strcpy(foo, td->file_name);
1715                 p = dirname(foo);
1716                 if (stat(p, &st)) {
1717                         perror("disk util stat");
1718                         return;
1719                 }
1720
1721                 dev = st.st_dev;
1722         }
1723
1724         if (disk_util_exists(dev))
1725                 return;
1726                 
1727         sprintf(foo, "/sys/block");
1728         if (!find_block_dir(dev, foo))
1729                 return;
1730
1731         /*
1732          * If there's a ../queue/ directory there, we are inside a partition.
1733          * Check if that is the case and jump back. For loop/md/dm etc we
1734          * are already in the right spot.
1735          */
1736         sprintf(tmp, "%s/../queue", foo);
1737         if (!stat(tmp, &st)) {
1738                 p = dirname(foo);
1739                 sprintf(tmp, "%s/queue", p);
1740                 if (stat(tmp, &st)) {
1741                         fprintf(stderr, "unknown sysfs layout\n");
1742                         return;
1743                 }
1744                 sprintf(foo, "%s", p);
1745         }
1746
1747         disk_util_add(dev, foo);
1748 }
1749
1750 static void disk_util_timer_arm(void)
1751 {
1752         itimer.it_value.tv_sec = 0;
1753         itimer.it_value.tv_usec = DISK_UTIL_MSEC * 1000;
1754         setitimer(ITIMER_REAL, &itimer, NULL);
1755 }
1756
1757 static void clear_io_state(struct thread_data *td)
1758 {
1759         if (td->io_engine == FIO_SYNCIO)
1760                 lseek(td->fd, SEEK_SET, 0);
1761
1762         td->last_pos = 0;
1763         td->stat_io_bytes[0] = td->stat_io_bytes[1] = 0;
1764         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
1765         td->zone_bytes = 0;
1766
1767         if (td->file_map)
1768                 memset(td->file_map, 0, td->num_maps * sizeof(long));
1769 }
1770
1771 static void update_rusage_stat(struct thread_data *td)
1772 {
1773         if (!(td->runtime[0] + td->runtime[1]))
1774                 return;
1775
1776         getrusage(RUSAGE_SELF, &td->ru_end);
1777
1778         td->usr_time += mtime_since(&td->ru_start.ru_utime, &td->ru_end.ru_utime);
1779         td->sys_time += mtime_since(&td->ru_start.ru_stime, &td->ru_end.ru_stime);
1780         td->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
1781
1782         
1783         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
1784 }
1785
1786 static void *thread_main(void *data)
1787 {
1788         struct thread_data *td = data;
1789
1790         if (!td->use_thread)
1791                 setsid();
1792
1793         td->pid = getpid();
1794
1795         INIT_LIST_HEAD(&td->io_u_freelist);
1796         INIT_LIST_HEAD(&td->io_u_busylist);
1797         INIT_LIST_HEAD(&td->io_hist_list);
1798         INIT_LIST_HEAD(&td->io_log_list);
1799
1800         if (init_io_u(td))
1801                 goto err;
1802
1803         if (fio_setaffinity(td) == -1) {
1804                 td_verror(td, errno);
1805                 goto err;
1806         }
1807
1808         if (init_io(td))
1809                 goto err;
1810
1811         if (init_iolog(td))
1812                 goto err;
1813
1814         if (td->ioprio) {
1815                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1816                         td_verror(td, errno);
1817                         goto err;
1818                 }
1819         }
1820
1821         if (nice(td->nice) < 0) {
1822                 td_verror(td, errno);
1823                 goto err;
1824         }
1825
1826         if (init_random_state(td))
1827                 goto err;
1828
1829         td_set_runstate(td, TD_INITIALIZED);
1830         sem_post(&startup_sem);
1831         sem_wait(&td->mutex);
1832
1833         if (!td->create_serialize && setup_file(td))
1834                 goto err;
1835
1836         gettimeofday(&td->epoch, NULL);
1837
1838         while (td->loops--) {
1839                 getrusage(RUSAGE_SELF, &td->ru_start);
1840                 gettimeofday(&td->start, NULL);
1841                 memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1842
1843                 if (td->ratemin)
1844                         memcpy(&td->lastrate, &td->stat_sample_time, sizeof(td->lastrate));
1845
1846                 clear_io_state(td);
1847                 prune_io_piece_log(td);
1848
1849                 do_io(td);
1850
1851                 td->runtime[td->ddir] += mtime_since_now(&td->start);
1852                 if (td_rw(td) && td->io_bytes[td->ddir ^ 1])
1853                         td->runtime[td->ddir ^ 1] = td->runtime[td->ddir];
1854
1855                 update_rusage_stat(td);
1856
1857                 if (td->error || td->terminate)
1858                         break;
1859
1860                 if (td->verify == VERIFY_NONE)
1861                         continue;
1862
1863                 clear_io_state(td);
1864                 gettimeofday(&td->start, NULL);
1865
1866                 do_verify(td);
1867
1868                 td->runtime[DDIR_READ] += mtime_since_now(&td->start);
1869
1870                 if (td->error || td->terminate)
1871                         break;
1872         }
1873
1874         if (td->bw_log)
1875                 finish_log(td, td->bw_log, "bw");
1876         if (td->slat_log)
1877                 finish_log(td, td->slat_log, "slat");
1878         if (td->clat_log)
1879                 finish_log(td, td->clat_log, "clat");
1880
1881         if (exitall_on_terminate)
1882                 terminate_threads(td->groupid);
1883
1884 err:
1885         if (td->fd != -1) {
1886                 close(td->fd);
1887                 td->fd = -1;
1888         }
1889         if (td->mmap)
1890                 munmap(td->mmap, td->file_size);
1891         cleanup_io(td);
1892         cleanup_io_u(td);
1893         td_set_runstate(td, TD_EXITED);
1894         return NULL;
1895
1896 }
1897
1898 static void *fork_main(int shmid, int offset)
1899 {
1900         struct thread_data *td;
1901         void *data;
1902
1903         data = shmat(shmid, NULL, 0);
1904         if (data == (void *) -1) {
1905                 perror("shmat");
1906                 return NULL;
1907         }
1908
1909         td = data + offset * sizeof(struct thread_data);
1910         thread_main(td);
1911         shmdt(data);
1912         return NULL;
1913 }
1914
1915 static int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
1916                     double *mean, double *dev)
1917 {
1918         double n;
1919
1920         if (is->samples == 0)
1921                 return 0;
1922
1923         *min = is->min_val;
1924         *max = is->max_val;
1925
1926         n = (double) is->samples;
1927         *mean = (double) is->val / n;
1928         *dev = sqrt(((double) is->val_sq - (*mean * *mean) / n) / (n - 1));
1929         if (!(*min + *max) && !(*mean + *dev))
1930                 return 0;
1931
1932         return 1;
1933 }
1934
1935 static void show_ddir_status(struct thread_data *td, struct group_run_stats *rs,
1936                              int ddir)
1937 {
1938         char *ddir_str[] = { "read ", "write" };
1939         unsigned long min, max;
1940         unsigned long long bw;
1941         double mean, dev;
1942
1943         if (!td->runtime[ddir])
1944                 return;
1945
1946         bw = td->io_bytes[ddir] / td->runtime[ddir];
1947         printf("  %s: io=%6lluMiB, bw=%6lluKiB/s, runt=%6lumsec\n", ddir_str[ddir], td->io_bytes[ddir] >> 20, bw, td->runtime[ddir]);
1948
1949         if (calc_lat(&td->slat_stat[ddir], &min, &max, &mean, &dev))
1950                 printf("    slat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1951
1952         if (calc_lat(&td->clat_stat[ddir], &min, &max, &mean, &dev))
1953                 printf("    clat (msec): min=%5lu, max=%5lu, avg=%5.02f, dev=%5.02f\n", min, max, mean, dev);
1954
1955         if (calc_lat(&td->bw_stat[ddir], &min, &max, &mean, &dev)) {
1956                 double p_of_agg;
1957
1958                 p_of_agg = mean * 100 / (double) rs->agg[ddir];
1959                 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);
1960         }
1961 }
1962
1963 static void show_thread_status(struct thread_data *td,
1964                                struct group_run_stats *rs)
1965 {
1966         double usr_cpu, sys_cpu;
1967
1968         if (!(td->io_bytes[0] + td->io_bytes[1]) && !td->error)
1969                 return;
1970
1971         printf("Client%d (groupid=%d): err=%2d:\n", td->thread_number, td->groupid, td->error);
1972
1973         show_ddir_status(td, rs, td->ddir);
1974         if (td->io_bytes[td->ddir ^ 1])
1975                 show_ddir_status(td, rs, td->ddir ^ 1);
1976
1977         if (td->runtime[0] + td->runtime[1]) {
1978                 double runt = td->runtime[0] + td->runtime[1];
1979
1980                 usr_cpu = (double) td->usr_time * 100 / runt;
1981                 sys_cpu = (double) td->sys_time * 100 / runt;
1982         } else {
1983                 usr_cpu = 0;
1984                 sys_cpu = 0;
1985         }
1986
1987         printf("  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%lu\n", usr_cpu, sys_cpu, td->ctx);
1988 }
1989
1990 static void check_str_update(struct thread_data *td)
1991 {
1992         char c = run_str[td->thread_number - 1];
1993
1994         if (td->runstate == td->old_runstate)
1995                 return;
1996
1997         switch (td->runstate) {
1998                 case TD_REAPED:
1999                         c = '_';
2000                         break;
2001                 case TD_EXITED:
2002                         c = 'E';
2003                         break;
2004                 case TD_RUNNING:
2005                         if (td_rw(td)) {
2006                                 if (td->sequential)
2007                                         c = 'M';
2008                                 else
2009                                         c = 'm';
2010                         } else if (td_read(td)) {
2011                                 if (td->sequential)
2012                                         c = 'R';
2013                                 else
2014                                         c = 'r';
2015                         } else {
2016                                 if (td->sequential)
2017                                         c = 'W';
2018                                 else
2019                                         c = 'w';
2020                         }
2021                         break;
2022                 case TD_VERIFYING:
2023                         c = 'V';
2024                         break;
2025                 case TD_CREATED:
2026                         c = 'C';
2027                         break;
2028                 case TD_INITIALIZED:
2029                         c = 'I';
2030                         break;
2031                 case TD_NOT_CREATED:
2032                         c = 'P';
2033                         break;
2034                 default:
2035                         printf("state %d\n", td->runstate);
2036         }
2037
2038         run_str[td->thread_number - 1] = c;
2039         td->old_runstate = td->runstate;
2040 }
2041
2042 static void eta_to_str(char *str, int eta_sec)
2043 {
2044         unsigned int d, h, m, s;
2045         static int always_d, always_h;
2046
2047         d = h = m = s = 0;
2048
2049         s = eta_sec % 60;
2050         eta_sec /= 60;
2051         m = eta_sec % 60;
2052         eta_sec /= 60;
2053         h = eta_sec % 24;
2054         eta_sec /= 24;
2055         d = eta_sec;
2056
2057         if (d || always_d) {
2058                 always_d = 1;
2059                 str += sprintf(str, "%02dd:", d);
2060         }
2061         if (h || always_h) {
2062                 always_h = 1;
2063                 str += sprintf(str, "%02dh:", h);
2064         }
2065
2066         str += sprintf(str, "%02dm:", m);
2067         str += sprintf(str, "%02ds", s);
2068 }
2069
2070 static int thread_eta(struct thread_data *td, unsigned long elapsed)
2071 {
2072         unsigned long long bytes_total, bytes_done;
2073         unsigned int eta_sec = 0;
2074
2075         bytes_total = td->total_io_size;
2076
2077         /*
2078          * if writing, bytes_total will be twice the size. If mixing,
2079          * assume a 50/50 split and thus bytes_total will be 50% larger.
2080          */
2081         if (td->verify) {
2082                 if (td_rw(td))
2083                         bytes_total = bytes_total * 3 / 2;
2084                 else
2085                         bytes_total <<= 1;
2086         }
2087         if (td->zone_size && td->zone_skip)
2088                 bytes_total /= (td->zone_skip / td->zone_size);
2089
2090         if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING) {
2091                 double perc;
2092
2093                 bytes_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE];
2094                 perc = (double) bytes_done / (double) bytes_total;
2095                 if (perc > 1.0)
2096                         perc = 1.0;
2097
2098                 eta_sec = (elapsed * (1.0 / perc)) - elapsed;
2099
2100                 if (td->timeout && eta_sec > (td->timeout - elapsed))
2101                         eta_sec = td->timeout - elapsed;
2102         } else if (td->runstate == TD_NOT_CREATED || td->runstate == TD_CREATED
2103                         || td->runstate == TD_INITIALIZED) {
2104                 int t_eta = 0, r_eta = 0;
2105
2106                 /*
2107                  * We can only guess - assume it'll run the full timeout
2108                  * if given, otherwise assume it'll run at the specified rate.
2109                  */
2110                 if (td->timeout)
2111                         t_eta = td->timeout + td->start_delay - elapsed;
2112                 if (td->rate) {
2113                         r_eta = (bytes_total / 1024) / td->rate;
2114                         r_eta += td->start_delay - elapsed;
2115                 }
2116
2117                 if (r_eta && t_eta)
2118                         eta_sec = min(r_eta, t_eta);
2119                 else if (r_eta)
2120                         eta_sec = r_eta;
2121                 else if (t_eta)
2122                         eta_sec = t_eta;
2123                 else
2124                         eta_sec = INT_MAX;
2125         } else {
2126                 /*
2127                  * thread is already done
2128                  */
2129                 eta_sec = 0;
2130         }
2131
2132         return eta_sec;
2133 }
2134
2135 static void print_thread_status(void)
2136 {
2137         unsigned long elapsed = time_since_now(&genesis);
2138         int i, nr_running, t_rate, m_rate, *eta_secs, eta_sec;
2139         char eta_str[32];
2140         double perc = 0.0;
2141
2142         eta_secs = malloc(thread_number * sizeof(int));
2143         memset(eta_secs, 0, thread_number * sizeof(int));
2144
2145         nr_running = t_rate = m_rate = 0;
2146         for (i = 0; i < thread_number; i++) {
2147                 struct thread_data *td = &threads[i];
2148
2149                 if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING){
2150                         nr_running++;
2151                         t_rate += td->rate;
2152                         m_rate += td->ratemin;
2153                 }
2154
2155                 if (elapsed >= 3)
2156                         eta_secs[i] = thread_eta(td, elapsed);
2157                 else
2158                         eta_secs[i] = INT_MAX;
2159
2160                 check_str_update(td);
2161         }
2162
2163         if (exitall_on_terminate)
2164                 eta_sec = INT_MAX;
2165         else
2166                 eta_sec = 0;
2167
2168         for (i = 0; i < thread_number; i++) {
2169                 if (exitall_on_terminate) {
2170                         if (eta_secs[i] < eta_sec)
2171                                 eta_sec = eta_secs[i];
2172                 } else {
2173                         if (eta_secs[i] > eta_sec)
2174                                 eta_sec = eta_secs[i];
2175                 }
2176         }
2177
2178         if (eta_sec != INT_MAX && elapsed) {
2179                 perc = (double) elapsed / (double) (elapsed + eta_sec);
2180                 eta_to_str(eta_str, eta_sec);
2181         }
2182
2183         printf("Threads now running (%d)", nr_running);
2184         if (m_rate || t_rate)
2185                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
2186         if (eta_sec != INT_MAX) {
2187                 perc *= 100.0;
2188                 printf(": [%s] [%3.2f%% done] [eta %s]", run_str, perc,eta_str);
2189         }
2190         printf("\r");
2191         fflush(stdout);
2192         free(eta_secs);
2193 }
2194
2195 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
2196 {
2197         int i;
2198
2199         /*
2200          * reap exited threads (TD_EXITED -> TD_REAPED)
2201          */
2202         for (i = 0; i < thread_number; i++) {
2203                 struct thread_data *td = &threads[i];
2204
2205                 if (td->runstate != TD_EXITED)
2206                         continue;
2207
2208                 td_set_runstate(td, TD_REAPED);
2209
2210                 if (td->use_thread) {
2211                         long ret;
2212
2213                         if (pthread_join(td->thread, (void *) &ret))
2214                                 perror("thread_join");
2215                 } else
2216                         waitpid(td->pid, NULL, 0);
2217
2218                 (*nr_running)--;
2219                 (*m_rate) -= td->ratemin;
2220                 (*t_rate) -= td->rate;
2221         }
2222 }
2223
2224 static void fio_unpin_memory(void *pinned)
2225 {
2226         if (pinned) {
2227                 if (munlock(pinned, mlock_size) < 0)
2228                         perror("munlock");
2229                 munmap(pinned, mlock_size);
2230         }
2231 }
2232
2233 static void *fio_pin_memory(void)
2234 {
2235         long pagesize, pages;
2236         void *ptr;
2237
2238         if (!mlock_size)
2239                 return NULL;
2240
2241         /*
2242          * Don't allow mlock of more than real_mem-128MB
2243          */
2244         pagesize = sysconf(_SC_PAGESIZE);
2245         pages = sysconf(_SC_PHYS_PAGES);
2246         if (pages != -1 && pagesize != -1) {
2247                 unsigned long long real_mem = pages * pagesize;
2248
2249                 if ((mlock_size + 128 * 1024 * 1024) > real_mem) {
2250                         mlock_size = real_mem - 128 * 1024 * 1024;
2251                         printf("fio: limiting mlocked memory to %lluMiB\n",
2252                                                         mlock_size >> 20);
2253                 }
2254         }
2255
2256         ptr = mmap(NULL, mlock_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
2257         if (!ptr) {
2258                 perror("malloc locked mem");
2259                 return NULL;
2260         }
2261         if (mlock(ptr, mlock_size) < 0) {
2262                 munmap(ptr, mlock_size);
2263                 perror("mlock");
2264                 return NULL;
2265         }
2266
2267         return ptr;
2268 }
2269
2270 static void run_threads(void)
2271 {
2272         struct thread_data *td;
2273         unsigned long spent;
2274         int i, todo, nr_running, m_rate, t_rate, nr_started;
2275         void *mlocked_mem;
2276
2277         mlocked_mem = fio_pin_memory();
2278
2279         printf("Starting %d thread%s\n", thread_number, thread_number > 1 ? "s" : "");
2280         fflush(stdout);
2281
2282         signal(SIGINT, sig_handler);
2283         signal(SIGALRM, sig_handler);
2284
2285         todo = thread_number;
2286         nr_running = 0;
2287         nr_started = 0;
2288         m_rate = t_rate = 0;
2289
2290         for (i = 0; i < thread_number; i++) {
2291                 td = &threads[i];
2292
2293                 run_str[td->thread_number - 1] = 'P';
2294
2295                 init_disk_util(td);
2296
2297                 if (!td->create_serialize)
2298                         continue;
2299
2300                 /*
2301                  * do file setup here so it happens sequentially,
2302                  * we don't want X number of threads getting their
2303                  * client data interspersed on disk
2304                  */
2305                 if (setup_file(td)) {
2306                         td_set_runstate(td, TD_REAPED);
2307                         todo--;
2308                 }
2309         }
2310
2311         gettimeofday(&genesis, NULL);
2312
2313         while (todo) {
2314                 struct thread_data *map[MAX_JOBS];
2315                 struct timeval this_start;
2316                 int this_jobs = 0, left;
2317
2318                 /*
2319                  * create threads (TD_NOT_CREATED -> TD_CREATED)
2320                  */
2321                 for (i = 0; i < thread_number; i++) {
2322                         td = &threads[i];
2323
2324                         if (td->runstate != TD_NOT_CREATED)
2325                                 continue;
2326
2327                         /*
2328                          * never got a chance to start, killed by other
2329                          * thread for some reason
2330                          */
2331                         if (td->terminate) {
2332                                 todo--;
2333                                 continue;
2334                         }
2335
2336                         if (td->start_delay) {
2337                                 spent = mtime_since_now(&genesis);
2338
2339                                 if (td->start_delay * 1000 > spent)
2340                                         continue;
2341                         }
2342
2343                         if (td->stonewall && (nr_started || nr_running))
2344                                 break;
2345
2346                         /*
2347                          * Set state to created. Thread will transition
2348                          * to TD_INITIALIZED when it's done setting up.
2349                          */
2350                         td_set_runstate(td, TD_CREATED);
2351                         map[this_jobs++] = td;
2352                         sem_init(&startup_sem, 0, 1);
2353                         nr_started++;
2354
2355                         if (td->use_thread) {
2356                                 if (pthread_create(&td->thread, NULL, thread_main, td)) {
2357                                         perror("thread_create");
2358                                         nr_started--;
2359                                 }
2360                         } else {
2361                                 if (fork())
2362                                         sem_wait(&startup_sem);
2363                                 else {
2364                                         fork_main(shm_id, i);
2365                                         exit(0);
2366                                 }
2367                         }
2368                 }
2369
2370                 /*
2371                  * Wait for the started threads to transition to
2372                  * TD_INITIALIZED.
2373                  */
2374                 printf("fio: Waiting for threads to initialize...\n");
2375                 gettimeofday(&this_start, NULL);
2376                 left = this_jobs;
2377                 while (left) {
2378                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
2379                                 break;
2380
2381                         usleep(100000);
2382
2383                         for (i = 0; i < this_jobs; i++) {
2384                                 td = map[i];
2385                                 if (!td)
2386                                         continue;
2387                                 if (td->runstate == TD_INITIALIZED) {
2388                                         map[i] = NULL;
2389                                         left--;
2390                                 } else if (td->runstate >= TD_EXITED) {
2391                                         map[i] = NULL;
2392                                         left--;
2393                                         todo--;
2394                                         nr_running++; /* work-around... */
2395                                 }
2396                         }
2397                 }
2398
2399                 if (left) {
2400                         fprintf(stderr, "fio: %d jobs failed to start\n", left);
2401                         for (i = 0; i < this_jobs; i++) {
2402                                 td = map[i];
2403                                 if (!td)
2404                                         continue;
2405                                 kill(td->pid, SIGTERM);
2406                         }
2407                         break;
2408                 }
2409
2410                 /*
2411                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
2412                  */
2413                 printf("fio: Go for launch\n");
2414                 for (i = 0; i < thread_number; i++) {
2415                         td = &threads[i];
2416
2417                         if (td->runstate != TD_INITIALIZED)
2418                                 continue;
2419
2420                         td_set_runstate(td, TD_RUNNING);
2421                         nr_running++;
2422                         nr_started--;
2423                         m_rate += td->ratemin;
2424                         t_rate += td->rate;
2425                         todo--;
2426                         sem_post(&td->mutex);
2427                 }
2428
2429                 reap_threads(&nr_running, &t_rate, &m_rate);
2430
2431                 if (todo)
2432                         usleep(100000);
2433         }
2434
2435         while (nr_running) {
2436                 reap_threads(&nr_running, &t_rate, &m_rate);
2437                 usleep(10000);
2438         }
2439
2440         update_io_ticks();
2441         fio_unpin_memory(mlocked_mem);
2442 }
2443
2444 static void show_group_stats(struct group_run_stats *rs, int id)
2445 {
2446         printf("\nRun status group %d (all jobs):\n", id);
2447
2448         if (rs->max_run[DDIR_READ])
2449                 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]);
2450         if (rs->max_run[DDIR_WRITE])
2451                 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]);
2452 }
2453
2454 static void show_disk_util(void)
2455 {
2456         struct disk_util_stat *dus;
2457         struct list_head *entry;
2458         struct disk_util *du;
2459         double util;
2460
2461         printf("\nDisk stats (read/write):\n");
2462
2463         list_for_each(entry, &disk_list) {
2464                 du = list_entry(entry, struct disk_util, list);
2465                 dus = &du->dus;
2466
2467                 util = (double) 100 * du->dus.io_ticks / (double) du->msec;
2468                 if (util > 100.0)
2469                         util = 100.0;
2470
2471                 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);
2472         }
2473 }
2474
2475 static void show_run_stats(void)
2476 {
2477         struct group_run_stats *runstats, *rs;
2478         struct thread_data *td;
2479         int i;
2480
2481         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
2482
2483         for (i = 0; i < groupid + 1; i++) {
2484                 rs = &runstats[i];
2485
2486                 memset(rs, 0, sizeof(*rs));
2487                 rs->min_bw[0] = rs->min_run[0] = ~0UL;
2488                 rs->min_bw[1] = rs->min_run[1] = ~0UL;
2489         }
2490
2491         for (i = 0; i < thread_number; i++) {
2492                 unsigned long long rbw, wbw;
2493
2494                 td = &threads[i];
2495
2496                 if (td->error) {
2497                         printf("Client%d: %s\n", td->thread_number, td->verror);
2498                         continue;
2499                 }
2500
2501                 rs = &runstats[td->groupid];
2502
2503                 if (td->runtime[0] < rs->min_run[0] || !rs->min_run[0])
2504                         rs->min_run[0] = td->runtime[0];
2505                 if (td->runtime[0] > rs->max_run[0])
2506                         rs->max_run[0] = td->runtime[0];
2507                 if (td->runtime[1] < rs->min_run[1] || !rs->min_run[1])
2508                         rs->min_run[1] = td->runtime[1];
2509                 if (td->runtime[1] > rs->max_run[1])
2510                         rs->max_run[1] = td->runtime[1];
2511
2512                 rbw = wbw = 0;
2513                 if (td->runtime[0])
2514                         rbw = td->io_bytes[0] / (unsigned long long) td->runtime[0];
2515                 if (td->runtime[1])
2516                         wbw = td->io_bytes[1] / (unsigned long long) td->runtime[1];
2517
2518                 if (rbw < rs->min_bw[0])
2519                         rs->min_bw[0] = rbw;
2520                 if (wbw < rs->min_bw[1])
2521                         rs->min_bw[1] = wbw;
2522                 if (rbw > rs->max_bw[0])
2523                         rs->max_bw[0] = rbw;
2524                 if (wbw > rs->max_bw[1])
2525                         rs->max_bw[1] = wbw;
2526
2527                 rs->io_mb[0] += td->io_bytes[0] >> 20;
2528                 rs->io_mb[1] += td->io_bytes[1] >> 20;
2529         }
2530
2531         for (i = 0; i < groupid + 1; i++) {
2532                 rs = &runstats[i];
2533
2534                 if (rs->max_run[0])
2535                         rs->agg[0] = (rs->io_mb[0]*1024*1000) / rs->max_run[0];
2536                 if (rs->max_run[1])
2537                         rs->agg[1] = (rs->io_mb[1]*1024*1000) / rs->max_run[1];
2538         }
2539
2540         /*
2541          * don't overwrite last signal output
2542          */
2543         printf("\n");
2544
2545         for (i = 0; i < thread_number; i++) {
2546                 td = &threads[i];
2547                 rs = &runstats[td->groupid];
2548
2549                 show_thread_status(td, rs);
2550         }
2551
2552         for (i = 0; i < groupid + 1; i++)
2553                 show_group_stats(&runstats[i], i);
2554
2555         show_disk_util();
2556 }
2557
2558 int main(int argc, char *argv[])
2559 {
2560         if (parse_options(argc, argv))
2561                 return 1;
2562
2563         if (!thread_number) {
2564                 printf("Nothing to do\n");
2565                 return 1;
2566         }
2567
2568         disk_util_timer_arm();
2569
2570         run_threads();
2571         show_run_stats();
2572
2573         return 0;
2574 }