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