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