65d94980cd2feca2c2050f390961c6a731a72dc1
[fio.git] / fio.c
1 /*
2  * fio - the flexible io tester
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <time.h>
26 #include <assert.h>
27 #include <sys/stat.h>
28 #include <sys/wait.h>
29 #include <sys/ipc.h>
30 #include <sys/shm.h>
31 #include <sys/ioctl.h>
32 #include <sys/mman.h>
33
34 #include "fio.h"
35 #include "os.h"
36
37 #define MASK    (4095)
38
39 #define ALIGN(buf)      (char *) (((unsigned long) (buf) + MASK) & ~(MASK))
40
41 int groupid = 0;
42 int thread_number = 0;
43 static char run_str[MAX_JOBS + 1];
44 int shm_id = 0;
45 static struct timeval genesis;
46
47 static void print_thread_status(void);
48
49 extern unsigned long long mlock_size;
50
51 /*
52  * Thread life cycle. Once a thread has a runstate beyond TD_INITIALIZED, it
53  * will never back again. It may cycle between running/verififying/fsyncing.
54  * Once the thread reaches TD_EXITED, it is just waiting for the core to
55  * reap it.
56  */
57 enum {
58         TD_NOT_CREATED = 0,
59         TD_CREATED,
60         TD_INITIALIZED,
61         TD_RUNNING,
62         TD_VERIFYING,
63         TD_FSYNCING,
64         TD_EXITED,
65         TD_REAPED,
66 };
67
68 #define should_fsync(td)        ((td_write(td) || td_rw(td)) && (!(td)->odirect || (td)->override_sync))
69
70 static volatile int startup_sem;
71
72 #define TERMINATE_ALL           (-1)
73 #define JOB_START_TIMEOUT       (5 * 1000)
74
75 static void terminate_threads(int group_id)
76 {
77         int i;
78
79         for (i = 0; i < thread_number; i++) {
80                 struct thread_data *td = &threads[i];
81
82                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
83                         td->terminate = 1;
84                         td->start_delay = 0;
85                 }
86         }
87 }
88
89 static void sig_handler(int sig)
90 {
91         switch (sig) {
92                 case SIGALRM:
93                         update_io_ticks();
94                         disk_util_timer_arm();
95                         print_thread_status();
96                         break;
97                 default:
98                         printf("\nfio: terminating on signal\n");
99                         fflush(stdout);
100                         terminate_threads(TERMINATE_ALL);
101                         break;
102         }
103 }
104
105 static int random_map_free(struct thread_data *td, unsigned long long block)
106 {
107         unsigned int idx = RAND_MAP_IDX(td, block);
108         unsigned int bit = RAND_MAP_BIT(td, block);
109
110         return (td->file_map[idx] & (1UL << bit)) == 0;
111 }
112
113 static int get_next_free_block(struct thread_data *td, unsigned long long *b)
114 {
115         int i;
116
117         *b = 0;
118         i = 0;
119         while ((*b) * td->min_bs < td->io_size) {
120                 if (td->file_map[i] != -1UL) {
121                         *b += ffz(td->file_map[i]);
122                         return 0;
123                 }
124
125                 *b += BLOCKS_PER_MAP;
126                 i++;
127         }
128
129         return 1;
130 }
131
132 static void mark_random_map(struct thread_data *td, struct io_u *io_u)
133 {
134         unsigned long long block = io_u->offset / (unsigned long long) td->min_bs;
135         unsigned int blocks = 0;
136
137         while (blocks < (io_u->buflen / td->min_bs)) {
138                 unsigned int idx, bit;
139
140                 if (!random_map_free(td, block))
141                         break;
142
143                 idx = RAND_MAP_IDX(td, block);
144                 bit = RAND_MAP_BIT(td, block);
145
146                 assert(idx < td->num_maps);
147
148                 td->file_map[idx] |= (1UL << bit);
149                 block++;
150                 blocks++;
151         }
152
153         if ((blocks * td->min_bs) < io_u->buflen)
154                 io_u->buflen = blocks * td->min_bs;
155 }
156
157 static int get_next_offset(struct thread_data *td, unsigned long long *offset)
158 {
159         unsigned long long b, rb;
160         long r;
161
162         if (!td->sequential) {
163                 unsigned long long max_blocks = td->io_size / td->min_bs;
164                 int loops = 50;
165
166                 do {
167                         r = os_random_long(&td->random_state);
168                         b = ((max_blocks - 1) * r / (unsigned long long) (RAND_MAX+1.0));
169                         rb = b + (td->file_offset / td->min_bs);
170                         loops--;
171                 } while (!random_map_free(td, rb) && loops);
172
173                 if (!loops) {
174                         if (get_next_free_block(td, &b))
175                                 return 1;
176                 }
177         } else
178                 b = td->last_pos / td->min_bs;
179
180         *offset = (b * td->min_bs) + td->file_offset;
181         if (*offset > td->real_file_size)
182                 return 1;
183
184         return 0;
185 }
186
187 static unsigned int get_next_buflen(struct thread_data *td)
188 {
189         unsigned int buflen;
190         long r;
191
192         if (td->min_bs == td->max_bs)
193                 buflen = td->min_bs;
194         else {
195                 r = os_random_long(&td->bsrange_state);
196                 buflen = (1 + (double) (td->max_bs - 1) * r / (RAND_MAX + 1.0));
197                 buflen = (buflen + td->min_bs - 1) & ~(td->min_bs - 1);
198         }
199
200         if (buflen > td->io_size - td->this_io_bytes[td->ddir])
201                 buflen = td->io_size - td->this_io_bytes[td->ddir];
202
203         return buflen;
204 }
205
206 static int check_min_rate(struct thread_data *td, struct timeval *now)
207 {
208         unsigned long spent;
209         unsigned long rate;
210         int ddir = td->ddir;
211
212         /*
213          * allow a 2 second settle period in the beginning
214          */
215         if (mtime_since(&td->start, now) < 2000)
216                 return 0;
217
218         /*
219          * if rate blocks is set, sample is running
220          */
221         if (td->rate_bytes) {
222                 spent = mtime_since(&td->lastrate, now);
223                 if (spent < td->ratecycle)
224                         return 0;
225
226                 rate = (td->this_io_bytes[ddir] - td->rate_bytes) / spent;
227                 if (rate < td->ratemin) {
228                         fprintf(f_out, "%s: min rate %d not met, got %ldKiB/sec\n", td->name, td->ratemin, rate);
229                         if (rate_quit)
230                                 terminate_threads(td->groupid);
231                         return 1;
232                 }
233         }
234
235         td->rate_bytes = td->this_io_bytes[ddir];
236         memcpy(&td->lastrate, now, sizeof(*now));
237         return 0;
238 }
239
240 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
241 {
242         if (!td->timeout)
243                 return 0;
244         if (mtime_since(&td->epoch, t) >= td->timeout * 1000)
245                 return 1;
246
247         return 0;
248 }
249
250 static void fill_random_bytes(struct thread_data *td,
251                               unsigned char *p, unsigned int len)
252 {
253         unsigned int todo;
254         double r;
255
256         while (len) {
257                 r = os_random_double(&td->verify_state);
258
259                 /*
260                  * lrand48_r seems to be broken and only fill the bottom
261                  * 32-bits, even on 64-bit archs with 64-bit longs
262                  */
263                 todo = sizeof(r);
264                 if (todo > len)
265                         todo = len;
266
267                 memcpy(p, &r, todo);
268
269                 len -= todo;
270                 p += todo;
271         }
272 }
273
274 static void hexdump(void *buffer, int len)
275 {
276         unsigned char *p = buffer;
277         int i;
278
279         for (i = 0; i < len; i++)
280                 fprintf(f_out, "%02x", p[i]);
281         fprintf(f_out, "\n");
282 }
283
284 static int verify_io_u_crc32(struct verify_header *hdr, struct io_u *io_u)
285 {
286         unsigned char *p = (unsigned char *) io_u->buf;
287         unsigned long c;
288
289         p += sizeof(*hdr);
290         c = crc32(p, hdr->len - sizeof(*hdr));
291
292         if (c != hdr->crc32) {
293                 log_err("crc32: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
294                 log_err("crc32: wanted %lx, got %lx\n", hdr->crc32, c);
295                 return 1;
296         }
297
298         return 0;
299 }
300
301 static int verify_io_u_md5(struct verify_header *hdr, struct io_u *io_u)
302 {
303         unsigned char *p = (unsigned char *) io_u->buf;
304         struct md5_ctx md5_ctx;
305
306         memset(&md5_ctx, 0, sizeof(md5_ctx));
307         p += sizeof(*hdr);
308         md5_update(&md5_ctx, p, hdr->len - sizeof(*hdr));
309
310         if (memcmp(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash))) {
311                 log_err("md5: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
312                 hexdump(hdr->md5_digest, sizeof(hdr->md5_digest));
313                 hexdump(md5_ctx.hash, sizeof(md5_ctx.hash));
314                 return 1;
315         }
316
317         return 0;
318 }
319
320 static int verify_io_u(struct io_u *io_u)
321 {
322         struct verify_header *hdr = (struct verify_header *) io_u->buf;
323         int ret;
324
325         if (hdr->fio_magic != FIO_HDR_MAGIC)
326                 return 1;
327
328         if (hdr->verify_type == VERIFY_MD5)
329                 ret = verify_io_u_md5(hdr, io_u);
330         else if (hdr->verify_type == VERIFY_CRC32)
331                 ret = verify_io_u_crc32(hdr, io_u);
332         else {
333                 log_err("Bad verify type %d\n", hdr->verify_type);
334                 ret = 1;
335         }
336
337         return ret;
338 }
339
340 static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
341 {
342         hdr->crc32 = crc32(p, len);
343 }
344
345 static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
346 {
347         struct md5_ctx md5_ctx;
348
349         memset(&md5_ctx, 0, sizeof(md5_ctx));
350         md5_update(&md5_ctx, p, len);
351         memcpy(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
352 }
353
354 static int get_rw_ddir(struct thread_data *td)
355 {
356         if (td_rw(td)) {
357                 struct timeval now;
358                 unsigned long elapsed;
359
360                 gettimeofday(&now, NULL);
361                 elapsed = mtime_since_now(&td->rwmix_switch);
362
363                 /*
364                  * Check if it's time to seed a new data direction.
365                  */
366                 if (elapsed >= td->rwmixcycle) {
367                         int v;
368                         long r;
369
370                         r = os_random_long(&td->rwmix_state);
371                         v = 1 + (int) (100.0 * (r / (RAND_MAX + 1.0)));
372                         if (v < td->rwmixread)
373                                 td->rwmix_ddir = DDIR_READ;
374                         else
375                                 td->rwmix_ddir = DDIR_WRITE;
376                         memcpy(&td->rwmix_switch, &now, sizeof(now));
377                 }
378                 return td->rwmix_ddir;
379         } else if (td_read(td))
380                 return DDIR_READ;
381         else
382                 return DDIR_WRITE;
383 }
384
385 /*
386  * fill body of io_u->buf with random data and add a header with the
387  * crc32 or md5 sum of that data.
388  */
389 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
390 {
391         unsigned char *p = (unsigned char *) io_u->buf;
392         struct verify_header hdr;
393
394         hdr.fio_magic = FIO_HDR_MAGIC;
395         hdr.len = io_u->buflen;
396         p += sizeof(hdr);
397         fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
398
399         if (td->verify == VERIFY_MD5) {
400                 fill_md5(&hdr, p, io_u->buflen - sizeof(hdr));
401                 hdr.verify_type = VERIFY_MD5;
402         } else {
403                 fill_crc32(&hdr, p, io_u->buflen - sizeof(hdr));
404                 hdr.verify_type = VERIFY_CRC32;
405         }
406
407         memcpy(io_u->buf, &hdr, sizeof(hdr));
408 }
409
410 static int td_io_prep(struct thread_data *td, struct io_u *io_u)
411 {
412         if (td->io_prep && td->io_prep(td, io_u))
413                 return 1;
414
415         return 0;
416 }
417
418 void put_io_u(struct thread_data *td, struct io_u *io_u)
419 {
420         list_del(&io_u->list);
421         list_add(&io_u->list, &td->io_u_freelist);
422         td->cur_depth--;
423 }
424
425 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
426 {
427         /*
428          * If using an iolog, grab next piece if any available.
429          */
430         if (td->read_iolog)
431                 return read_iolog_get(td, io_u);
432
433         /*
434          * No log, let the seq/rand engine retrieve the next position.
435          */
436         if (!get_next_offset(td, &io_u->offset)) {
437                 io_u->buflen = get_next_buflen(td);
438
439                 if (io_u->buflen) {
440                         io_u->ddir = get_rw_ddir(td);
441
442                         /*
443                          * If using a write iolog, store this entry.
444                          */
445                         if (td->write_iolog)
446                                 write_iolog_put(td, io_u);
447
448                         return 0;
449                 }
450         }
451
452         return 1;
453 }
454
455 #define queue_full(td)  list_empty(&(td)->io_u_freelist)
456
457 struct io_u *__get_io_u(struct thread_data *td)
458 {
459         struct io_u *io_u = NULL;
460
461         if (!queue_full(td)) {
462                 io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
463
464                 io_u->error = 0;
465                 io_u->resid = 0;
466                 list_del(&io_u->list);
467                 list_add(&io_u->list, &td->io_u_busylist);
468                 td->cur_depth++;
469         }
470
471         return io_u;
472 }
473
474 static struct io_u *get_io_u(struct thread_data *td)
475 {
476         struct io_u *io_u;
477
478         io_u = __get_io_u(td);
479         if (!io_u)
480                 return NULL;
481
482         if (td->zone_bytes >= td->zone_size) {
483                 td->zone_bytes = 0;
484                 td->last_pos += td->zone_skip;
485         }
486
487         if (fill_io_u(td, io_u)) {
488                 put_io_u(td, io_u);
489                 return NULL;
490         }
491
492         if (io_u->buflen + io_u->offset > td->real_file_size)
493                 io_u->buflen = td->real_file_size - io_u->offset;
494
495         if (!io_u->buflen) {
496                 put_io_u(td, io_u);
497                 return NULL;
498         }
499
500         if (!td->read_iolog && !td->sequential)
501                 mark_random_map(td, io_u);
502
503         td->last_pos += io_u->buflen;
504
505         if (td->verify != VERIFY_NONE)
506                 populate_io_u(td, io_u);
507
508         if (td_io_prep(td, io_u)) {
509                 put_io_u(td, io_u);
510                 return NULL;
511         }
512
513         gettimeofday(&io_u->start_time, NULL);
514         return io_u;
515 }
516
517 static inline void td_set_runstate(struct thread_data *td, int runstate)
518 {
519         td->runstate = runstate;
520 }
521
522 static int get_next_verify(struct thread_data *td, struct io_u *io_u)
523 {
524         struct io_piece *ipo;
525
526         if (!list_empty(&td->io_hist_list)) {
527                 ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
528
529                 list_del(&ipo->list);
530
531                 io_u->offset = ipo->offset;
532                 io_u->buflen = ipo->len;
533                 io_u->ddir = DDIR_READ;
534                 free(ipo);
535                 return 0;
536         }
537
538         return 1;
539 }
540
541 static int sync_td(struct thread_data *td)
542 {
543         if (td->io_sync)
544                 return td->io_sync(td);
545
546         return 0;
547 }
548
549 static int io_u_getevents(struct thread_data *td, int min, int max,
550                           struct timespec *t)
551 {
552         return td->io_getevents(td, min, max, t);
553 }
554
555 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
556 {
557         gettimeofday(&io_u->issue_time, NULL);
558
559         return td->io_queue(td, io_u);
560 }
561
562 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
563
564 static void io_completed(struct thread_data *td, struct io_u *io_u,
565                          struct io_completion_data *icd)
566 {
567         struct timeval e;
568         unsigned long msec;
569
570         gettimeofday(&e, NULL);
571
572         if (!io_u->error) {
573                 unsigned int bytes = io_u->buflen - io_u->resid;
574                 const int idx = io_u->ddir;
575
576                 td->io_blocks[idx]++;
577                 td->io_bytes[idx] += bytes;
578                 td->zone_bytes += bytes;
579                 td->this_io_bytes[idx] += bytes;
580
581                 msec = mtime_since(&io_u->issue_time, &e);
582
583                 add_clat_sample(td, idx, msec);
584                 add_bw_sample(td, idx);
585
586                 if ((td_rw(td) || td_write(td)) && idx == DDIR_WRITE)
587                         log_io_piece(td, io_u);
588
589                 icd->bytes_done[idx] += bytes;
590         } else
591                 icd->error = io_u->error;
592 }
593
594 static void ios_completed(struct thread_data *td,struct io_completion_data *icd)
595 {
596         struct io_u *io_u;
597         int i;
598
599         icd->error = 0;
600         icd->bytes_done[0] = icd->bytes_done[1] = 0;
601
602         for (i = 0; i < icd->nr; i++) {
603                 io_u = td->io_event(td, i);
604
605                 io_completed(td, io_u, icd);
606                 put_io_u(td, io_u);
607         }
608 }
609
610 static void cleanup_pending_aio(struct thread_data *td)
611 {
612         struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
613         struct list_head *entry, *n;
614         struct io_completion_data icd;
615         struct io_u *io_u;
616         int r;
617
618         /*
619          * get immediately available events, if any
620          */
621         r = io_u_getevents(td, 0, td->cur_depth, &ts);
622         if (r > 0) {
623                 icd.nr = r;
624                 ios_completed(td, &icd);
625         }
626
627         /*
628          * now cancel remaining active events
629          */
630         if (td->io_cancel) {
631                 list_for_each_safe(entry, n, &td->io_u_busylist) {
632                         io_u = list_entry(entry, struct io_u, list);
633
634                         r = td->io_cancel(td, io_u);
635                         if (!r)
636                                 put_io_u(td, io_u);
637                 }
638         }
639
640         if (td->cur_depth) {
641                 r = io_u_getevents(td, td->cur_depth, td->cur_depth, NULL);
642                 if (r > 0) {
643                         icd.nr = r;
644                         ios_completed(td, &icd);
645                 }
646         }
647 }
648
649 static int do_io_u_verify(struct thread_data *td, struct io_u **io_u)
650 {
651         struct io_u *v_io_u = *io_u;
652         int ret = 0;
653
654         if (v_io_u) {
655                 ret = verify_io_u(v_io_u);
656                 put_io_u(td, v_io_u);
657                 *io_u = NULL;
658         }
659
660         return ret;
661 }
662
663 static void do_verify(struct thread_data *td)
664 {
665         struct timeval t;
666         struct io_u *io_u, *v_io_u = NULL;
667         struct io_completion_data icd;
668         int ret;
669
670         td_set_runstate(td, TD_VERIFYING);
671
672         do {
673                 if (td->terminate)
674                         break;
675
676                 gettimeofday(&t, NULL);
677                 if (runtime_exceeded(td, &t))
678                         break;
679
680                 io_u = __get_io_u(td);
681                 if (!io_u)
682                         break;
683
684                 if (get_next_verify(td, io_u)) {
685                         put_io_u(td, io_u);
686                         break;
687                 }
688
689                 if (td_io_prep(td, io_u)) {
690                         put_io_u(td, io_u);
691                         break;
692                 }
693
694                 ret = io_u_queue(td, io_u);
695                 if (ret) {
696                         put_io_u(td, io_u);
697                         td_verror(td, ret);
698                         break;
699                 }
700
701                 /*
702                  * we have one pending to verify, do that while
703                  * we are doing io on the next one
704                  */
705                 if (do_io_u_verify(td, &v_io_u))
706                         break;
707
708                 ret = io_u_getevents(td, 1, 1, NULL);
709                 if (ret != 1) {
710                         if (ret < 0)
711                                 td_verror(td, ret);
712                         break;
713                 }
714
715                 v_io_u = td->io_event(td, 0);
716                 icd.nr = 1;
717                 icd.error = 0;
718                 io_completed(td, v_io_u, &icd);
719
720                 if (icd.error) {
721                         td_verror(td, icd.error);
722                         put_io_u(td, v_io_u);
723                         v_io_u = NULL;
724                         break;
725                 }
726
727                 /*
728                  * if we can't submit more io, we need to verify now
729                  */
730                 if (queue_full(td) && do_io_u_verify(td, &v_io_u))
731                         break;
732
733         } while (1);
734
735         do_io_u_verify(td, &v_io_u);
736
737         if (td->cur_depth)
738                 cleanup_pending_aio(td);
739
740         td_set_runstate(td, TD_RUNNING);
741 }
742
743 /*
744  * Main IO worker functions. It retrieves io_u's to process and queues
745  * and reaps them, checking for rate and errors along the way.
746  */
747 static void do_io(struct thread_data *td)
748 {
749         struct io_completion_data icd;
750         struct timeval s, e;
751         unsigned long usec;
752
753         td_set_runstate(td, TD_RUNNING);
754
755         while (td->this_io_bytes[td->ddir] < td->io_size) {
756                 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
757                 struct timespec *timeout;
758                 int ret, min_evts = 0;
759                 struct io_u *io_u;
760
761                 if (td->terminate)
762                         break;
763
764                 io_u = get_io_u(td);
765                 if (!io_u)
766                         break;
767
768                 memcpy(&s, &io_u->start_time, sizeof(s));
769
770                 ret = io_u_queue(td, io_u);
771                 if (ret) {
772                         put_io_u(td, io_u);
773                         td_verror(td, ret);
774                         break;
775                 }
776
777                 add_slat_sample(td, io_u->ddir, mtime_since(&io_u->start_time, &io_u->issue_time));
778
779                 if (td->cur_depth < td->iodepth) {
780                         timeout = &ts;
781                         min_evts = 0;
782                 } else {
783                         timeout = NULL;
784                         min_evts = 1;
785                 }
786
787                 ret = io_u_getevents(td, min_evts, td->cur_depth, timeout);
788                 if (ret < 0) {
789                         td_verror(td, ret);
790                         break;
791                 } else if (!ret)
792                         continue;
793
794                 icd.nr = ret;
795                 ios_completed(td, &icd);
796                 if (icd.error) {
797                         td_verror(td, icd.error);
798                         break;
799                 }
800
801                 /*
802                  * the rate is batched for now, it should work for batches
803                  * of completions except the very first one which may look
804                  * a little bursty
805                  */
806                 gettimeofday(&e, NULL);
807                 usec = utime_since(&s, &e);
808
809                 rate_throttle(td, usec, icd.bytes_done[td->ddir]);
810
811                 if (check_min_rate(td, &e)) {
812                         td_verror(td, ENOMEM);
813                         break;
814                 }
815
816                 if (runtime_exceeded(td, &e))
817                         break;
818
819                 if (td->thinktime)
820                         usec_sleep(td, td->thinktime);
821
822                 if (should_fsync(td) && td->fsync_blocks &&
823                     (td->io_blocks[DDIR_WRITE] % td->fsync_blocks) == 0)
824                         sync_td(td);
825         }
826
827         if (td->cur_depth)
828                 cleanup_pending_aio(td);
829
830         if (should_fsync(td) && td->end_fsync) {
831                 td_set_runstate(td, TD_FSYNCING);
832                 sync_td(td);
833         }
834 }
835
836 static void cleanup_io(struct thread_data *td)
837 {
838         if (td->io_cleanup)
839                 td->io_cleanup(td);
840 }
841
842 static int init_io(struct thread_data *td)
843 {
844         if (td->io_engine == FIO_SYNCIO)
845                 return fio_syncio_init(td);
846         else if (td->io_engine == FIO_MMAPIO)
847                 return fio_mmapio_init(td);
848         else if (td->io_engine == FIO_LIBAIO)
849                 return fio_libaio_init(td);
850         else if (td->io_engine == FIO_POSIXAIO)
851                 return fio_posixaio_init(td);
852         else if (td->io_engine == FIO_SGIO)
853                 return fio_sgio_init(td);
854         else if (td->io_engine == FIO_SPLICEIO)
855                 return fio_spliceio_init(td);
856         else {
857                 log_err("bad io_engine %d\n", td->io_engine);
858                 return 1;
859         }
860 }
861
862 static void cleanup_io_u(struct thread_data *td)
863 {
864         struct list_head *entry, *n;
865         struct io_u *io_u;
866
867         list_for_each_safe(entry, n, &td->io_u_freelist) {
868                 io_u = list_entry(entry, struct io_u, list);
869
870                 list_del(&io_u->list);
871                 free(io_u);
872         }
873
874         if (td->mem_type == MEM_MALLOC)
875                 free(td->orig_buffer);
876         else if (td->mem_type == MEM_SHM) {
877                 struct shmid_ds sbuf;
878
879                 shmdt(td->orig_buffer);
880                 shmctl(td->shm_id, IPC_RMID, &sbuf);
881         } else if (td->mem_type == MEM_MMAP)
882                 munmap(td->orig_buffer, td->orig_buffer_size);
883         else
884                 log_err("Bad memory type %d\n", td->mem_type);
885
886         td->orig_buffer = NULL;
887 }
888
889 static int init_io_u(struct thread_data *td)
890 {
891         struct io_u *io_u;
892         int i, max_units;
893         char *p;
894
895         if (td->io_engine & FIO_SYNCIO)
896                 max_units = 1;
897         else
898                 max_units = td->iodepth;
899
900         td->orig_buffer_size = td->max_bs * max_units + MASK;
901
902         if (td->mem_type == MEM_MALLOC)
903                 td->orig_buffer = malloc(td->orig_buffer_size);
904         else if (td->mem_type == MEM_SHM) {
905                 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
906                 if (td->shm_id < 0) {
907                         td_verror(td, errno);
908                         perror("shmget");
909                         return 1;
910                 }
911
912                 td->orig_buffer = shmat(td->shm_id, NULL, 0);
913                 if (td->orig_buffer == (void *) -1) {
914                         td_verror(td, errno);
915                         perror("shmat");
916                         td->orig_buffer = NULL;
917                         return 1;
918                 }
919         } else if (td->mem_type == MEM_MMAP) {
920                 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
921                 if (td->orig_buffer == MAP_FAILED) {
922                         td_verror(td, errno);
923                         perror("mmap");
924                         td->orig_buffer = NULL;
925                         return 1;
926                 }
927         }
928
929         p = ALIGN(td->orig_buffer);
930         for (i = 0; i < max_units; i++) {
931                 io_u = malloc(sizeof(*io_u));
932                 memset(io_u, 0, sizeof(*io_u));
933                 INIT_LIST_HEAD(&io_u->list);
934
935                 io_u->buf = p + td->max_bs * i;
936                 io_u->index = i;
937                 list_add(&io_u->list, &td->io_u_freelist);
938         }
939
940         return 0;
941 }
942
943 static int create_file(struct thread_data *td, unsigned long long size,
944                        int extend)
945 {
946         unsigned long long left;
947         unsigned int bs;
948         int r, oflags;
949         char *b;
950
951         /*
952          * unless specifically asked for overwrite, let normal io extend it
953          */
954         if (td_write(td) && !td->overwrite)
955                 return 0;
956
957         if (!size) {
958                 log_err("Need size for create\n");
959                 td_verror(td, EINVAL);
960                 return 1;
961         }
962
963         if (!extend) {
964                 oflags = O_CREAT | O_TRUNC;
965                 fprintf(f_out, "%s: Laying out IO file (%LuMiB)\n", td->name, size >> 20);
966         } else {
967                 oflags = O_APPEND;
968                 fprintf(f_out, "%s: Extending IO file (%Lu -> %LuMiB)\n", td->name, (td->file_size - size) >> 20, td->file_size >> 20);
969         }
970
971         td->fd = open(td->file_name, O_WRONLY | oflags, 0644);
972         if (td->fd < 0) {
973                 td_verror(td, errno);
974                 return 1;
975         }
976
977         if (!extend && ftruncate(td->fd, td->file_size) == -1) {
978                 td_verror(td, errno);
979                 return 1;
980         }
981
982         td->io_size = td->file_size;
983         b = malloc(td->max_bs);
984         memset(b, 0, td->max_bs);
985
986         left = size;
987         while (left && !td->terminate) {
988                 bs = td->max_bs;
989                 if (bs > left)
990                         bs = left;
991
992                 r = write(td->fd, b, bs);
993
994                 if (r == (int) bs) {
995                         left -= bs;
996                         continue;
997                 } else {
998                         if (r < 0)
999                                 td_verror(td, errno);
1000                         else
1001                                 td_verror(td, EIO);
1002
1003                         break;
1004                 }
1005         }
1006
1007         if (td->terminate)
1008                 unlink(td->file_name);
1009         else if (td->create_fsync)
1010                 fsync(td->fd);
1011
1012         close(td->fd);
1013         td->fd = -1;
1014         free(b);
1015         return 0;
1016 }
1017
1018 static int file_size(struct thread_data *td)
1019 {
1020         struct stat st;
1021
1022         if (fstat(td->fd, &st) == -1) {
1023                 td_verror(td, errno);
1024                 return 1;
1025         }
1026
1027         td->real_file_size = st.st_size;
1028
1029         if (!td->file_size || td->file_size > td->real_file_size)
1030                 td->file_size = td->real_file_size;
1031
1032         td->file_size -= td->file_offset;
1033         return 0;
1034 }
1035
1036 static int bdev_size(struct thread_data *td)
1037 {
1038         unsigned long long bytes;
1039         int r;
1040
1041         r = blockdev_size(td->fd, &bytes);
1042         if (r) {
1043                 td_verror(td, r);
1044                 return 1;
1045         }
1046
1047         td->real_file_size = bytes;
1048
1049         /*
1050          * no extend possibilities, so limit size to device size if too large
1051          */
1052         if (!td->file_size || td->file_size > td->real_file_size)
1053                 td->file_size = td->real_file_size;
1054
1055         td->file_size -= td->file_offset;
1056         return 0;
1057 }
1058
1059 static int get_file_size(struct thread_data *td)
1060 {
1061         int ret = 0;
1062
1063         if (td->filetype == FIO_TYPE_FILE)
1064                 ret = file_size(td);
1065         else if (td->filetype == FIO_TYPE_BD)
1066                 ret = bdev_size(td);
1067         else
1068                 td->real_file_size = -1;
1069
1070         if (ret)
1071                 return ret;
1072
1073         if (td->file_offset > td->real_file_size) {
1074                 log_err("%s: offset extends end (%Lu > %Lu)\n", td->name, td->file_offset, td->real_file_size);
1075                 return 1;
1076         }
1077
1078         td->io_size = td->file_size;
1079         if (td->io_size == 0) {
1080                 log_err("%s: no io blocks\n", td->name);
1081                 td_verror(td, EINVAL);
1082                 return 1;
1083         }
1084
1085         if (!td->zone_size)
1086                 td->zone_size = td->io_size;
1087
1088         td->total_io_size = td->io_size * td->loops;
1089         return 0;
1090 }
1091
1092 static int setup_file_mmap(struct thread_data *td)
1093 {
1094         int flags;
1095
1096         if (td_rw(td))
1097                 flags = PROT_READ | PROT_WRITE;
1098         else if (td_write(td)) {
1099                 flags = PROT_WRITE;
1100
1101                 if (td->verify != VERIFY_NONE)
1102                         flags |= PROT_READ;
1103         } else
1104                 flags = PROT_READ;
1105
1106         td->mmap = mmap(NULL, td->file_size, flags, MAP_SHARED, td->fd, td->file_offset);
1107         if (td->mmap == MAP_FAILED) {
1108                 td->mmap = NULL;
1109                 td_verror(td, errno);
1110                 return 1;
1111         }
1112
1113         if (td->invalidate_cache) {
1114                 if (madvise(td->mmap, td->file_size, MADV_DONTNEED) < 0) {
1115                         td_verror(td, errno);
1116                         return 1;
1117                 }
1118         }
1119
1120         if (td->sequential) {
1121                 if (madvise(td->mmap, td->file_size, MADV_SEQUENTIAL) < 0) {
1122                         td_verror(td, errno);
1123                         return 1;
1124                 }
1125         } else {
1126                 if (madvise(td->mmap, td->file_size, MADV_RANDOM) < 0) {
1127                         td_verror(td, errno);
1128                         return 1;
1129                 }
1130         }
1131
1132         return 0;
1133 }
1134
1135 static int setup_file_plain(struct thread_data *td)
1136 {
1137         if (td->invalidate_cache) {
1138                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_DONTNEED) < 0) {
1139                         td_verror(td, errno);
1140                         return 1;
1141                 }
1142         }
1143
1144         if (td->sequential) {
1145                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_SEQUENTIAL) < 0) {
1146                         td_verror(td, errno);
1147                         return 1;
1148                 }
1149         } else {
1150                 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_RANDOM) < 0) {
1151                         td_verror(td, errno);
1152                         return 1;
1153                 }
1154         }
1155
1156         return 0;
1157 }
1158
1159 static int setup_file(struct thread_data *td)
1160 {
1161         struct stat st;
1162         int flags = 0;
1163
1164         if (stat(td->file_name, &st) == -1) {
1165                 if (errno != ENOENT) {
1166                         td_verror(td, errno);
1167                         return 1;
1168                 }
1169                 if (!td->create_file) {
1170                         td_verror(td, ENOENT);
1171                         return 1;
1172                 }
1173                 if (create_file(td, td->file_size, 0))
1174                         return 1;
1175         } else if (td->filetype == FIO_TYPE_FILE) {
1176                 if (st.st_size < (off_t) td->file_size) {
1177                         if (create_file(td, td->file_size - st.st_size, 1))
1178                                 return 1;
1179                 }
1180         }
1181
1182         if (td->odirect)
1183                 flags |= OS_O_DIRECT;
1184
1185         if (td_write(td) || td_rw(td)) {
1186                 if (td->filetype == FIO_TYPE_FILE) {
1187                         if (!td->overwrite)
1188                                 flags |= O_TRUNC;
1189
1190                         flags |= O_CREAT;
1191                 }
1192                 if (td->sync_io)
1193                         flags |= O_SYNC;
1194
1195                 flags |= O_RDWR;
1196
1197                 td->fd = open(td->file_name, flags, 0600);
1198         } else {
1199                 if (td->filetype == FIO_TYPE_CHAR)
1200                         flags |= O_RDWR;
1201                 else
1202                         flags |= O_RDONLY;
1203
1204                 td->fd = open(td->file_name, flags);
1205         }
1206
1207         if (td->fd == -1) {
1208                 td_verror(td, errno);
1209                 return 1;
1210         }
1211
1212         if (get_file_size(td))
1213                 return 1;
1214
1215         if (td->io_engine != FIO_MMAPIO)
1216                 return setup_file_plain(td);
1217         else
1218                 return setup_file_mmap(td);
1219 }
1220
1221 static int switch_ioscheduler(struct thread_data *td)
1222 {
1223         char tmp[256], tmp2[128];
1224         FILE *f;
1225         int ret;
1226
1227         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
1228
1229         f = fopen(tmp, "r+");
1230         if (!f) {
1231                 td_verror(td, errno);
1232                 return 1;
1233         }
1234
1235         /*
1236          * Set io scheduler.
1237          */
1238         ret = fwrite(td->ioscheduler, strlen(td->ioscheduler), 1, f);
1239         if (ferror(f) || ret != 1) {
1240                 td_verror(td, errno);
1241                 fclose(f);
1242                 return 1;
1243         }
1244
1245         rewind(f);
1246
1247         /*
1248          * Read back and check that the selected scheduler is now the default.
1249          */
1250         ret = fread(tmp, 1, sizeof(tmp), f);
1251         if (ferror(f) || ret < 0) {
1252                 td_verror(td, errno);
1253                 fclose(f);
1254                 return 1;
1255         }
1256
1257         sprintf(tmp2, "[%s]", td->ioscheduler);
1258         if (!strstr(tmp, tmp2)) {
1259                 log_err("fio: io scheduler %s not found\n", td->ioscheduler);
1260                 td_verror(td, EINVAL);
1261                 fclose(f);
1262                 return 1;
1263         }
1264
1265         fclose(f);
1266         return 0;
1267 }
1268
1269 static void clear_io_state(struct thread_data *td)
1270 {
1271         if (td->io_engine == FIO_SYNCIO)
1272                 lseek(td->fd, SEEK_SET, 0);
1273
1274         td->last_pos = 0;
1275         td->stat_io_bytes[0] = td->stat_io_bytes[1] = 0;
1276         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
1277         td->zone_bytes = 0;
1278
1279         if (td->file_map)
1280                 memset(td->file_map, 0, td->num_maps * sizeof(long));
1281 }
1282
1283 static void *thread_main(void *data)
1284 {
1285         struct thread_data *td = data;
1286
1287         if (!td->use_thread)
1288                 setsid();
1289
1290         td->pid = getpid();
1291
1292         INIT_LIST_HEAD(&td->io_u_freelist);
1293         INIT_LIST_HEAD(&td->io_u_busylist);
1294         INIT_LIST_HEAD(&td->io_hist_list);
1295         INIT_LIST_HEAD(&td->io_log_list);
1296
1297         if (init_io_u(td))
1298                 goto err;
1299
1300         if (fio_setaffinity(td) == -1) {
1301                 td_verror(td, errno);
1302                 goto err;
1303         }
1304
1305         if (init_io(td))
1306                 goto err;
1307
1308         if (init_iolog(td))
1309                 goto err;
1310
1311         if (td->ioprio) {
1312                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1313                         td_verror(td, errno);
1314                         goto err;
1315                 }
1316         }
1317
1318         if (nice(td->nice) < 0) {
1319                 td_verror(td, errno);
1320                 goto err;
1321         }
1322
1323         if (init_random_state(td))
1324                 goto err;
1325
1326         if (td->ioscheduler && switch_ioscheduler(td))
1327                 goto err;
1328
1329         td_set_runstate(td, TD_INITIALIZED);
1330         fio_sem_up(&startup_sem);
1331         fio_sem_down(&td->mutex);
1332
1333         if (!td->create_serialize && setup_file(td))
1334                 goto err;
1335
1336         gettimeofday(&td->epoch, NULL);
1337
1338         if (td->exec_prerun)
1339                 system(td->exec_prerun);
1340
1341         while (td->loops--) {
1342                 getrusage(RUSAGE_SELF, &td->ru_start);
1343                 gettimeofday(&td->start, NULL);
1344                 memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1345
1346                 if (td->ratemin)
1347                         memcpy(&td->lastrate, &td->stat_sample_time, sizeof(td->lastrate));
1348
1349                 clear_io_state(td);
1350                 prune_io_piece_log(td);
1351
1352                 do_io(td);
1353
1354                 td->runtime[td->ddir] += mtime_since_now(&td->start);
1355                 if (td_rw(td) && td->io_bytes[td->ddir ^ 1])
1356                         td->runtime[td->ddir ^ 1] = td->runtime[td->ddir];
1357
1358                 update_rusage_stat(td);
1359
1360                 if (td->error || td->terminate)
1361                         break;
1362
1363                 if (td->verify == VERIFY_NONE)
1364                         continue;
1365
1366                 clear_io_state(td);
1367                 gettimeofday(&td->start, NULL);
1368
1369                 do_verify(td);
1370
1371                 td->runtime[DDIR_READ] += mtime_since_now(&td->start);
1372
1373                 if (td->error || td->terminate)
1374                         break;
1375         }
1376
1377         if (td->bw_log)
1378                 finish_log(td, td->bw_log, "bw");
1379         if (td->slat_log)
1380                 finish_log(td, td->slat_log, "slat");
1381         if (td->clat_log)
1382                 finish_log(td, td->clat_log, "clat");
1383         if (td->write_iolog)
1384                 write_iolog_close(td);
1385         if (td->exec_postrun)
1386                 system(td->exec_postrun);
1387
1388         if (exitall_on_terminate)
1389                 terminate_threads(td->groupid);
1390
1391 err:
1392         if (td->fd != -1) {
1393                 close(td->fd);
1394                 td->fd = -1;
1395         }
1396         if (td->mmap)
1397                 munmap(td->mmap, td->file_size);
1398         cleanup_io(td);
1399         cleanup_io_u(td);
1400         td_set_runstate(td, TD_EXITED);
1401         return NULL;
1402
1403 }
1404
1405 static void *fork_main(int shmid, int offset)
1406 {
1407         struct thread_data *td;
1408         void *data;
1409
1410         data = shmat(shmid, NULL, 0);
1411         if (data == (void *) -1) {
1412                 perror("shmat");
1413                 return NULL;
1414         }
1415
1416         td = data + offset * sizeof(struct thread_data);
1417         thread_main(td);
1418         shmdt(data);
1419         return NULL;
1420 }
1421
1422 static void check_str_update(struct thread_data *td)
1423 {
1424         char c = run_str[td->thread_number - 1];
1425
1426         switch (td->runstate) {
1427                 case TD_REAPED:
1428                         c = '_';
1429                         break;
1430                 case TD_EXITED:
1431                         c = 'E';
1432                         break;
1433                 case TD_RUNNING:
1434                         if (td_rw(td)) {
1435                                 if (td->sequential)
1436                                         c = 'M';
1437                                 else
1438                                         c = 'm';
1439                         } else if (td_read(td)) {
1440                                 if (td->sequential)
1441                                         c = 'R';
1442                                 else
1443                                         c = 'r';
1444                         } else {
1445                                 if (td->sequential)
1446                                         c = 'W';
1447                                 else
1448                                         c = 'w';
1449                         }
1450                         break;
1451                 case TD_VERIFYING:
1452                         c = 'V';
1453                         break;
1454                 case TD_FSYNCING:
1455                         c = 'F';
1456                         break;
1457                 case TD_CREATED:
1458                         c = 'C';
1459                         break;
1460                 case TD_INITIALIZED:
1461                         c = 'I';
1462                         break;
1463                 case TD_NOT_CREATED:
1464                         c = 'P';
1465                         break;
1466                 default:
1467                         log_err("state %d\n", td->runstate);
1468         }
1469
1470         run_str[td->thread_number - 1] = c;
1471 }
1472
1473 static void eta_to_str(char *str, int eta_sec)
1474 {
1475         unsigned int d, h, m, s;
1476         static int always_d, always_h;
1477
1478         d = h = m = s = 0;
1479
1480         s = eta_sec % 60;
1481         eta_sec /= 60;
1482         m = eta_sec % 60;
1483         eta_sec /= 60;
1484         h = eta_sec % 24;
1485         eta_sec /= 24;
1486         d = eta_sec;
1487
1488         if (d || always_d) {
1489                 always_d = 1;
1490                 str += sprintf(str, "%02dd:", d);
1491         }
1492         if (h || always_h) {
1493                 always_h = 1;
1494                 str += sprintf(str, "%02dh:", h);
1495         }
1496
1497         str += sprintf(str, "%02dm:", m);
1498         str += sprintf(str, "%02ds", s);
1499 }
1500
1501 static int thread_eta(struct thread_data *td, unsigned long elapsed)
1502 {
1503         unsigned long long bytes_total, bytes_done;
1504         unsigned int eta_sec = 0;
1505
1506         bytes_total = td->total_io_size;
1507
1508         /*
1509          * if writing, bytes_total will be twice the size. If mixing,
1510          * assume a 50/50 split and thus bytes_total will be 50% larger.
1511          */
1512         if (td->verify) {
1513                 if (td_rw(td))
1514                         bytes_total = bytes_total * 3 / 2;
1515                 else
1516                         bytes_total <<= 1;
1517         }
1518         if (td->zone_size && td->zone_skip)
1519                 bytes_total /= (td->zone_skip / td->zone_size);
1520
1521         if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING) {
1522                 double perc;
1523
1524                 bytes_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE];
1525                 perc = (double) bytes_done / (double) bytes_total;
1526                 if (perc > 1.0)
1527                         perc = 1.0;
1528
1529                 eta_sec = (elapsed * (1.0 / perc)) - elapsed;
1530
1531                 if (td->timeout && eta_sec > (td->timeout - elapsed))
1532                         eta_sec = td->timeout - elapsed;
1533         } else if (td->runstate == TD_NOT_CREATED || td->runstate == TD_CREATED
1534                         || td->runstate == TD_INITIALIZED) {
1535                 int t_eta = 0, r_eta = 0;
1536
1537                 /*
1538                  * We can only guess - assume it'll run the full timeout
1539                  * if given, otherwise assume it'll run at the specified rate.
1540                  */
1541                 if (td->timeout)
1542                         t_eta = td->timeout + td->start_delay - elapsed;
1543                 if (td->rate) {
1544                         r_eta = (bytes_total / 1024) / td->rate;
1545                         r_eta += td->start_delay - elapsed;
1546                 }
1547
1548                 if (r_eta && t_eta)
1549                         eta_sec = min(r_eta, t_eta);
1550                 else if (r_eta)
1551                         eta_sec = r_eta;
1552                 else if (t_eta)
1553                         eta_sec = t_eta;
1554                 else
1555                         eta_sec = INT_MAX;
1556         } else {
1557                 /*
1558                  * thread is already done or waiting for fsync
1559                  */
1560                 eta_sec = 0;
1561         }
1562
1563         return eta_sec;
1564 }
1565
1566 static void print_thread_status(void)
1567 {
1568         unsigned long elapsed = time_since_now(&genesis);
1569         int i, nr_running, nr_pending, t_rate, m_rate, *eta_secs, eta_sec;
1570         char eta_str[32];
1571         double perc = 0.0;
1572
1573         eta_secs = malloc(thread_number * sizeof(int));
1574         memset(eta_secs, 0, thread_number * sizeof(int));
1575
1576         nr_pending = nr_running = t_rate = m_rate = 0;
1577         for (i = 0; i < thread_number; i++) {
1578                 struct thread_data *td = &threads[i];
1579
1580                 if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING||
1581                     td->runstate == TD_FSYNCING) {
1582                         nr_running++;
1583                         t_rate += td->rate;
1584                         m_rate += td->ratemin;
1585                 } else if (td->runstate < TD_RUNNING)
1586                         nr_pending++;
1587
1588                 if (elapsed >= 3)
1589                         eta_secs[i] = thread_eta(td, elapsed);
1590                 else
1591                         eta_secs[i] = INT_MAX;
1592
1593                 check_str_update(td);
1594         }
1595
1596         if (exitall_on_terminate)
1597                 eta_sec = INT_MAX;
1598         else
1599                 eta_sec = 0;
1600
1601         for (i = 0; i < thread_number; i++) {
1602                 if (exitall_on_terminate) {
1603                         if (eta_secs[i] < eta_sec)
1604                                 eta_sec = eta_secs[i];
1605                 } else {
1606                         if (eta_secs[i] > eta_sec)
1607                                 eta_sec = eta_secs[i];
1608                 }
1609         }
1610
1611         if (eta_sec != INT_MAX && elapsed) {
1612                 perc = (double) elapsed / (double) (elapsed + eta_sec);
1613                 eta_to_str(eta_str, eta_sec);
1614         }
1615
1616         if (!nr_running && !nr_pending)
1617                 return;
1618
1619         printf("Threads running: %d", nr_running);
1620         if (m_rate || t_rate)
1621                 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
1622         if (eta_sec != INT_MAX) {
1623                 perc *= 100.0;
1624                 printf(": [%s] [%3.2f%% done] [eta %s]", run_str, perc,eta_str);
1625         }
1626         printf("\r");
1627         fflush(stdout);
1628         free(eta_secs);
1629 }
1630
1631 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1632 {
1633         int i;
1634
1635         /*
1636          * reap exited threads (TD_EXITED -> TD_REAPED)
1637          */
1638         for (i = 0; i < thread_number; i++) {
1639                 struct thread_data *td = &threads[i];
1640
1641                 if (td->runstate != TD_EXITED)
1642                         continue;
1643
1644                 td_set_runstate(td, TD_REAPED);
1645
1646                 if (td->use_thread) {
1647                         long ret;
1648
1649                         if (pthread_join(td->thread, (void *) &ret))
1650                                 perror("thread_join");
1651                 } else
1652                         waitpid(td->pid, NULL, 0);
1653
1654                 (*nr_running)--;
1655                 (*m_rate) -= td->ratemin;
1656                 (*t_rate) -= td->rate;
1657         }
1658 }
1659
1660 static void fio_unpin_memory(void *pinned)
1661 {
1662         if (pinned) {
1663                 if (munlock(pinned, mlock_size) < 0)
1664                         perror("munlock");
1665                 munmap(pinned, mlock_size);
1666         }
1667 }
1668
1669 static void *fio_pin_memory(void)
1670 {
1671         unsigned long long phys_mem;
1672         void *ptr;
1673
1674         if (!mlock_size)
1675                 return NULL;
1676
1677         /*
1678          * Don't allow mlock of more than real_mem-128MB
1679          */
1680         phys_mem = os_phys_mem();
1681         if (phys_mem) {
1682                 if ((mlock_size + 128 * 1024 * 1024) > phys_mem) {
1683                         mlock_size = phys_mem - 128 * 1024 * 1024;
1684                         fprintf(f_out, "fio: limiting mlocked memory to %lluMiB\n", mlock_size >> 20);
1685                 }
1686         }
1687
1688         ptr = mmap(NULL, mlock_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
1689         if (!ptr) {
1690                 perror("malloc locked mem");
1691                 return NULL;
1692         }
1693         if (mlock(ptr, mlock_size) < 0) {
1694                 munmap(ptr, mlock_size);
1695                 perror("mlock");
1696                 return NULL;
1697         }
1698
1699         return ptr;
1700 }
1701
1702 static void run_threads(void)
1703 {
1704         struct thread_data *td;
1705         unsigned long spent;
1706         int i, todo, nr_running, m_rate, t_rate, nr_started;
1707         void *mlocked_mem;
1708
1709         mlocked_mem = fio_pin_memory();
1710
1711         printf("Starting %d thread%s\n", thread_number, thread_number > 1 ? "s" : "");
1712         fflush(stdout);
1713
1714         signal(SIGINT, sig_handler);
1715         signal(SIGALRM, sig_handler);
1716
1717         todo = thread_number;
1718         nr_running = 0;
1719         nr_started = 0;
1720         m_rate = t_rate = 0;
1721
1722         for (i = 0; i < thread_number; i++) {
1723                 td = &threads[i];
1724
1725                 run_str[td->thread_number - 1] = 'P';
1726
1727                 init_disk_util(td);
1728
1729                 if (!td->create_serialize)
1730                         continue;
1731
1732                 /*
1733                  * do file setup here so it happens sequentially,
1734                  * we don't want X number of threads getting their
1735                  * client data interspersed on disk
1736                  */
1737                 if (setup_file(td)) {
1738                         td_set_runstate(td, TD_REAPED);
1739                         todo--;
1740                 }
1741         }
1742
1743         gettimeofday(&genesis, NULL);
1744
1745         while (todo) {
1746                 struct thread_data *map[MAX_JOBS];
1747                 struct timeval this_start;
1748                 int this_jobs = 0, left;
1749
1750                 /*
1751                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1752                  */
1753                 for (i = 0; i < thread_number; i++) {
1754                         td = &threads[i];
1755
1756                         if (td->runstate != TD_NOT_CREATED)
1757                                 continue;
1758
1759                         /*
1760                          * never got a chance to start, killed by other
1761                          * thread for some reason
1762                          */
1763                         if (td->terminate) {
1764                                 todo--;
1765                                 continue;
1766                         }
1767
1768                         if (td->start_delay) {
1769                                 spent = mtime_since_now(&genesis);
1770
1771                                 if (td->start_delay * 1000 > spent)
1772                                         continue;
1773                         }
1774
1775                         if (td->stonewall && (nr_started || nr_running))
1776                                 break;
1777
1778                         /*
1779                          * Set state to created. Thread will transition
1780                          * to TD_INITIALIZED when it's done setting up.
1781                          */
1782                         td_set_runstate(td, TD_CREATED);
1783                         map[this_jobs++] = td;
1784                         fio_sem_init(&startup_sem, 1);
1785                         nr_started++;
1786
1787                         if (td->use_thread) {
1788                                 if (pthread_create(&td->thread, NULL, thread_main, td)) {
1789                                         perror("thread_create");
1790                                         nr_started--;
1791                                 }
1792                         } else {
1793                                 if (fork())
1794                                         fio_sem_down(&startup_sem);
1795                                 else {
1796                                         fork_main(shm_id, i);
1797                                         exit(0);
1798                                 }
1799                         }
1800                 }
1801
1802                 /*
1803                  * Wait for the started threads to transition to
1804                  * TD_INITIALIZED.
1805                  */
1806                 printf("fio: Waiting for threads to initialize...\n");
1807                 gettimeofday(&this_start, NULL);
1808                 left = this_jobs;
1809                 while (left) {
1810                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1811                                 break;
1812
1813                         usleep(100000);
1814
1815                         for (i = 0; i < this_jobs; i++) {
1816                                 td = map[i];
1817                                 if (!td)
1818                                         continue;
1819                                 if (td->runstate == TD_INITIALIZED) {
1820                                         map[i] = NULL;
1821                                         left--;
1822                                 } else if (td->runstate >= TD_EXITED) {
1823                                         map[i] = NULL;
1824                                         left--;
1825                                         todo--;
1826                                         nr_running++; /* work-around... */
1827                                 }
1828                         }
1829                 }
1830
1831                 if (left) {
1832                         log_err("fio: %d jobs failed to start\n", left);
1833                         for (i = 0; i < this_jobs; i++) {
1834                                 td = map[i];
1835                                 if (!td)
1836                                         continue;
1837                                 kill(td->pid, SIGTERM);
1838                         }
1839                         break;
1840                 }
1841
1842                 /*
1843                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1844                  */
1845                 printf("fio: Go for launch\n");
1846                 for (i = 0; i < thread_number; i++) {
1847                         td = &threads[i];
1848
1849                         if (td->runstate != TD_INITIALIZED)
1850                                 continue;
1851
1852                         td_set_runstate(td, TD_RUNNING);
1853                         nr_running++;
1854                         nr_started--;
1855                         m_rate += td->ratemin;
1856                         t_rate += td->rate;
1857                         todo--;
1858                         fio_sem_up(&td->mutex);
1859                 }
1860
1861                 reap_threads(&nr_running, &t_rate, &m_rate);
1862
1863                 if (todo)
1864                         usleep(100000);
1865         }
1866
1867         while (nr_running) {
1868                 reap_threads(&nr_running, &t_rate, &m_rate);
1869                 usleep(10000);
1870         }
1871
1872         update_io_ticks();
1873         fio_unpin_memory(mlocked_mem);
1874 }
1875
1876 int main(int argc, char *argv[])
1877 {
1878         if (parse_options(argc, argv))
1879                 return 1;
1880
1881         if (!thread_number) {
1882                 log_err("Nothing to do\n");
1883                 return 1;
1884         }
1885
1886         disk_util_timer_arm();
1887
1888         run_threads();
1889         show_run_stats();
1890
1891         return 0;
1892 }