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