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