231a581f5478df56054531137d2f1b17ebc3ba57
[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  * The license below covers all files distributed with fio unless otherwise
8  * noted in the file itself.
9  *
10  *  This program is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License version 2 as
12  *  published by the Free Software Foundation.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <string.h>
27 #include <signal.h>
28 #include <time.h>
29 #include <locale.h>
30 #include <assert.h>
31 #include <sys/stat.h>
32 #include <sys/wait.h>
33 #include <sys/ipc.h>
34 #include <sys/shm.h>
35 #include <sys/mman.h>
36
37 #include "fio.h"
38 #include "hash.h"
39 #include "smalloc.h"
40
41 unsigned long page_mask;
42 unsigned long page_size;
43 #define ALIGN(buf)      \
44         (char *) (((unsigned long) (buf) + page_mask) & ~page_mask)
45
46 int groupid = 0;
47 int thread_number = 0;
48 int nr_process = 0;
49 int nr_thread = 0;
50 int shm_id = 0;
51 int temp_stall_ts;
52
53 static struct fio_mutex *startup_mutex;
54 static volatile int fio_abort;
55 static int exit_value;
56
57 struct io_log *agg_io_log[2];
58
59 #define TERMINATE_ALL           (-1)
60 #define JOB_START_TIMEOUT       (5 * 1000)
61
62 static inline void td_set_runstate(struct thread_data *td, int runstate)
63 {
64         if (td->runstate == runstate)
65                 return;
66
67         dprint(FD_PROCESS, "pid=%d: runstate %d -> %d\n", td->pid, td->runstate,
68                                                                 runstate);
69         td->runstate = runstate;
70 }
71
72 static void terminate_threads(int group_id)
73 {
74         struct thread_data *td;
75         int i;
76
77         dprint(FD_PROCESS, "terminate group_id=%d\n", group_id);
78
79         for_each_td(td, i) {
80                 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
81                         dprint(FD_PROCESS, "setting terminate on %s/%d\n",
82                                                         td->o.name, td->pid);
83                         td->terminate = 1;
84                         td->o.start_delay = 0;
85
86                         /*
87                          * if the thread is running, just let it exit
88                          */
89                         if (td->runstate < TD_RUNNING)
90                                 kill(td->pid, SIGQUIT);
91                         else {
92                                 struct ioengine_ops *ops = td->io_ops;
93
94                                 if (ops && (ops->flags & FIO_SIGQUIT))
95                                         kill(td->pid, SIGQUIT);
96                         }
97                 }
98         }
99 }
100
101 static void sig_handler(int sig)
102 {
103         switch (sig) {
104         case SIGALRM:
105                 update_io_ticks();
106                 disk_util_timer_arm();
107                 print_thread_status();
108                 break;
109         default:
110                 printf("\nfio: terminating on signal %d\n", sig);
111                 fflush(stdout);
112                 terminate_threads(TERMINATE_ALL);
113                 break;
114         }
115 }
116
117 /*
118  * Check if we are above the minimum rate given.
119  */
120 static int check_min_rate(struct thread_data *td, struct timeval *now)
121 {
122         unsigned long long bytes = 0;
123         unsigned long iops = 0;
124         unsigned long spent;
125         unsigned long rate;
126
127         /*
128          * No minimum rate set, always ok
129          */
130         if (!td->o.ratemin && !td->o.rate_iops_min)
131                 return 0;
132
133         /*
134          * allow a 2 second settle period in the beginning
135          */
136         if (mtime_since(&td->start, now) < 2000)
137                 return 0;
138
139         if (td_read(td)) {
140                 iops += td->io_blocks[DDIR_READ];
141                 bytes += td->this_io_bytes[DDIR_READ];
142         }
143         if (td_write(td)) {
144                 iops += td->io_blocks[DDIR_WRITE];
145                 bytes += td->this_io_bytes[DDIR_WRITE];
146         }
147
148         /*
149          * if rate blocks is set, sample is running
150          */
151         if (td->rate_bytes || td->rate_blocks) {
152                 spent = mtime_since(&td->lastrate, now);
153                 if (spent < td->o.ratecycle)
154                         return 0;
155
156                 if (td->o.rate) {
157                         /*
158                          * check bandwidth specified rate
159                          */
160                         if (bytes < td->rate_bytes) {
161                                 log_err("%s: min rate %u not met\n", td->o.name,
162                                                                 td->o.ratemin);
163                                 return 1;
164                         } else {
165                                 rate = (bytes - td->rate_bytes) / spent;
166                                 if (rate < td->o.ratemin ||
167                                     bytes < td->rate_bytes) {
168                                         log_err("%s: min rate %u not met, got"
169                                                 " %luKiB/sec\n", td->o.name,
170                                                         td->o.ratemin, rate);
171                                         return 1;
172                                 }
173                         }
174                 } else {
175                         /*
176                          * checks iops specified rate
177                          */
178                         if (iops < td->o.rate_iops) {
179                                 log_err("%s: min iops rate %u not met\n",
180                                                 td->o.name, td->o.rate_iops);
181                                 return 1;
182                         } else {
183                                 rate = (iops - td->rate_blocks) / spent;
184                                 if (rate < td->o.rate_iops_min ||
185                                     iops < td->rate_blocks) {
186                                         log_err("%s: min iops rate %u not met,"
187                                                 " got %lu\n", td->o.name,
188                                                         td->o.rate_iops_min,
189                                                         rate);
190                                 }
191                         }
192                 }
193         }
194
195         td->rate_bytes = bytes;
196         td->rate_blocks = iops;
197         memcpy(&td->lastrate, now, sizeof(*now));
198         return 0;
199 }
200
201 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
202 {
203         if (!td->o.timeout)
204                 return 0;
205         if (mtime_since(&td->epoch, t) >= td->o.timeout * 1000)
206                 return 1;
207
208         return 0;
209 }
210
211 /*
212  * When job exits, we can cancel the in-flight IO if we are using async
213  * io. Attempt to do so.
214  */
215 static void cleanup_pending_aio(struct thread_data *td)
216 {
217         struct list_head *entry, *n;
218         struct io_u *io_u;
219         int r;
220
221         /*
222          * get immediately available events, if any
223          */
224         r = io_u_queued_complete(td, 0);
225         if (r < 0)
226                 return;
227
228         /*
229          * now cancel remaining active events
230          */
231         if (td->io_ops->cancel) {
232                 list_for_each_safe(entry, n, &td->io_u_busylist) {
233                         io_u = list_entry(entry, struct io_u, list);
234
235                         /*
236                          * if the io_u isn't in flight, then that generally
237                          * means someone leaked an io_u. complain but fix
238                          * it up, so we don't stall here.
239                          */
240                         if ((io_u->flags & IO_U_F_FLIGHT) == 0) {
241                                 log_err("fio: non-busy IO on busy list\n");
242                                 put_io_u(td, io_u);
243                         } else {
244                                 r = td->io_ops->cancel(td, io_u);
245                                 if (!r)
246                                         put_io_u(td, io_u);
247                         }
248                 }
249         }
250
251         if (td->cur_depth)
252                 r = io_u_queued_complete(td, td->cur_depth);
253 }
254
255 /*
256  * Helper to handle the final sync of a file. Works just like the normal
257  * io path, just does everything sync.
258  */
259 static int fio_io_sync(struct thread_data *td, struct fio_file *f)
260 {
261         struct io_u *io_u = __get_io_u(td);
262         int ret;
263
264         if (!io_u)
265                 return 1;
266
267         io_u->ddir = DDIR_SYNC;
268         io_u->file = f;
269
270         if (td_io_prep(td, io_u)) {
271                 put_io_u(td, io_u);
272                 return 1;
273         }
274
275 requeue:
276         ret = td_io_queue(td, io_u);
277         if (ret < 0) {
278                 td_verror(td, io_u->error, "td_io_queue");
279                 put_io_u(td, io_u);
280                 return 1;
281         } else if (ret == FIO_Q_QUEUED) {
282                 if (io_u_queued_complete(td, 1) < 0)
283                         return 1;
284         } else if (ret == FIO_Q_COMPLETED) {
285                 if (io_u->error) {
286                         td_verror(td, io_u->error, "td_io_queue");
287                         return 1;
288                 }
289
290                 if (io_u_sync_complete(td, io_u) < 0)
291                         return 1;
292         } else if (ret == FIO_Q_BUSY) {
293                 if (td_io_commit(td))
294                         return 1;
295                 goto requeue;
296         }
297
298         return 0;
299 }
300
301 /*
302  * The main verify engine. Runs over the writes we previously submitted,
303  * reads the blocks back in, and checks the crc/md5 of the data.
304  */
305 static void do_verify(struct thread_data *td)
306 {
307         struct fio_file *f;
308         struct io_u *io_u;
309         int ret, min_events;
310         unsigned int i;
311
312         /*
313          * sync io first and invalidate cache, to make sure we really
314          * read from disk.
315          */
316         for_each_file(td, f, i) {
317                 if (!(f->flags & FIO_FILE_OPEN))
318                         continue;
319                 if (fio_io_sync(td, f))
320                         break;
321                 if (file_invalidate_cache(td, f))
322                         break;
323         }
324
325         if (td->error)
326                 return;
327
328         td_set_runstate(td, TD_VERIFYING);
329
330         io_u = NULL;
331         while (!td->terminate) {
332                 int ret2;
333
334                 io_u = __get_io_u(td);
335                 if (!io_u)
336                         break;
337
338                 if (runtime_exceeded(td, &io_u->start_time)) {
339                         put_io_u(td, io_u);
340                         td->terminate = 1;
341                         break;
342                 }
343
344                 if (get_next_verify(td, io_u)) {
345                         put_io_u(td, io_u);
346                         break;
347                 }
348
349                 if (td_io_prep(td, io_u)) {
350                         put_io_u(td, io_u);
351                         break;
352                 }
353
354                 io_u->end_io = verify_io_u;
355
356                 ret = td_io_queue(td, io_u);
357                 switch (ret) {
358                 case FIO_Q_COMPLETED:
359                         if (io_u->error)
360                                 ret = -io_u->error;
361                         else if (io_u->resid) {
362                                 int bytes = io_u->xfer_buflen - io_u->resid;
363                                 struct fio_file *f = io_u->file;
364
365                                 /*
366                                  * zero read, fail
367                                  */
368                                 if (!bytes) {
369                                         td_verror(td, ENODATA, "full resid");
370                                         put_io_u(td, io_u);
371                                         break;
372                                 }
373
374                                 io_u->xfer_buflen = io_u->resid;
375                                 io_u->xfer_buf += bytes;
376                                 io_u->offset += bytes;
377
378                                 td->ts.short_io_u[io_u->ddir]++;
379
380                                 if (io_u->offset == f->real_file_size)
381                                         goto sync_done;
382
383                                 requeue_io_u(td, &io_u);
384                         } else {
385 sync_done:
386                                 ret = io_u_sync_complete(td, io_u);
387                                 if (ret < 0)
388                                         break;
389                         }
390                         continue;
391                 case FIO_Q_QUEUED:
392                         break;
393                 case FIO_Q_BUSY:
394                         requeue_io_u(td, &io_u);
395                         ret2 = td_io_commit(td);
396                         if (ret2 < 0)
397                                 ret = ret2;
398                         break;
399                 default:
400                         assert(ret < 0);
401                         td_verror(td, -ret, "td_io_queue");
402                         break;
403                 }
404
405                 if (ret < 0 || td->error)
406                         break;
407
408                 /*
409                  * if we can queue more, do so. but check if there are
410                  * completed io_u's first.
411                  */
412                 min_events = 0;
413                 if (queue_full(td) || ret == FIO_Q_BUSY) {
414                         min_events = 1;
415
416                         if (td->cur_depth > td->o.iodepth_low)
417                                 min_events = td->cur_depth - td->o.iodepth_low;
418                 }
419
420                 /*
421                  * Reap required number of io units, if any, and do the
422                  * verification on them through the callback handler
423                  */
424                 if (io_u_queued_complete(td, min_events) < 0)
425                         break;
426         }
427
428         if (!td->error) {
429                 min_events = td->cur_depth;
430
431                 if (min_events)
432                         ret = io_u_queued_complete(td, min_events);
433         } else
434                 cleanup_pending_aio(td);
435
436         td_set_runstate(td, TD_RUNNING);
437 }
438
439 /*
440  * Main IO worker function. It retrieves io_u's to process and queues
441  * and reaps them, checking for rate and errors along the way.
442  */
443 static void do_io(struct thread_data *td)
444 {
445         struct timeval s;
446         unsigned long usec;
447         unsigned int i;
448         int ret = 0;
449
450         td_set_runstate(td, TD_RUNNING);
451
452         while ((td->this_io_bytes[0] + td->this_io_bytes[1]) < td->o.size) {
453                 struct timeval comp_time;
454                 long bytes_done = 0;
455                 int min_evts = 0;
456                 struct io_u *io_u;
457                 int ret2;
458
459                 if (td->terminate)
460                         break;
461
462                 io_u = get_io_u(td);
463                 if (!io_u)
464                         break;
465
466                 memcpy(&s, &io_u->start_time, sizeof(s));
467
468                 if (runtime_exceeded(td, &s)) {
469                         put_io_u(td, io_u);
470                         td->terminate = 1;
471                         break;
472                 }
473
474                 /*
475                  * Add verification end_io handler, if asked to verify
476                  * a previously written file.
477                  */
478                 if (td->o.verify != VERIFY_NONE && io_u->ddir == DDIR_READ) {
479                         io_u->end_io = verify_io_u;
480                         td_set_runstate(td, TD_VERIFYING);
481                 } else
482                         td_set_runstate(td, TD_RUNNING);
483
484                 ret = td_io_queue(td, io_u);
485                 switch (ret) {
486                 case FIO_Q_COMPLETED:
487                         if (io_u->error)
488                                 ret = -io_u->error;
489                         else if (io_u->resid) {
490                                 int bytes = io_u->xfer_buflen - io_u->resid;
491                                 struct fio_file *f = io_u->file;
492
493                                 /*
494                                  * zero read, fail
495                                  */
496                                 if (!bytes) {
497                                         td_verror(td, ENODATA, "full resid");
498                                         put_io_u(td, io_u);
499                                         break;
500                                 }
501
502                                 io_u->xfer_buflen = io_u->resid;
503                                 io_u->xfer_buf += bytes;
504                                 io_u->offset += bytes;
505
506                                 td->ts.short_io_u[io_u->ddir]++;
507
508                                 if (io_u->offset == f->real_file_size)
509                                         goto sync_done;
510
511                                 requeue_io_u(td, &io_u);
512                         } else {
513 sync_done:
514                                 fio_gettime(&comp_time, NULL);
515                                 bytes_done = io_u_sync_complete(td, io_u);
516                                 if (bytes_done < 0)
517                                         ret = bytes_done;
518                         }
519                         break;
520                 case FIO_Q_QUEUED:
521                         /*
522                          * if the engine doesn't have a commit hook,
523                          * the io_u is really queued. if it does have such
524                          * a hook, it has to call io_u_queued() itself.
525                          */
526                         if (td->io_ops->commit == NULL)
527                                 io_u_queued(td, io_u);
528                         break;
529                 case FIO_Q_BUSY:
530                         requeue_io_u(td, &io_u);
531                         ret2 = td_io_commit(td);
532                         if (ret2 < 0)
533                                 ret = ret2;
534                         break;
535                 default:
536                         assert(ret < 0);
537                         put_io_u(td, io_u);
538                         break;
539                 }
540
541                 if (ret < 0 || td->error)
542                         break;
543
544                 /*
545                  * See if we need to complete some commands
546                  */
547                 if (ret == FIO_Q_QUEUED || ret == FIO_Q_BUSY) {
548                         min_evts = 0;
549                         if (queue_full(td) || ret == FIO_Q_BUSY) {
550                                 min_evts = 1;
551
552                                 if (td->cur_depth > td->o.iodepth_low)
553                                         min_evts = td->cur_depth
554                                                         - td->o.iodepth_low;
555                         }
556
557                         fio_gettime(&comp_time, NULL);
558                         bytes_done = io_u_queued_complete(td, min_evts);
559                         if (bytes_done < 0)
560                                 break;
561                 }
562
563                 if (!bytes_done)
564                         continue;
565
566                 /*
567                  * the rate is batched for now, it should work for batches
568                  * of completions except the very first one which may look
569                  * a little bursty
570                  */
571                 usec = utime_since(&s, &comp_time);
572
573                 rate_throttle(td, usec, bytes_done);
574
575                 if (check_min_rate(td, &comp_time)) {
576                         if (exitall_on_terminate)
577                                 terminate_threads(td->groupid);
578                         td_verror(td, ENODATA, "check_min_rate");
579                         break;
580                 }
581
582                 if (td->o.thinktime) {
583                         unsigned long long b;
584
585                         b = td->io_blocks[0] + td->io_blocks[1];
586                         if (!(b % td->o.thinktime_blocks)) {
587                                 int left;
588
589                                 if (td->o.thinktime_spin)
590                                         __usec_sleep(td->o.thinktime_spin);
591
592                                 left = td->o.thinktime - td->o.thinktime_spin;
593                                 if (left)
594                                         usec_sleep(td, left);
595                         }
596                 }
597         }
598
599         if (td->o.fill_device && td->error == ENOSPC) {
600                 td->error = 0;
601                 td->terminate = 1;
602         }
603         if (!td->error) {
604                 struct fio_file *f;
605
606                 i = td->cur_depth;
607                 if (i)
608                         ret = io_u_queued_complete(td, i);
609
610                 if (should_fsync(td) && td->o.end_fsync) {
611                         td_set_runstate(td, TD_FSYNCING);
612
613                         for_each_file(td, f, i) {
614                                 if (!(f->flags & FIO_FILE_OPEN))
615                                         continue;
616                                 fio_io_sync(td, f);
617                         }
618                 }
619         } else
620                 cleanup_pending_aio(td);
621
622         /*
623          * stop job if we failed doing any IO
624          */
625         if ((td->this_io_bytes[0] + td->this_io_bytes[1]) == 0)
626                 td->done = 1;
627 }
628
629 static void cleanup_io_u(struct thread_data *td)
630 {
631         struct list_head *entry, *n;
632         struct io_u *io_u;
633
634         list_for_each_safe(entry, n, &td->io_u_freelist) {
635                 io_u = list_entry(entry, struct io_u, list);
636
637                 list_del(&io_u->list);
638                 free(io_u);
639         }
640
641         free_io_mem(td);
642 }
643
644 /*
645  * "randomly" fill the buffer contents
646  */
647 static void fill_io_buf(struct thread_data *td, struct io_u *io_u, int max_bs)
648 {
649         long *ptr = io_u->buf;
650
651         if (!td->o.zero_buffers) {
652                 while ((void *) ptr - io_u->buf < max_bs) {
653                         *ptr = rand() * GOLDEN_RATIO_PRIME;
654                         ptr++;
655                 }
656         } else
657                 memset(ptr, 0, max_bs);
658 }
659
660 static int init_io_u(struct thread_data *td)
661 {
662         struct io_u *io_u;
663         unsigned int max_bs;
664         int i, max_units;
665         char *p;
666
667         max_units = td->o.iodepth;
668         max_bs = max(td->o.max_bs[DDIR_READ], td->o.max_bs[DDIR_WRITE]);
669         td->orig_buffer_size = (unsigned long long) max_bs
670                                         * (unsigned long long) max_units;
671
672         if (td->o.mem_type == MEM_SHMHUGE || td->o.mem_type == MEM_MMAPHUGE) {
673                 unsigned long bs;
674
675                 bs = td->orig_buffer_size + td->o.hugepage_size - 1;
676                 td->orig_buffer_size = bs & ~(td->o.hugepage_size - 1);
677         }
678
679         if (td->orig_buffer_size != (size_t) td->orig_buffer_size) {
680                 log_err("fio: IO memory too large. Reduce max_bs or iodepth\n");
681                 return 1;
682         }
683
684         if (allocate_io_mem(td))
685                 return 1;
686
687         if (td->o.odirect)
688                 p = ALIGN(td->orig_buffer);
689         else
690                 p = td->orig_buffer;
691
692         for (i = 0; i < max_units; i++) {
693                 if (td->terminate)
694                         return 1;
695                 io_u = malloc(sizeof(*io_u));
696                 memset(io_u, 0, sizeof(*io_u));
697                 INIT_LIST_HEAD(&io_u->list);
698
699                 if (!(td->io_ops->flags & FIO_NOIO)) {
700                         io_u->buf = p + max_bs * i;
701
702                         if (td_write(td))
703                                 fill_io_buf(td, io_u, max_bs);
704                 }
705
706                 io_u->index = i;
707                 io_u->flags = IO_U_F_FREE;
708                 list_add(&io_u->list, &td->io_u_freelist);
709         }
710
711         io_u_init_timeout();
712
713         return 0;
714 }
715
716 static int switch_ioscheduler(struct thread_data *td)
717 {
718         char tmp[256], tmp2[128];
719         FILE *f;
720         int ret;
721
722         if (td->io_ops->flags & FIO_DISKLESSIO)
723                 return 0;
724
725         sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
726
727         f = fopen(tmp, "r+");
728         if (!f) {
729                 if (errno == ENOENT) {
730                         log_err("fio: os or kernel doesn't support IO scheduler"
731                                 " switching\n");
732                         return 0;
733                 }
734                 td_verror(td, errno, "fopen iosched");
735                 return 1;
736         }
737
738         /*
739          * Set io scheduler.
740          */
741         ret = fwrite(td->o.ioscheduler, strlen(td->o.ioscheduler), 1, f);
742         if (ferror(f) || ret != 1) {
743                 td_verror(td, errno, "fwrite");
744                 fclose(f);
745                 return 1;
746         }
747
748         rewind(f);
749
750         /*
751          * Read back and check that the selected scheduler is now the default.
752          */
753         ret = fread(tmp, 1, sizeof(tmp), f);
754         if (ferror(f) || ret < 0) {
755                 td_verror(td, errno, "fread");
756                 fclose(f);
757                 return 1;
758         }
759
760         sprintf(tmp2, "[%s]", td->o.ioscheduler);
761         if (!strstr(tmp, tmp2)) {
762                 log_err("fio: io scheduler %s not found\n", td->o.ioscheduler);
763                 td_verror(td, EINVAL, "iosched_switch");
764                 fclose(f);
765                 return 1;
766         }
767
768         fclose(f);
769         return 0;
770 }
771
772 static int keep_running(struct thread_data *td)
773 {
774         unsigned long long io_done;
775
776         if (td->done)
777                 return 0;
778         if (td->o.time_based)
779                 return 1;
780         if (td->o.loops) {
781                 td->o.loops--;
782                 return 1;
783         }
784
785         io_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE]
786                         + td->io_skip_bytes;
787         if (io_done < td->o.size)
788                 return 1;
789
790         return 0;
791 }
792
793 static int clear_io_state(struct thread_data *td)
794 {
795         struct fio_file *f;
796         unsigned int i;
797         int ret;
798
799         td->ts.stat_io_bytes[0] = td->ts.stat_io_bytes[1] = 0;
800         td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
801         td->zone_bytes = 0;
802         td->rate_bytes = 0;
803         td->rate_blocks = 0;
804         td->rw_end_set[0] = td->rw_end_set[1] = 0;
805
806         td->last_was_sync = 0;
807
808         /*
809          * reset file done count if we are to start over
810          */
811         if (td->o.time_based || td->o.loops)
812                 td->nr_done_files = 0;
813
814         close_files(td);
815
816         ret = 0;
817         for_each_file(td, f, i) {
818                 f->flags &= ~FIO_FILE_DONE;
819                 ret = td_io_open_file(td, f);
820                 if (ret)
821                         break;
822         }
823
824         return ret;
825 }
826
827 /*
828  * Entry point for the thread based jobs. The process based jobs end up
829  * here as well, after a little setup.
830  */
831 static void *thread_main(void *data)
832 {
833         unsigned long long runtime[2], elapsed;
834         struct thread_data *td = data;
835         int clear_state;
836
837         if (!td->o.use_thread)
838                 setsid();
839
840         td->pid = getpid();
841
842         dprint(FD_PROCESS, "jobs pid=%d started\n", td->pid);
843
844         INIT_LIST_HEAD(&td->io_u_freelist);
845         INIT_LIST_HEAD(&td->io_u_busylist);
846         INIT_LIST_HEAD(&td->io_u_requeues);
847         INIT_LIST_HEAD(&td->io_log_list);
848         INIT_LIST_HEAD(&td->io_hist_list);
849         td->io_hist_tree = RB_ROOT;
850
851         td_set_runstate(td, TD_INITIALIZED);
852         fio_mutex_up(startup_mutex);
853         fio_mutex_down(td->mutex);
854
855         /*
856          * the ->mutex mutex is now no longer used, close it to avoid
857          * eating a file descriptor
858          */
859         fio_mutex_remove(td->mutex);
860
861         /*
862          * May alter parameters that init_io_u() will use, so we need to
863          * do this first.
864          */
865         if (init_iolog(td))
866                 goto err;
867
868         if (init_io_u(td))
869                 goto err;
870
871         if (td->o.cpumask_set && fio_setaffinity(td) == -1) {
872                 td_verror(td, errno, "cpu_set_affinity");
873                 goto err;
874         }
875
876         if (td->ioprio_set) {
877                 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
878                         td_verror(td, errno, "ioprio_set");
879                         goto err;
880                 }
881         }
882
883         if (nice(td->o.nice) == -1) {
884                 td_verror(td, errno, "nice");
885                 goto err;
886         }
887
888         if (td->o.ioscheduler && switch_ioscheduler(td))
889                 goto err;
890
891         if (!td->o.create_serialize && setup_files(td))
892                 goto err;
893
894         if (td_io_init(td))
895                 goto err;
896
897         if (open_files(td))
898                 goto err;
899
900         if (init_random_map(td))
901                 goto err;
902
903         if (td->o.exec_prerun) {
904                 if (system(td->o.exec_prerun) < 0)
905                         goto err;
906         }
907
908         fio_gettime(&td->epoch, NULL);
909         memcpy(&td->timeout_end, &td->epoch, sizeof(td->epoch));
910         getrusage(RUSAGE_SELF, &td->ts.ru_start);
911
912         runtime[0] = runtime[1] = 0;
913         clear_state = 0;
914         while (keep_running(td)) {
915                 fio_gettime(&td->start, NULL);
916                 memcpy(&td->ts.stat_sample_time, &td->start, sizeof(td->start));
917
918                 if (td->o.ratemin)
919                         memcpy(&td->lastrate, &td->ts.stat_sample_time,
920                                                         sizeof(td->lastrate));
921
922                 if (clear_state && clear_io_state(td))
923                         break;
924
925                 prune_io_piece_log(td);
926
927                 do_io(td);
928
929                 clear_state = 1;
930
931                 if (td_read(td) && td->io_bytes[DDIR_READ]) {
932                         if (td->rw_end_set[DDIR_READ])
933                                 elapsed = utime_since(&td->start,
934                                                       &td->rw_end[DDIR_READ]);
935                         else
936                                 elapsed = utime_since_now(&td->start);
937
938                         runtime[DDIR_READ] += elapsed;
939                 }
940                 if (td_write(td) && td->io_bytes[DDIR_WRITE]) {
941                         if (td->rw_end_set[DDIR_WRITE])
942                                 elapsed = utime_since(&td->start,
943                                                       &td->rw_end[DDIR_WRITE]);
944                         else
945                                 elapsed = utime_since_now(&td->start);
946
947                         runtime[DDIR_WRITE] += elapsed;
948                 }
949
950                 if (td->error || td->terminate)
951                         break;
952
953                 if (!td->o.do_verify ||
954                     td->o.verify == VERIFY_NONE ||
955                     (td->io_ops->flags & FIO_UNIDIR))
956                         continue;
957
958                 if (clear_io_state(td))
959                         break;
960
961                 fio_gettime(&td->start, NULL);
962
963                 do_verify(td);
964
965                 runtime[DDIR_READ] += utime_since_now(&td->start);
966
967                 if (td->error || td->terminate)
968                         break;
969         }
970
971         update_rusage_stat(td);
972         td->ts.runtime[0] = (runtime[0] + 999) / 1000;
973         td->ts.runtime[1] = (runtime[1] + 999) / 1000;
974         td->ts.total_run_time = mtime_since_now(&td->epoch);
975         td->ts.io_bytes[0] = td->io_bytes[0];
976         td->ts.io_bytes[1] = td->io_bytes[1];
977
978         if (td->ts.bw_log)
979                 finish_log(td, td->ts.bw_log, "bw");
980         if (td->ts.slat_log)
981                 finish_log(td, td->ts.slat_log, "slat");
982         if (td->ts.clat_log)
983                 finish_log(td, td->ts.clat_log, "clat");
984         if (td->o.exec_postrun) {
985                 if (system(td->o.exec_postrun) < 0)
986                         log_err("fio: postrun %s failed\n", td->o.exec_postrun);
987         }
988
989         if (exitall_on_terminate)
990                 terminate_threads(td->groupid);
991
992 err:
993         if (td->error)
994                 printf("fio: pid=%d, err=%d/%s\n", td->pid, td->error,
995                                                         td->verror);
996         close_and_free_files(td);
997         close_ioengine(td);
998         cleanup_io_u(td);
999
1000         /*
1001          * do this very late, it will log file closing as well
1002          */
1003         if (td->o.write_iolog_file)
1004                 write_iolog_close(td);
1005
1006         options_mem_free(td);
1007         td_set_runstate(td, TD_EXITED);
1008         return (void *) (unsigned long) td->error;
1009 }
1010
1011 /*
1012  * We cannot pass the td data into a forked process, so attach the td and
1013  * pass it to the thread worker.
1014  */
1015 static int fork_main(int shmid, int offset)
1016 {
1017         struct thread_data *td;
1018         void *data, *ret;
1019
1020         data = shmat(shmid, NULL, 0);
1021         if (data == (void *) -1) {
1022                 int __err = errno;
1023
1024                 perror("shmat");
1025                 return __err;
1026         }
1027
1028         td = data + offset * sizeof(struct thread_data);
1029         ret = thread_main(td);
1030         shmdt(data);
1031         return (int) (unsigned long) ret;
1032 }
1033
1034 /*
1035  * Run over the job map and reap the threads that have exited, if any.
1036  */
1037 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1038 {
1039         struct thread_data *td;
1040         int i, cputhreads, realthreads, pending, status, ret;
1041
1042         /*
1043          * reap exited threads (TD_EXITED -> TD_REAPED)
1044          */
1045         realthreads = pending = cputhreads = 0;
1046         for_each_td(td, i) {
1047                 int flags = 0;
1048
1049                 /*
1050                  * ->io_ops is NULL for a thread that has closed its
1051                  * io engine
1052                  */
1053                 if (td->io_ops && !strcmp(td->io_ops->name, "cpuio"))
1054                         cputhreads++;
1055                 else
1056                         realthreads++;
1057
1058                 if (!td->pid) {
1059                         pending++;
1060                         continue;
1061                 }
1062                 if (td->runstate == TD_REAPED)
1063                         continue;
1064                 if (td->o.use_thread) {
1065                         if (td->runstate == TD_EXITED) {
1066                                 td_set_runstate(td, TD_REAPED);
1067                                 goto reaped;
1068                         }
1069                         continue;
1070                 }
1071
1072                 flags = WNOHANG;
1073                 if (td->runstate == TD_EXITED)
1074                         flags = 0;
1075
1076                 /*
1077                  * check if someone quit or got killed in an unusual way
1078                  */
1079                 ret = waitpid(td->pid, &status, flags);
1080                 if (ret < 0) {
1081                         if (errno == ECHILD) {
1082                                 log_err("fio: pid=%d disappeared %d\n", td->pid,
1083                                                                 td->runstate);
1084                                 td_set_runstate(td, TD_REAPED);
1085                                 goto reaped;
1086                         }
1087                         perror("waitpid");
1088                 } else if (ret == td->pid) {
1089                         if (WIFSIGNALED(status)) {
1090                                 int sig = WTERMSIG(status);
1091
1092                                 if (sig != SIGQUIT)
1093                                         log_err("fio: pid=%d, got signal=%d\n",
1094                                                                 td->pid, sig);
1095                                 td_set_runstate(td, TD_REAPED);
1096                                 goto reaped;
1097                         }
1098                         if (WIFEXITED(status)) {
1099                                 if (WEXITSTATUS(status) && !td->error)
1100                                         td->error = WEXITSTATUS(status);
1101
1102                                 td_set_runstate(td, TD_REAPED);
1103                                 goto reaped;
1104                         }
1105                 }
1106
1107                 /*
1108                  * thread is not dead, continue
1109                  */
1110                 pending++;
1111                 continue;
1112 reaped:
1113                 (*nr_running)--;
1114                 (*m_rate) -= td->o.ratemin;
1115                 (*t_rate) -= td->o.rate;
1116                 if (!td->pid)
1117                         pending--;
1118
1119                 if (td->error)
1120                         exit_value++;
1121         }
1122
1123         if (*nr_running == cputhreads && !pending && realthreads)
1124                 terminate_threads(TERMINATE_ALL);
1125 }
1126
1127 /*
1128  * Main function for kicking off and reaping jobs, as needed.
1129  */
1130 static void run_threads(void)
1131 {
1132         struct thread_data *td;
1133         unsigned long spent;
1134         int i, todo, nr_running, m_rate, t_rate, nr_started;
1135
1136         if (fio_pin_memory())
1137                 return;
1138
1139         if (!terse_output) {
1140                 printf("Starting ");
1141                 if (nr_thread)
1142                         printf("%d thread%s", nr_thread,
1143                                                 nr_thread > 1 ? "s" : "");
1144                 if (nr_process) {
1145                         if (nr_thread)
1146                                 printf(" and ");
1147                         printf("%d process%s", nr_process,
1148                                                 nr_process > 1 ? "es" : "");
1149                 }
1150                 printf("\n");
1151                 fflush(stdout);
1152         }
1153
1154         signal(SIGINT, sig_handler);
1155         signal(SIGALRM, sig_handler);
1156
1157         todo = thread_number;
1158         nr_running = 0;
1159         nr_started = 0;
1160         m_rate = t_rate = 0;
1161
1162         for_each_td(td, i) {
1163                 print_status_init(td->thread_number - 1);
1164
1165                 if (!td->o.create_serialize) {
1166                         init_disk_util(td);
1167                         continue;
1168                 }
1169
1170                 /*
1171                  * do file setup here so it happens sequentially,
1172                  * we don't want X number of threads getting their
1173                  * client data interspersed on disk
1174                  */
1175                 if (setup_files(td)) {
1176                         exit_value++;
1177                         if (td->error)
1178                                 log_err("fio: pid=%d, err=%d/%s\n", td->pid,
1179                                                         td->error, td->verror);
1180                         td_set_runstate(td, TD_REAPED);
1181                         todo--;
1182                 } else {
1183                         struct fio_file *f;
1184                         unsigned int i;
1185
1186                         /*
1187                          * for sharing to work, each job must always open
1188                          * its own files. so close them, if we opened them
1189                          * for creation
1190                          */
1191                         for_each_file(td, f, i)
1192                                 td_io_close_file(td, f);
1193                 }
1194
1195                 init_disk_util(td);
1196         }
1197
1198         set_genesis_time();
1199
1200         while (todo) {
1201                 struct thread_data *map[MAX_JOBS];
1202                 struct timeval this_start;
1203                 int this_jobs = 0, left;
1204
1205                 /*
1206                  * create threads (TD_NOT_CREATED -> TD_CREATED)
1207                  */
1208                 for_each_td(td, i) {
1209                         if (td->runstate != TD_NOT_CREATED)
1210                                 continue;
1211
1212                         /*
1213                          * never got a chance to start, killed by other
1214                          * thread for some reason
1215                          */
1216                         if (td->terminate) {
1217                                 todo--;
1218                                 continue;
1219                         }
1220
1221                         if (td->o.start_delay) {
1222                                 spent = mtime_since_genesis();
1223
1224                                 if (td->o.start_delay * 1000 > spent)
1225                                         continue;
1226                         }
1227
1228                         if (td->o.stonewall && (nr_started || nr_running)) {
1229                                 dprint(FD_PROCESS, "%s: stonewall wait\n",
1230                                                         td->o.name);
1231                                 break;
1232                         }
1233
1234                         /*
1235                          * Set state to created. Thread will transition
1236                          * to TD_INITIALIZED when it's done setting up.
1237                          */
1238                         td_set_runstate(td, TD_CREATED);
1239                         map[this_jobs++] = td;
1240                         nr_started++;
1241
1242                         if (td->o.use_thread) {
1243                                 dprint(FD_PROCESS, "will pthread_create\n");
1244                                 if (pthread_create(&td->thread, NULL,
1245                                                    thread_main, td)) {
1246                                         perror("pthread_create");
1247                                         nr_started--;
1248                                         break;
1249                                 }
1250                                 if (pthread_detach(td->thread) < 0)
1251                                         perror("pthread_detach");
1252                         } else {
1253                                 dprint(FD_PROCESS, "will fork\n");
1254                                 if (!fork()) {
1255                                         int ret = fork_main(shm_id, i);
1256
1257                                         exit(ret);
1258                                 }
1259                         }
1260                         fio_mutex_down(startup_mutex);
1261                 }
1262
1263                 /*
1264                  * Wait for the started threads to transition to
1265                  * TD_INITIALIZED.
1266                  */
1267                 fio_gettime(&this_start, NULL);
1268                 left = this_jobs;
1269                 while (left && !fio_abort) {
1270                         if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1271                                 break;
1272
1273                         usleep(100000);
1274
1275                         for (i = 0; i < this_jobs; i++) {
1276                                 td = map[i];
1277                                 if (!td)
1278                                         continue;
1279                                 if (td->runstate == TD_INITIALIZED) {
1280                                         map[i] = NULL;
1281                                         left--;
1282                                 } else if (td->runstate >= TD_EXITED) {
1283                                         map[i] = NULL;
1284                                         left--;
1285                                         todo--;
1286                                         nr_running++; /* work-around... */
1287                                 }
1288                         }
1289                 }
1290
1291                 if (left) {
1292                         log_err("fio: %d jobs failed to start\n", left);
1293                         for (i = 0; i < this_jobs; i++) {
1294                                 td = map[i];
1295                                 if (!td)
1296                                         continue;
1297                                 kill(td->pid, SIGTERM);
1298                         }
1299                         break;
1300                 }
1301
1302                 /*
1303                  * start created threads (TD_INITIALIZED -> TD_RUNNING).
1304                  */
1305                 for_each_td(td, i) {
1306                         if (td->runstate != TD_INITIALIZED)
1307                                 continue;
1308
1309                         td_set_runstate(td, TD_RUNNING);
1310                         nr_running++;
1311                         nr_started--;
1312                         m_rate += td->o.ratemin;
1313                         t_rate += td->o.rate;
1314                         todo--;
1315                         fio_mutex_up(td->mutex);
1316                 }
1317
1318                 reap_threads(&nr_running, &t_rate, &m_rate);
1319
1320                 if (todo)
1321                         usleep(100000);
1322         }
1323
1324         while (nr_running) {
1325                 reap_threads(&nr_running, &t_rate, &m_rate);
1326                 usleep(10000);
1327         }
1328
1329         update_io_ticks();
1330         fio_unpin_memory();
1331 }
1332
1333 int main(int argc, char *argv[])
1334 {
1335         long ps;
1336
1337         sinit();
1338
1339         /*
1340          * We need locale for number printing, if it isn't set then just
1341          * go with the US format.
1342          */
1343         if (!getenv("LC_NUMERIC"))
1344                 setlocale(LC_NUMERIC, "en_US");
1345
1346         if (parse_options(argc, argv))
1347                 return 1;
1348
1349         if (!thread_number)
1350                 return 0;
1351
1352         ps = sysconf(_SC_PAGESIZE);
1353         if (ps < 0) {
1354                 log_err("Failed to get page size\n");
1355                 return 1;
1356         }
1357
1358         page_size = ps;
1359         page_mask = ps - 1;
1360
1361         if (write_bw_log) {
1362                 setup_log(&agg_io_log[DDIR_READ]);
1363                 setup_log(&agg_io_log[DDIR_WRITE]);
1364         }
1365
1366         startup_mutex = fio_mutex_init(0);
1367
1368         set_genesis_time();
1369
1370         disk_util_timer_arm();
1371
1372         run_threads();
1373
1374         if (!fio_abort) {
1375                 show_run_stats();
1376                 if (write_bw_log) {
1377                         __finish_log(agg_io_log[DDIR_READ], "agg-read_bw.log");
1378                         __finish_log(agg_io_log[DDIR_WRITE],
1379                                         "agg-write_bw.log");
1380                 }
1381         }
1382
1383         fio_mutex_remove(startup_mutex);
1384         return exit_value;
1385 }