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