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