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