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