2 * fio - the flexible io tester
4 * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5 * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 #include <sys/ioctl.h>
40 #define ALIGN(buf) (char *) (((unsigned long) (buf) + MASK) & ~(MASK))
43 int thread_number = 0;
44 static char run_str[MAX_JOBS + 1];
46 static struct timeval genesis;
47 static int temp_stall_ts;
48 char *fio_inst_prefix = _INST_PREFIX;
50 static void print_thread_status(void);
52 extern unsigned long long mlock_size;
55 * Thread life cycle. Once a thread has a runstate beyond TD_INITIALIZED, it
56 * will never back again. It may cycle between running/verififying/fsyncing.
57 * Once the thread reaches TD_EXITED, it is just waiting for the core to
71 #define should_fsync(td) ((td_write(td) || td_rw(td)) && (!(td)->odirect || (td)->override_sync))
73 static volatile int startup_sem;
75 #define TERMINATE_ALL (-1)
76 #define JOB_START_TIMEOUT (5 * 1000)
78 static void terminate_threads(int group_id)
82 for (i = 0; i < thread_number; i++) {
83 struct thread_data *td = &threads[i];
85 if (group_id == TERMINATE_ALL || groupid == td->groupid) {
92 static void sig_handler(int sig)
97 disk_util_timer_arm();
98 print_thread_status();
101 printf("\nfio: terminating on signal\n");
103 terminate_threads(TERMINATE_ALL);
109 * The ->file_map[] contains a map of blocks we have or have not done io
110 * to yet. Used to make sure we cover the entire range in a fair fashion.
112 static int random_map_free(struct thread_data *td, unsigned long long block)
114 unsigned int idx = RAND_MAP_IDX(td, block);
115 unsigned int bit = RAND_MAP_BIT(td, block);
117 return (td->file_map[idx] & (1UL << bit)) == 0;
121 * Return the next free block in the map.
123 static int get_next_free_block(struct thread_data *td, unsigned long long *b)
129 while ((*b) * td->min_bs < td->io_size) {
130 if (td->file_map[i] != -1UL) {
131 *b += ffz(td->file_map[i]);
135 *b += BLOCKS_PER_MAP;
143 * Mark a given offset as used in the map.
145 static void mark_random_map(struct thread_data *td, struct io_u *io_u)
147 unsigned long long block = io_u->offset / (unsigned long long) td->min_bs;
148 unsigned int blocks = 0;
150 while (blocks < (io_u->buflen / td->min_bs)) {
151 unsigned int idx, bit;
153 if (!random_map_free(td, block))
156 idx = RAND_MAP_IDX(td, block);
157 bit = RAND_MAP_BIT(td, block);
159 assert(idx < td->num_maps);
161 td->file_map[idx] |= (1UL << bit);
166 if ((blocks * td->min_bs) < io_u->buflen)
167 io_u->buflen = blocks * td->min_bs;
171 * For random io, generate a random new block and see if it's used. Repeat
172 * until we find a free one. For sequential io, just return the end of
173 * the last io issued.
175 static int get_next_offset(struct thread_data *td, unsigned long long *offset)
177 unsigned long long b, rb;
180 if (!td->sequential) {
181 unsigned long long max_blocks = td->io_size / td->min_bs;
185 r = os_random_long(&td->random_state);
186 b = ((max_blocks - 1) * r / (unsigned long long) (RAND_MAX+1.0));
187 rb = b + (td->file_offset / td->min_bs);
189 } while (!random_map_free(td, rb) && loops);
192 if (get_next_free_block(td, &b))
196 b = td->last_pos / td->min_bs;
198 *offset = (b * td->min_bs) + td->file_offset;
199 if (*offset > td->real_file_size)
205 static unsigned int get_next_buflen(struct thread_data *td)
210 if (td->min_bs == td->max_bs)
213 r = os_random_long(&td->bsrange_state);
214 buflen = (1 + (double) (td->max_bs - 1) * r / (RAND_MAX + 1.0));
215 buflen = (buflen + td->min_bs - 1) & ~(td->min_bs - 1);
218 if (buflen > td->io_size - td->this_io_bytes[td->ddir])
219 buflen = td->io_size - td->this_io_bytes[td->ddir];
225 * Check if we are above the minimum rate given.
227 static int check_min_rate(struct thread_data *td, struct timeval *now)
234 * allow a 2 second settle period in the beginning
236 if (mtime_since(&td->start, now) < 2000)
240 * if rate blocks is set, sample is running
242 if (td->rate_bytes) {
243 spent = mtime_since(&td->lastrate, now);
244 if (spent < td->ratecycle)
247 rate = (td->this_io_bytes[ddir] - td->rate_bytes) / spent;
248 if (rate < td->ratemin) {
249 fprintf(f_out, "%s: min rate %d not met, got %ldKiB/sec\n", td->name, td->ratemin, rate);
251 terminate_threads(td->groupid);
256 td->rate_bytes = td->this_io_bytes[ddir];
257 memcpy(&td->lastrate, now, sizeof(*now));
261 static inline int runtime_exceeded(struct thread_data *td, struct timeval *t)
265 if (mtime_since(&td->epoch, t) >= td->timeout * 1000)
271 static void fill_random_bytes(struct thread_data *td,
272 unsigned char *p, unsigned int len)
278 r = os_random_double(&td->verify_state);
281 * lrand48_r seems to be broken and only fill the bottom
282 * 32-bits, even on 64-bit archs with 64-bit longs
295 static void hexdump(void *buffer, int len)
297 unsigned char *p = buffer;
300 for (i = 0; i < len; i++)
301 fprintf(f_out, "%02x", p[i]);
302 fprintf(f_out, "\n");
305 static int verify_io_u_crc32(struct verify_header *hdr, struct io_u *io_u)
307 unsigned char *p = (unsigned char *) io_u->buf;
311 c = crc32(p, hdr->len - sizeof(*hdr));
313 if (c != hdr->crc32) {
314 log_err("crc32: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
315 log_err("crc32: wanted %lx, got %lx\n", hdr->crc32, c);
322 static int verify_io_u_md5(struct verify_header *hdr, struct io_u *io_u)
324 unsigned char *p = (unsigned char *) io_u->buf;
325 struct md5_ctx md5_ctx;
327 memset(&md5_ctx, 0, sizeof(md5_ctx));
329 md5_update(&md5_ctx, p, hdr->len - sizeof(*hdr));
331 if (memcmp(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash))) {
332 log_err("md5: verify failed at %llu/%u\n", io_u->offset, io_u->buflen);
333 hexdump(hdr->md5_digest, sizeof(hdr->md5_digest));
334 hexdump(md5_ctx.hash, sizeof(md5_ctx.hash));
341 static int verify_io_u(struct io_u *io_u)
343 struct verify_header *hdr = (struct verify_header *) io_u->buf;
346 if (hdr->fio_magic != FIO_HDR_MAGIC)
349 if (hdr->verify_type == VERIFY_MD5)
350 ret = verify_io_u_md5(hdr, io_u);
351 else if (hdr->verify_type == VERIFY_CRC32)
352 ret = verify_io_u_crc32(hdr, io_u);
354 log_err("Bad verify type %d\n", hdr->verify_type);
361 static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
363 hdr->crc32 = crc32(p, len);
366 static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
368 struct md5_ctx md5_ctx;
370 memset(&md5_ctx, 0, sizeof(md5_ctx));
371 md5_update(&md5_ctx, p, len);
372 memcpy(hdr->md5_digest, md5_ctx.hash, sizeof(md5_ctx.hash));
376 * Return the data direction for the next io_u. If the job is a
377 * mixed read/write workload, check the rwmix cycle and switch if
380 static int get_rw_ddir(struct thread_data *td)
384 unsigned long elapsed;
386 gettimeofday(&now, NULL);
387 elapsed = mtime_since_now(&td->rwmix_switch);
390 * Check if it's time to seed a new data direction.
392 if (elapsed >= td->rwmixcycle) {
396 r = os_random_long(&td->rwmix_state);
397 v = 1 + (int) (100.0 * (r / (RAND_MAX + 1.0)));
398 if (v < td->rwmixread)
399 td->rwmix_ddir = DDIR_READ;
401 td->rwmix_ddir = DDIR_WRITE;
402 memcpy(&td->rwmix_switch, &now, sizeof(now));
404 return td->rwmix_ddir;
405 } else if (td_read(td))
412 * fill body of io_u->buf with random data and add a header with the
413 * crc32 or md5 sum of that data.
415 static void populate_io_u(struct thread_data *td, struct io_u *io_u)
417 unsigned char *p = (unsigned char *) io_u->buf;
418 struct verify_header hdr;
420 hdr.fio_magic = FIO_HDR_MAGIC;
421 hdr.len = io_u->buflen;
423 fill_random_bytes(td, p, io_u->buflen - sizeof(hdr));
425 if (td->verify == VERIFY_MD5) {
426 fill_md5(&hdr, p, io_u->buflen - sizeof(hdr));
427 hdr.verify_type = VERIFY_MD5;
429 fill_crc32(&hdr, p, io_u->buflen - sizeof(hdr));
430 hdr.verify_type = VERIFY_CRC32;
433 memcpy(io_u->buf, &hdr, sizeof(hdr));
436 static int td_io_prep(struct thread_data *td, struct io_u *io_u)
438 if (td->io_ops->prep && td->io_ops->prep(td, io_u))
444 void put_io_u(struct thread_data *td, struct io_u *io_u)
446 list_del(&io_u->list);
447 list_add(&io_u->list, &td->io_u_freelist);
451 static int fill_io_u(struct thread_data *td, struct io_u *io_u)
454 * If using an iolog, grab next piece if any available.
457 return read_iolog_get(td, io_u);
460 * No log, let the seq/rand engine retrieve the next position.
462 if (!get_next_offset(td, &io_u->offset)) {
463 io_u->buflen = get_next_buflen(td);
466 io_u->ddir = get_rw_ddir(td);
469 * If using a write iolog, store this entry.
472 write_iolog_put(td, io_u);
481 #define queue_full(td) list_empty(&(td)->io_u_freelist)
483 struct io_u *__get_io_u(struct thread_data *td)
485 struct io_u *io_u = NULL;
487 if (!queue_full(td)) {
488 io_u = list_entry(td->io_u_freelist.next, struct io_u, list);
492 list_del(&io_u->list);
493 list_add(&io_u->list, &td->io_u_busylist);
501 * Return an io_u to be processed. Gets a buflen and offset, sets direction,
502 * etc. The returned io_u is fully ready to be prepped and submitted.
504 static struct io_u *get_io_u(struct thread_data *td)
508 io_u = __get_io_u(td);
512 if (td->zone_bytes >= td->zone_size) {
514 td->last_pos += td->zone_skip;
517 if (fill_io_u(td, io_u)) {
522 if (io_u->buflen + io_u->offset > td->real_file_size)
523 io_u->buflen = td->real_file_size - io_u->offset;
530 if (!td->read_iolog && !td->sequential)
531 mark_random_map(td, io_u);
533 td->last_pos += io_u->buflen;
535 if (td->verify != VERIFY_NONE)
536 populate_io_u(td, io_u);
538 if (td_io_prep(td, io_u)) {
543 gettimeofday(&io_u->start_time, NULL);
547 static inline void td_set_runstate(struct thread_data *td, int runstate)
549 td->runstate = runstate;
552 static int get_next_verify(struct thread_data *td, struct io_u *io_u)
554 struct io_piece *ipo;
556 if (!list_empty(&td->io_hist_list)) {
557 ipo = list_entry(td->io_hist_list.next, struct io_piece, list);
559 list_del(&ipo->list);
561 io_u->offset = ipo->offset;
562 io_u->buflen = ipo->len;
563 io_u->ddir = DDIR_READ;
571 static int sync_td(struct thread_data *td)
573 if (td->io_ops->sync)
574 return td->io_ops->sync(td);
579 static int io_u_getevents(struct thread_data *td, int min, int max,
582 return td->io_ops->getevents(td, min, max, t);
585 static int io_u_queue(struct thread_data *td, struct io_u *io_u)
587 gettimeofday(&io_u->issue_time, NULL);
589 return td->io_ops->queue(td, io_u);
592 #define iocb_time(iocb) ((unsigned long) (iocb)->data)
594 static void io_completed(struct thread_data *td, struct io_u *io_u,
595 struct io_completion_data *icd)
600 gettimeofday(&e, NULL);
603 unsigned int bytes = io_u->buflen - io_u->resid;
604 const int idx = io_u->ddir;
606 td->io_blocks[idx]++;
607 td->io_bytes[idx] += bytes;
608 td->zone_bytes += bytes;
609 td->this_io_bytes[idx] += bytes;
611 msec = mtime_since(&io_u->issue_time, &e);
613 add_clat_sample(td, idx, msec);
614 add_bw_sample(td, idx);
616 if ((td_rw(td) || td_write(td)) && idx == DDIR_WRITE)
617 log_io_piece(td, io_u);
619 icd->bytes_done[idx] += bytes;
621 icd->error = io_u->error;
624 static void ios_completed(struct thread_data *td,struct io_completion_data *icd)
630 icd->bytes_done[0] = icd->bytes_done[1] = 0;
632 for (i = 0; i < icd->nr; i++) {
633 io_u = td->io_ops->event(td, i);
635 io_completed(td, io_u, icd);
641 * When job exits, we can cancel the in-flight IO if we are using async
642 * io. Attempt to do so.
644 static void cleanup_pending_aio(struct thread_data *td)
646 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
647 struct list_head *entry, *n;
648 struct io_completion_data icd;
653 * get immediately available events, if any
655 r = io_u_getevents(td, 0, td->cur_depth, &ts);
658 ios_completed(td, &icd);
662 * now cancel remaining active events
664 if (td->io_ops->cancel) {
665 list_for_each_safe(entry, n, &td->io_u_busylist) {
666 io_u = list_entry(entry, struct io_u, list);
668 r = td->io_ops->cancel(td, io_u);
675 r = io_u_getevents(td, td->cur_depth, td->cur_depth, NULL);
678 ios_completed(td, &icd);
683 static int do_io_u_verify(struct thread_data *td, struct io_u **io_u)
685 struct io_u *v_io_u = *io_u;
689 ret = verify_io_u(v_io_u);
690 put_io_u(td, v_io_u);
698 * The main verify engine. Runs over the writes we previusly submitted,
699 * reads the blocks back in, and checks the crc/md5 of the data.
701 static void do_verify(struct thread_data *td)
704 struct io_u *io_u, *v_io_u = NULL;
705 struct io_completion_data icd;
708 td_set_runstate(td, TD_VERIFYING);
714 gettimeofday(&t, NULL);
715 if (runtime_exceeded(td, &t))
718 io_u = __get_io_u(td);
722 if (get_next_verify(td, io_u)) {
727 if (td_io_prep(td, io_u)) {
732 ret = io_u_queue(td, io_u);
740 * we have one pending to verify, do that while
741 * we are doing io on the next one
743 if (do_io_u_verify(td, &v_io_u))
746 ret = io_u_getevents(td, 1, 1, NULL);
753 v_io_u = td->io_ops->event(td, 0);
756 io_completed(td, v_io_u, &icd);
759 td_verror(td, icd.error);
760 put_io_u(td, v_io_u);
766 * if we can't submit more io, we need to verify now
768 if (queue_full(td) && do_io_u_verify(td, &v_io_u))
773 do_io_u_verify(td, &v_io_u);
776 cleanup_pending_aio(td);
778 td_set_runstate(td, TD_RUNNING);
782 * Not really an io thread, all it does is burn CPU cycles in the specified
785 static void do_cpuio(struct thread_data *td)
788 int split = 100 / td->cpuload;
791 while (!td->terminate) {
792 gettimeofday(&e, NULL);
794 if (runtime_exceeded(td, &e))
800 usec_sleep(td, 10000);
807 * Main IO worker function. It retrieves io_u's to process and queues
808 * and reaps them, checking for rate and errors along the way.
810 static void do_io(struct thread_data *td)
812 struct io_completion_data icd;
816 td_set_runstate(td, TD_RUNNING);
818 while (td->this_io_bytes[td->ddir] < td->io_size) {
819 struct timespec ts = { .tv_sec = 0, .tv_nsec = 0};
820 struct timespec *timeout;
821 int ret, min_evts = 0;
831 memcpy(&s, &io_u->start_time, sizeof(s));
833 ret = io_u_queue(td, io_u);
840 add_slat_sample(td, io_u->ddir, mtime_since(&io_u->start_time, &io_u->issue_time));
842 if (td->cur_depth < td->iodepth) {
850 ret = io_u_getevents(td, min_evts, td->cur_depth, timeout);
858 ios_completed(td, &icd);
860 td_verror(td, icd.error);
865 * the rate is batched for now, it should work for batches
866 * of completions except the very first one which may look
869 gettimeofday(&e, NULL);
870 usec = utime_since(&s, &e);
872 rate_throttle(td, usec, icd.bytes_done[td->ddir]);
874 if (check_min_rate(td, &e)) {
875 td_verror(td, ENOMEM);
879 if (runtime_exceeded(td, &e))
883 usec_sleep(td, td->thinktime);
885 if (should_fsync(td) && td->fsync_blocks &&
886 (td->io_blocks[DDIR_WRITE] % td->fsync_blocks) == 0)
891 cleanup_pending_aio(td);
893 if (should_fsync(td) && td->end_fsync) {
894 td_set_runstate(td, TD_FSYNCING);
899 static int init_io(struct thread_data *td)
901 if (td->io_ops->init)
902 return td->io_ops->init(td);
907 static void cleanup_io_u(struct thread_data *td)
909 struct list_head *entry, *n;
912 list_for_each_safe(entry, n, &td->io_u_freelist) {
913 io_u = list_entry(entry, struct io_u, list);
915 list_del(&io_u->list);
919 if (td->mem_type == MEM_MALLOC)
920 free(td->orig_buffer);
921 else if (td->mem_type == MEM_SHM) {
922 struct shmid_ds sbuf;
924 shmdt(td->orig_buffer);
925 shmctl(td->shm_id, IPC_RMID, &sbuf);
926 } else if (td->mem_type == MEM_MMAP)
927 munmap(td->orig_buffer, td->orig_buffer_size);
929 log_err("Bad memory type %d\n", td->mem_type);
931 td->orig_buffer = NULL;
934 static int init_io_u(struct thread_data *td)
940 if (td->io_ops->flags & FIO_CPUIO)
943 if (td->io_ops->flags & FIO_SYNCIO)
946 max_units = td->iodepth;
948 td->orig_buffer_size = td->max_bs * max_units + MASK;
950 if (td->mem_type == MEM_MALLOC)
951 td->orig_buffer = malloc(td->orig_buffer_size);
952 else if (td->mem_type == MEM_SHM) {
953 td->shm_id = shmget(IPC_PRIVATE, td->orig_buffer_size, IPC_CREAT | 0600);
954 if (td->shm_id < 0) {
955 td_verror(td, errno);
960 td->orig_buffer = shmat(td->shm_id, NULL, 0);
961 if (td->orig_buffer == (void *) -1) {
962 td_verror(td, errno);
964 td->orig_buffer = NULL;
967 } else if (td->mem_type == MEM_MMAP) {
968 td->orig_buffer = mmap(NULL, td->orig_buffer_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
969 if (td->orig_buffer == MAP_FAILED) {
970 td_verror(td, errno);
972 td->orig_buffer = NULL;
977 p = ALIGN(td->orig_buffer);
978 for (i = 0; i < max_units; i++) {
979 io_u = malloc(sizeof(*io_u));
980 memset(io_u, 0, sizeof(*io_u));
981 INIT_LIST_HEAD(&io_u->list);
983 io_u->buf = p + td->max_bs * i;
985 list_add(&io_u->list, &td->io_u_freelist);
991 static int create_file(struct thread_data *td, unsigned long long size)
993 unsigned long long left;
999 * unless specifically asked for overwrite, let normal io extend it
1001 if (!td->overwrite) {
1002 td->real_file_size = size;
1007 log_err("Need size for create\n");
1008 td_verror(td, EINVAL);
1013 fprintf(f_out, "%s: Laying out IO file (%LuMiB)\n",td->name,size >> 20);
1015 td->fd = open(td->file_name, O_WRONLY | O_CREAT | O_TRUNC, 0644);
1017 td_verror(td, errno);
1021 if (ftruncate(td->fd, td->file_size) == -1) {
1022 td_verror(td, errno);
1026 td->io_size = td->file_size;
1027 b = malloc(td->max_bs);
1028 memset(b, 0, td->max_bs);
1031 while (left && !td->terminate) {
1036 r = write(td->fd, b, bs);
1038 if (r == (int) bs) {
1043 td_verror(td, errno);
1052 unlink(td->file_name);
1053 else if (td->create_fsync)
1065 static int file_size(struct thread_data *td)
1069 if (td->overwrite) {
1070 if (fstat(td->fd, &st) == -1) {
1071 td_verror(td, errno);
1075 td->real_file_size = st.st_size;
1077 if (!td->file_size || td->file_size > td->real_file_size)
1078 td->file_size = td->real_file_size;
1081 td->file_size -= td->file_offset;
1085 static int bdev_size(struct thread_data *td)
1087 unsigned long long bytes;
1090 r = blockdev_size(td->fd, &bytes);
1096 td->real_file_size = bytes;
1099 * no extend possibilities, so limit size to device size if too large
1101 if (!td->file_size || td->file_size > td->real_file_size)
1102 td->file_size = td->real_file_size;
1104 td->file_size -= td->file_offset;
1108 static int get_file_size(struct thread_data *td)
1112 if (td->filetype == FIO_TYPE_FILE)
1113 ret = file_size(td);
1114 else if (td->filetype == FIO_TYPE_BD)
1115 ret = bdev_size(td);
1117 td->real_file_size = -1;
1122 if (td->file_offset > td->real_file_size) {
1123 log_err("%s: offset extends end (%Lu > %Lu)\n", td->name, td->file_offset, td->real_file_size);
1127 td->io_size = td->file_size;
1128 if (td->io_size == 0) {
1129 log_err("%s: no io blocks\n", td->name);
1130 td_verror(td, EINVAL);
1135 td->zone_size = td->io_size;
1137 td->total_io_size = td->io_size * td->loops;
1141 static int setup_file_mmap(struct thread_data *td)
1146 flags = PROT_READ | PROT_WRITE;
1147 else if (td_write(td)) {
1150 if (td->verify != VERIFY_NONE)
1155 td->mmap = mmap(NULL, td->file_size, flags, MAP_SHARED, td->fd, td->file_offset);
1156 if (td->mmap == MAP_FAILED) {
1158 td_verror(td, errno);
1162 if (td->invalidate_cache) {
1163 if (madvise(td->mmap, td->file_size, MADV_DONTNEED) < 0) {
1164 td_verror(td, errno);
1169 if (td->sequential) {
1170 if (madvise(td->mmap, td->file_size, MADV_SEQUENTIAL) < 0) {
1171 td_verror(td, errno);
1175 if (madvise(td->mmap, td->file_size, MADV_RANDOM) < 0) {
1176 td_verror(td, errno);
1184 static int setup_file_plain(struct thread_data *td)
1186 if (td->invalidate_cache) {
1187 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_DONTNEED) < 0) {
1188 td_verror(td, errno);
1193 if (td->sequential) {
1194 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_SEQUENTIAL) < 0) {
1195 td_verror(td, errno);
1199 if (fadvise(td->fd, td->file_offset, td->file_size, POSIX_FADV_RANDOM) < 0) {
1200 td_verror(td, errno);
1208 static int setup_file(struct thread_data *td)
1213 if (td->io_ops->setup)
1214 return td->io_ops->setup(td);
1216 if (stat(td->file_name, &st) == -1) {
1217 if (errno != ENOENT) {
1218 td_verror(td, errno);
1221 if (!td->create_file) {
1222 td_verror(td, ENOENT);
1225 if (create_file(td, td->file_size))
1227 } else if (td->filetype == FIO_TYPE_FILE &&
1228 st.st_size < (off_t) td->file_size) {
1229 if (create_file(td, td->file_size))
1234 flags |= OS_O_DIRECT;
1236 if (td_write(td) || td_rw(td)) {
1237 if (td->filetype == FIO_TYPE_FILE) {
1248 td->fd = open(td->file_name, flags, 0600);
1250 if (td->filetype == FIO_TYPE_CHAR)
1255 td->fd = open(td->file_name, flags);
1259 td_verror(td, errno);
1263 if (get_file_size(td))
1266 if (td->io_ops->flags & FIO_MMAPIO)
1267 return setup_file_mmap(td);
1269 return setup_file_plain(td);
1272 static int switch_ioscheduler(struct thread_data *td)
1274 char tmp[256], tmp2[128];
1278 sprintf(tmp, "%s/queue/scheduler", td->sysfs_root);
1280 f = fopen(tmp, "r+");
1282 td_verror(td, errno);
1289 ret = fwrite(td->ioscheduler, strlen(td->ioscheduler), 1, f);
1290 if (ferror(f) || ret != 1) {
1291 td_verror(td, errno);
1299 * Read back and check that the selected scheduler is now the default.
1301 ret = fread(tmp, 1, sizeof(tmp), f);
1302 if (ferror(f) || ret < 0) {
1303 td_verror(td, errno);
1308 sprintf(tmp2, "[%s]", td->ioscheduler);
1309 if (!strstr(tmp, tmp2)) {
1310 log_err("fio: io scheduler %s not found\n", td->ioscheduler);
1311 td_verror(td, EINVAL);
1320 static void clear_io_state(struct thread_data *td)
1322 if (td->io_ops->flags & FIO_SYNCIO)
1323 lseek(td->fd, SEEK_SET, 0);
1326 td->stat_io_bytes[0] = td->stat_io_bytes[1] = 0;
1327 td->this_io_bytes[0] = td->this_io_bytes[1] = 0;
1331 memset(td->file_map, 0, td->num_maps * sizeof(long));
1335 * Entry point for the thread based jobs. The process based jobs end up
1336 * here as well, after a little setup.
1338 static void *thread_main(void *data)
1340 struct thread_data *td = data;
1342 if (!td->use_thread)
1347 INIT_LIST_HEAD(&td->io_u_freelist);
1348 INIT_LIST_HEAD(&td->io_u_busylist);
1349 INIT_LIST_HEAD(&td->io_hist_list);
1350 INIT_LIST_HEAD(&td->io_log_list);
1355 if (fio_setaffinity(td) == -1) {
1356 td_verror(td, errno);
1367 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, td->ioprio) == -1) {
1368 td_verror(td, errno);
1373 if (nice(td->nice) == -1) {
1374 td_verror(td, errno);
1378 if (init_random_state(td))
1381 if (td->ioscheduler && switch_ioscheduler(td))
1384 td_set_runstate(td, TD_INITIALIZED);
1385 fio_sem_up(&startup_sem);
1386 fio_sem_down(&td->mutex);
1388 if (!td->create_serialize && setup_file(td))
1391 gettimeofday(&td->epoch, NULL);
1393 if (td->exec_prerun)
1394 system(td->exec_prerun);
1396 while (td->loops--) {
1397 getrusage(RUSAGE_SELF, &td->ru_start);
1398 gettimeofday(&td->start, NULL);
1399 memcpy(&td->stat_sample_time, &td->start, sizeof(td->start));
1402 memcpy(&td->lastrate, &td->stat_sample_time, sizeof(td->lastrate));
1405 prune_io_piece_log(td);
1407 if (td->io_ops->flags & FIO_CPUIO)
1412 td->runtime[td->ddir] += mtime_since_now(&td->start);
1413 if (td_rw(td) && td->io_bytes[td->ddir ^ 1])
1414 td->runtime[td->ddir ^ 1] = td->runtime[td->ddir];
1416 update_rusage_stat(td);
1418 if (td->error || td->terminate)
1421 if (td->verify == VERIFY_NONE)
1425 gettimeofday(&td->start, NULL);
1429 td->runtime[DDIR_READ] += mtime_since_now(&td->start);
1431 if (td->error || td->terminate)
1436 finish_log(td, td->bw_log, "bw");
1438 finish_log(td, td->slat_log, "slat");
1440 finish_log(td, td->clat_log, "clat");
1441 if (td->write_iolog)
1442 write_iolog_close(td);
1443 if (td->exec_postrun)
1444 system(td->exec_postrun);
1446 if (exitall_on_terminate)
1447 terminate_threads(td->groupid);
1455 munmap(td->mmap, td->file_size);
1458 td_set_runstate(td, TD_EXITED);
1464 * We cannot pass the td data into a forked process, so attach the td and
1465 * pass it to the thread worker.
1467 static void *fork_main(int shmid, int offset)
1469 struct thread_data *td;
1472 data = shmat(shmid, NULL, 0);
1473 if (data == (void *) -1) {
1478 td = data + offset * sizeof(struct thread_data);
1485 * Sets the status of the 'td' in the printed status map.
1487 static void check_str_update(struct thread_data *td)
1489 char c = run_str[td->thread_number - 1];
1491 switch (td->runstate) {
1504 } else if (td_read(td)) {
1525 case TD_INITIALIZED:
1528 case TD_NOT_CREATED:
1532 log_err("state %d\n", td->runstate);
1535 run_str[td->thread_number - 1] = c;
1539 * Convert seconds to a printable string.
1541 static void eta_to_str(char *str, int eta_sec)
1543 unsigned int d, h, m, s;
1544 static int always_d, always_h;
1556 if (d || always_d) {
1558 str += sprintf(str, "%02dd:", d);
1560 if (h || always_h) {
1562 str += sprintf(str, "%02dh:", h);
1565 str += sprintf(str, "%02dm:", m);
1566 str += sprintf(str, "%02ds", s);
1570 * Best effort calculation of the estimated pending runtime of a job.
1572 static int thread_eta(struct thread_data *td, unsigned long elapsed)
1574 unsigned long long bytes_total, bytes_done;
1575 unsigned int eta_sec = 0;
1577 bytes_total = td->total_io_size;
1580 * if writing, bytes_total will be twice the size. If mixing,
1581 * assume a 50/50 split and thus bytes_total will be 50% larger.
1585 bytes_total = bytes_total * 3 / 2;
1589 if (td->zone_size && td->zone_skip)
1590 bytes_total /= (td->zone_skip / td->zone_size);
1592 if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING) {
1595 bytes_done = td->io_bytes[DDIR_READ] + td->io_bytes[DDIR_WRITE];
1596 perc = (double) bytes_done / (double) bytes_total;
1600 eta_sec = (elapsed * (1.0 / perc)) - elapsed;
1602 if (td->timeout && eta_sec > (td->timeout - elapsed))
1603 eta_sec = td->timeout - elapsed;
1604 } else if (td->runstate == TD_NOT_CREATED || td->runstate == TD_CREATED
1605 || td->runstate == TD_INITIALIZED) {
1606 int t_eta = 0, r_eta = 0;
1609 * We can only guess - assume it'll run the full timeout
1610 * if given, otherwise assume it'll run at the specified rate.
1613 t_eta = td->timeout + td->start_delay - elapsed;
1615 r_eta = (bytes_total / 1024) / td->rate;
1616 r_eta += td->start_delay - elapsed;
1620 eta_sec = min(r_eta, t_eta);
1629 * thread is already done or waiting for fsync
1638 * Print status of the jobs we know about. This includes rate estimates,
1639 * ETA, thread state, etc.
1641 static void print_thread_status(void)
1643 unsigned long elapsed = time_since_now(&genesis);
1644 int i, nr_running, nr_pending, t_rate, m_rate, *eta_secs, eta_sec;
1648 if (temp_stall_ts || terse_output)
1651 eta_secs = malloc(thread_number * sizeof(int));
1652 memset(eta_secs, 0, thread_number * sizeof(int));
1654 nr_pending = nr_running = t_rate = m_rate = 0;
1655 for (i = 0; i < thread_number; i++) {
1656 struct thread_data *td = &threads[i];
1658 if (td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING||
1659 td->runstate == TD_FSYNCING) {
1662 m_rate += td->ratemin;
1663 } else if (td->runstate < TD_RUNNING)
1667 eta_secs[i] = thread_eta(td, elapsed);
1669 eta_secs[i] = INT_MAX;
1671 check_str_update(td);
1674 if (exitall_on_terminate)
1679 for (i = 0; i < thread_number; i++) {
1680 if (exitall_on_terminate) {
1681 if (eta_secs[i] < eta_sec)
1682 eta_sec = eta_secs[i];
1684 if (eta_secs[i] > eta_sec)
1685 eta_sec = eta_secs[i];
1689 if (eta_sec != INT_MAX && elapsed) {
1690 perc = (double) elapsed / (double) (elapsed + eta_sec);
1691 eta_to_str(eta_str, eta_sec);
1694 if (!nr_running && !nr_pending)
1697 printf("Threads running: %d", nr_running);
1698 if (m_rate || t_rate)
1699 printf(", commitrate %d/%dKiB/sec", t_rate, m_rate);
1700 if (eta_sec != INT_MAX && nr_running) {
1702 printf(": [%s] [%3.2f%% done] [eta %s]", run_str, perc,eta_str);
1710 * Run over the job map and reap the threads that have exited, if any.
1712 static void reap_threads(int *nr_running, int *t_rate, int *m_rate)
1717 * reap exited threads (TD_EXITED -> TD_REAPED)
1719 for (i = 0, cputhreads = 0; i < thread_number; i++) {
1720 struct thread_data *td = &threads[i];
1722 if (td->io_ops->flags & FIO_CPUIO)
1725 if (td->runstate != TD_EXITED)
1728 td_set_runstate(td, TD_REAPED);
1730 if (td->use_thread) {
1733 if (pthread_join(td->thread, (void *) &ret))
1734 perror("thread_join");
1736 waitpid(td->pid, NULL, 0);
1739 (*m_rate) -= td->ratemin;
1740 (*t_rate) -= td->rate;
1743 if (*nr_running == cputhreads)
1744 terminate_threads(TERMINATE_ALL);
1747 static void fio_unpin_memory(void *pinned)
1750 if (munlock(pinned, mlock_size) < 0)
1752 munmap(pinned, mlock_size);
1756 static void *fio_pin_memory(void)
1758 unsigned long long phys_mem;
1765 * Don't allow mlock of more than real_mem-128MB
1767 phys_mem = os_phys_mem();
1769 if ((mlock_size + 128 * 1024 * 1024) > phys_mem) {
1770 mlock_size = phys_mem - 128 * 1024 * 1024;
1771 fprintf(f_out, "fio: limiting mlocked memory to %lluMiB\n", mlock_size >> 20);
1775 ptr = mmap(NULL, mlock_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | OS_MAP_ANON, 0, 0);
1777 perror("malloc locked mem");
1780 if (mlock(ptr, mlock_size) < 0) {
1781 munmap(ptr, mlock_size);
1790 * Main function for kicking off and reaping jobs, as needed.
1792 static void run_threads(void)
1794 struct thread_data *td;
1795 unsigned long spent;
1796 int i, todo, nr_running, m_rate, t_rate, nr_started;
1799 mlocked_mem = fio_pin_memory();
1801 if (!terse_output) {
1802 printf("Starting %d thread%s\n", thread_number, thread_number > 1 ? "s" : "");
1806 signal(SIGINT, sig_handler);
1807 signal(SIGALRM, sig_handler);
1809 todo = thread_number;
1812 m_rate = t_rate = 0;
1814 for (i = 0; i < thread_number; i++) {
1817 run_str[td->thread_number - 1] = 'P';
1821 if (!td->create_serialize)
1825 * do file setup here so it happens sequentially,
1826 * we don't want X number of threads getting their
1827 * client data interspersed on disk
1829 if (setup_file(td)) {
1830 td_set_runstate(td, TD_REAPED);
1835 gettimeofday(&genesis, NULL);
1838 struct thread_data *map[MAX_JOBS];
1839 struct timeval this_start;
1840 int this_jobs = 0, left;
1843 * create threads (TD_NOT_CREATED -> TD_CREATED)
1845 for (i = 0; i < thread_number; i++) {
1848 if (td->runstate != TD_NOT_CREATED)
1852 * never got a chance to start, killed by other
1853 * thread for some reason
1855 if (td->terminate) {
1860 if (td->start_delay) {
1861 spent = mtime_since_now(&genesis);
1863 if (td->start_delay * 1000 > spent)
1867 if (td->stonewall && (nr_started || nr_running))
1871 * Set state to created. Thread will transition
1872 * to TD_INITIALIZED when it's done setting up.
1874 td_set_runstate(td, TD_CREATED);
1875 map[this_jobs++] = td;
1876 fio_sem_init(&startup_sem, 1);
1879 if (td->use_thread) {
1880 if (pthread_create(&td->thread, NULL, thread_main, td)) {
1881 perror("thread_create");
1886 fio_sem_down(&startup_sem);
1888 fork_main(shm_id, i);
1895 * Wait for the started threads to transition to
1898 gettimeofday(&this_start, NULL);
1901 if (mtime_since_now(&this_start) > JOB_START_TIMEOUT)
1906 for (i = 0; i < this_jobs; i++) {
1910 if (td->runstate == TD_INITIALIZED) {
1913 } else if (td->runstate >= TD_EXITED) {
1917 nr_running++; /* work-around... */
1923 log_err("fio: %d jobs failed to start\n", left);
1924 for (i = 0; i < this_jobs; i++) {
1928 kill(td->pid, SIGTERM);
1934 * start created threads (TD_INITIALIZED -> TD_RUNNING).
1936 for (i = 0; i < thread_number; i++) {
1939 if (td->runstate != TD_INITIALIZED)
1942 td_set_runstate(td, TD_RUNNING);
1945 m_rate += td->ratemin;
1948 fio_sem_up(&td->mutex);
1951 reap_threads(&nr_running, &t_rate, &m_rate);
1957 while (nr_running) {
1958 reap_threads(&nr_running, &t_rate, &m_rate);
1963 fio_unpin_memory(mlocked_mem);
1966 int main(int argc, char *argv[])
1968 if (parse_options(argc, argv))
1971 if (!thread_number) {
1972 log_err("Nothing to do\n");
1976 disk_util_timer_arm();