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