Merge branch 'master' of https://github.com/bvanassche/fio into master
[fio.git] / iolog.c
1 /*
2  * Code related to writing an iolog of what a thread is doing, and to
3  * later read that back and replay
4  */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <sys/types.h>
9 #include <sys/stat.h>
10 #include <unistd.h>
11 #ifdef CONFIG_ZLIB
12 #include <zlib.h>
13 #endif
14
15 #include "flist.h"
16 #include "fio.h"
17 #include "trim.h"
18 #include "filelock.h"
19 #include "smalloc.h"
20 #include "blktrace.h"
21 #include "pshared.h"
22 #include "lib/roundup.h"
23
24 #include <netinet/in.h>
25 #include <netinet/tcp.h>
26 #include <arpa/inet.h>
27 #include <sys/stat.h>
28 #include <sys/socket.h>
29 #include <sys/un.h>
30
31 static int iolog_flush(struct io_log *log);
32
33 static const char iolog_ver2[] = "fio version 2 iolog";
34
35 void queue_io_piece(struct thread_data *td, struct io_piece *ipo)
36 {
37         flist_add_tail(&ipo->list, &td->io_log_list);
38         td->total_io_size += ipo->len;
39 }
40
41 void log_io_u(const struct thread_data *td, const struct io_u *io_u)
42 {
43         if (!td->o.write_iolog_file)
44                 return;
45
46         fprintf(td->iolog_f, "%s %s %llu %llu\n", io_u->file->file_name,
47                                                 io_ddir_name(io_u->ddir),
48                                                 io_u->offset, io_u->buflen);
49 }
50
51 void log_file(struct thread_data *td, struct fio_file *f,
52               enum file_log_act what)
53 {
54         const char *act[] = { "add", "open", "close" };
55
56         assert(what < 3);
57
58         if (!td->o.write_iolog_file)
59                 return;
60
61
62         /*
63          * this happens on the pre-open/close done before the job starts
64          */
65         if (!td->iolog_f)
66                 return;
67
68         fprintf(td->iolog_f, "%s %s\n", f->file_name, act[what]);
69 }
70
71 static void iolog_delay(struct thread_data *td, unsigned long delay)
72 {
73         uint64_t usec = utime_since_now(&td->last_issue);
74         unsigned long orig_delay = delay;
75         uint64_t this_delay;
76         struct timespec ts;
77
78         if (delay < td->time_offset) {
79                 td->time_offset = 0;
80                 return;
81         }
82
83         delay -= td->time_offset;
84         if (delay < usec)
85                 return;
86
87         delay -= usec;
88
89         fio_gettime(&ts, NULL);
90         while (delay && !td->terminate) {
91                 this_delay = delay;
92                 if (this_delay > 500000)
93                         this_delay = 500000;
94
95                 usec_sleep(td, this_delay);
96                 delay -= this_delay;
97         }
98
99         usec = utime_since_now(&ts);
100         if (usec > orig_delay)
101                 td->time_offset = usec - orig_delay;
102         else
103                 td->time_offset = 0;
104 }
105
106 static int ipo_special(struct thread_data *td, struct io_piece *ipo)
107 {
108         struct fio_file *f;
109         int ret;
110
111         /*
112          * Not a special ipo
113          */
114         if (ipo->ddir != DDIR_INVAL)
115                 return 0;
116
117         f = td->files[ipo->fileno];
118
119         switch (ipo->file_action) {
120         case FIO_LOG_OPEN_FILE:
121                 if (td->o.replay_redirect && fio_file_open(f)) {
122                         dprint(FD_FILE, "iolog: ignoring re-open of file %s\n",
123                                         f->file_name);
124                         break;
125                 }
126                 ret = td_io_open_file(td, f);
127                 if (!ret)
128                         break;
129                 td_verror(td, ret, "iolog open file");
130                 return -1;
131         case FIO_LOG_CLOSE_FILE:
132                 td_io_close_file(td, f);
133                 break;
134         case FIO_LOG_UNLINK_FILE:
135                 td_io_unlink_file(td, f);
136                 break;
137         default:
138                 log_err("fio: bad file action %d\n", ipo->file_action);
139                 break;
140         }
141
142         return 1;
143 }
144
145 static bool read_iolog2(struct thread_data *td);
146
147 int read_iolog_get(struct thread_data *td, struct io_u *io_u)
148 {
149         struct io_piece *ipo;
150         unsigned long elapsed;
151
152         while (!flist_empty(&td->io_log_list)) {
153                 int ret;
154                 if (td->o.read_iolog_chunked) {
155                         if (td->io_log_checkmark == td->io_log_current) {
156                                 if (!read_iolog2(td))
157                                         return 1;
158                         }
159                         td->io_log_current--;
160                 }
161                 ipo = flist_first_entry(&td->io_log_list, struct io_piece, list);
162                 flist_del(&ipo->list);
163                 remove_trim_entry(td, ipo);
164
165                 ret = ipo_special(td, ipo);
166                 if (ret < 0) {
167                         free(ipo);
168                         break;
169                 } else if (ret > 0) {
170                         free(ipo);
171                         continue;
172                 }
173
174                 io_u->ddir = ipo->ddir;
175                 if (ipo->ddir != DDIR_WAIT) {
176                         io_u->offset = ipo->offset;
177                         io_u->buflen = ipo->len;
178                         io_u->file = td->files[ipo->fileno];
179                         get_file(io_u->file);
180                         dprint(FD_IO, "iolog: get %llu/%llu/%s\n", io_u->offset,
181                                                 io_u->buflen, io_u->file->file_name);
182                         if (ipo->delay)
183                                 iolog_delay(td, ipo->delay);
184                 } else {
185                         elapsed = mtime_since_genesis();
186                         if (ipo->delay > elapsed)
187                                 usec_sleep(td, (ipo->delay - elapsed) * 1000);
188                 }
189
190                 free(ipo);
191
192                 if (io_u->ddir != DDIR_WAIT)
193                         return 0;
194         }
195
196         td->done = 1;
197         return 1;
198 }
199
200 void prune_io_piece_log(struct thread_data *td)
201 {
202         struct io_piece *ipo;
203         struct fio_rb_node *n;
204
205         while ((n = rb_first(&td->io_hist_tree)) != NULL) {
206                 ipo = rb_entry(n, struct io_piece, rb_node);
207                 rb_erase(n, &td->io_hist_tree);
208                 remove_trim_entry(td, ipo);
209                 td->io_hist_len--;
210                 free(ipo);
211         }
212
213         while (!flist_empty(&td->io_hist_list)) {
214                 ipo = flist_first_entry(&td->io_hist_list, struct io_piece, list);
215                 flist_del(&ipo->list);
216                 remove_trim_entry(td, ipo);
217                 td->io_hist_len--;
218                 free(ipo);
219         }
220 }
221
222 /*
223  * log a successful write, so we can unwind the log for verify
224  */
225 void log_io_piece(struct thread_data *td, struct io_u *io_u)
226 {
227         struct fio_rb_node **p, *parent;
228         struct io_piece *ipo, *__ipo;
229
230         ipo = calloc(1, sizeof(struct io_piece));
231         init_ipo(ipo);
232         ipo->file = io_u->file;
233         ipo->offset = io_u->offset;
234         ipo->len = io_u->buflen;
235         ipo->numberio = io_u->numberio;
236         ipo->flags = IP_F_IN_FLIGHT;
237
238         io_u->ipo = ipo;
239
240         if (io_u_should_trim(td, io_u)) {
241                 flist_add_tail(&ipo->trim_list, &td->trim_list);
242                 td->trim_entries++;
243         }
244
245         /*
246          * Only sort writes if we don't have a random map in which case we need
247          * to check for duplicate blocks and drop the old one, which we rely on
248          * the rb insert/lookup for handling.
249          */
250         if (file_randommap(td, ipo->file)) {
251                 INIT_FLIST_HEAD(&ipo->list);
252                 flist_add_tail(&ipo->list, &td->io_hist_list);
253                 ipo->flags |= IP_F_ONLIST;
254                 td->io_hist_len++;
255                 return;
256         }
257
258         RB_CLEAR_NODE(&ipo->rb_node);
259
260         /*
261          * Sort the entry into the verification list
262          */
263 restart:
264         p = &td->io_hist_tree.rb_node;
265         parent = NULL;
266         while (*p) {
267                 int overlap = 0;
268                 parent = *p;
269
270                 __ipo = rb_entry(parent, struct io_piece, rb_node);
271                 if (ipo->file < __ipo->file)
272                         p = &(*p)->rb_left;
273                 else if (ipo->file > __ipo->file)
274                         p = &(*p)->rb_right;
275                 else if (ipo->offset < __ipo->offset) {
276                         p = &(*p)->rb_left;
277                         overlap = ipo->offset + ipo->len > __ipo->offset;
278                 }
279                 else if (ipo->offset > __ipo->offset) {
280                         p = &(*p)->rb_right;
281                         overlap = __ipo->offset + __ipo->len > ipo->offset;
282                 }
283                 else
284                         overlap = 1;
285
286                 if (overlap) {
287                         dprint(FD_IO, "iolog: overlap %llu/%lu, %llu/%lu\n",
288                                 __ipo->offset, __ipo->len,
289                                 ipo->offset, ipo->len);
290                         td->io_hist_len--;
291                         rb_erase(parent, &td->io_hist_tree);
292                         remove_trim_entry(td, __ipo);
293                         if (!(__ipo->flags & IP_F_IN_FLIGHT))
294                                 free(__ipo);
295                         goto restart;
296                 }
297         }
298
299         rb_link_node(&ipo->rb_node, parent, p);
300         rb_insert_color(&ipo->rb_node, &td->io_hist_tree);
301         ipo->flags |= IP_F_ONRB;
302         td->io_hist_len++;
303 }
304
305 void unlog_io_piece(struct thread_data *td, struct io_u *io_u)
306 {
307         struct io_piece *ipo = io_u->ipo;
308
309         if (td->ts.nr_block_infos) {
310                 uint32_t *info = io_u_block_info(td, io_u);
311                 if (BLOCK_INFO_STATE(*info) < BLOCK_STATE_TRIM_FAILURE) {
312                         if (io_u->ddir == DDIR_TRIM)
313                                 *info = BLOCK_INFO_SET_STATE(*info,
314                                                 BLOCK_STATE_TRIM_FAILURE);
315                         else if (io_u->ddir == DDIR_WRITE)
316                                 *info = BLOCK_INFO_SET_STATE(*info,
317                                                 BLOCK_STATE_WRITE_FAILURE);
318                 }
319         }
320
321         if (!ipo)
322                 return;
323
324         if (ipo->flags & IP_F_ONRB)
325                 rb_erase(&ipo->rb_node, &td->io_hist_tree);
326         else if (ipo->flags & IP_F_ONLIST)
327                 flist_del(&ipo->list);
328
329         free(ipo);
330         io_u->ipo = NULL;
331         td->io_hist_len--;
332 }
333
334 void trim_io_piece(const struct io_u *io_u)
335 {
336         struct io_piece *ipo = io_u->ipo;
337
338         if (!ipo)
339                 return;
340
341         ipo->len = io_u->xfer_buflen - io_u->resid;
342 }
343
344 void write_iolog_close(struct thread_data *td)
345 {
346         if (!td->iolog_f)
347                 return;
348
349         fflush(td->iolog_f);
350         fclose(td->iolog_f);
351         free(td->iolog_buf);
352         td->iolog_f = NULL;
353         td->iolog_buf = NULL;
354 }
355
356 static int64_t iolog_items_to_fetch(struct thread_data *td)
357 {
358         struct timespec now;
359         uint64_t elapsed;
360         uint64_t for_1s;
361         int64_t items_to_fetch;
362
363         if (!td->io_log_highmark)
364                 return 10;
365
366
367         fio_gettime(&now, NULL);
368         elapsed = ntime_since(&td->io_log_highmark_time, &now);
369         if (elapsed) {
370                 for_1s = (td->io_log_highmark - td->io_log_current) * 1000000000 / elapsed;
371                 items_to_fetch = for_1s - td->io_log_current;
372                 if (items_to_fetch < 0)
373                         items_to_fetch = 0;
374         } else
375                 items_to_fetch = 0;
376
377         td->io_log_highmark = td->io_log_current + items_to_fetch;
378         td->io_log_checkmark = (td->io_log_highmark + 1) / 2;
379         fio_gettime(&td->io_log_highmark_time, NULL);
380
381         return items_to_fetch;
382 }
383
384 /*
385  * Read version 2 iolog data. It is enhanced to include per-file logging,
386  * syncs, etc.
387  */
388 static bool read_iolog2(struct thread_data *td)
389 {
390         unsigned long long offset;
391         unsigned int bytes;
392         int reads, writes, waits, fileno = 0, file_action = 0; /* stupid gcc */
393         char *rfname, *fname, *act;
394         char *str, *p;
395         enum fio_ddir rw;
396         bool realloc = false;
397         int64_t items_to_fetch = 0;
398
399         if (td->o.read_iolog_chunked) {
400                 items_to_fetch = iolog_items_to_fetch(td);
401                 if (!items_to_fetch)
402                         return true;
403         }
404
405         /*
406          * Read in the read iolog and store it, reuse the infrastructure
407          * for doing verifications.
408          */
409         str = malloc(4096);
410         rfname = fname = malloc(256+16);
411         act = malloc(256+16);
412
413         reads = writes = waits = 0;
414         while ((p = fgets(str, 4096, td->io_log_rfile)) != NULL) {
415                 struct io_piece *ipo;
416                 int r;
417
418                 r = sscanf(p, "%256s %256s %llu %u", rfname, act, &offset,
419                                                                         &bytes);
420
421                 if (td->o.replay_redirect)
422                         fname = td->o.replay_redirect;
423
424                 if (r == 4) {
425                         /*
426                          * Check action first
427                          */
428                         if (!strcmp(act, "wait"))
429                                 rw = DDIR_WAIT;
430                         else if (!strcmp(act, "read"))
431                                 rw = DDIR_READ;
432                         else if (!strcmp(act, "write"))
433                                 rw = DDIR_WRITE;
434                         else if (!strcmp(act, "sync"))
435                                 rw = DDIR_SYNC;
436                         else if (!strcmp(act, "datasync"))
437                                 rw = DDIR_DATASYNC;
438                         else if (!strcmp(act, "trim"))
439                                 rw = DDIR_TRIM;
440                         else {
441                                 log_err("fio: bad iolog file action: %s\n",
442                                                                         act);
443                                 continue;
444                         }
445                         fileno = get_fileno(td, fname);
446                 } else if (r == 2) {
447                         rw = DDIR_INVAL;
448                         if (!strcmp(act, "add")) {
449                                 if (td->o.replay_redirect &&
450                                     get_fileno(td, fname) != -1) {
451                                         dprint(FD_FILE, "iolog: ignoring"
452                                                 " re-add of file %s\n", fname);
453                                 } else {
454                                         fileno = add_file(td, fname, td->subjob_number, 1);
455                                         file_action = FIO_LOG_ADD_FILE;
456                                 }
457                                 continue;
458                         } else if (!strcmp(act, "open")) {
459                                 fileno = get_fileno(td, fname);
460                                 file_action = FIO_LOG_OPEN_FILE;
461                         } else if (!strcmp(act, "close")) {
462                                 fileno = get_fileno(td, fname);
463                                 file_action = FIO_LOG_CLOSE_FILE;
464                         } else {
465                                 log_err("fio: bad iolog file action: %s\n",
466                                                                         act);
467                                 continue;
468                         }
469                 } else {
470                         log_err("bad iolog2: %s\n", p);
471                         continue;
472                 }
473
474                 if (rw == DDIR_READ)
475                         reads++;
476                 else if (rw == DDIR_WRITE) {
477                         /*
478                          * Don't add a write for ro mode
479                          */
480                         if (read_only)
481                                 continue;
482                         writes++;
483                 } else if (rw == DDIR_WAIT) {
484                         if (td->o.no_stall)
485                                 continue;
486                         waits++;
487                 } else if (rw == DDIR_INVAL) {
488                 } else if (!ddir_sync(rw)) {
489                         log_err("bad ddir: %d\n", rw);
490                         continue;
491                 }
492
493                 /*
494                  * Make note of file
495                  */
496                 ipo = calloc(1, sizeof(*ipo));
497                 init_ipo(ipo);
498                 ipo->ddir = rw;
499                 if (rw == DDIR_WAIT) {
500                         ipo->delay = offset;
501                 } else {
502                         if (td->o.replay_scale)
503                                 ipo->offset = offset / td->o.replay_scale;
504                         else
505                                 ipo->offset = offset;
506                         ipo_bytes_align(td->o.replay_align, ipo);
507
508                         ipo->len = bytes;
509                         if (rw != DDIR_INVAL && bytes > td->o.max_bs[rw]) {
510                                 realloc = true;
511                                 td->o.max_bs[rw] = bytes;
512                         }
513                         ipo->fileno = fileno;
514                         ipo->file_action = file_action;
515                         td->o.size += bytes;
516                 }
517
518                 queue_io_piece(td, ipo);
519
520                 if (td->o.read_iolog_chunked) {
521                         td->io_log_current++;
522                         items_to_fetch--;
523                         if (items_to_fetch == 0)
524                                 break;
525                 }
526         }
527
528         free(str);
529         free(act);
530         free(rfname);
531
532         if (td->o.read_iolog_chunked) {
533                 td->io_log_highmark = td->io_log_current;
534                 td->io_log_checkmark = (td->io_log_highmark + 1) / 2;
535                 fio_gettime(&td->io_log_highmark_time, NULL);
536         }
537
538         if (writes && read_only) {
539                 log_err("fio: <%s> skips replay of %d writes due to"
540                         " read-only\n", td->o.name, writes);
541                 writes = 0;
542         }
543
544         if (td->o.read_iolog_chunked) {
545                 if (td->io_log_current == 0) {
546                         return false;
547                 }
548                 td->o.td_ddir = TD_DDIR_RW;
549                 if (realloc && td->orig_buffer)
550                 {
551                         io_u_quiesce(td);
552                         free_io_mem(td);
553                         init_io_u_buffers(td);
554                 }
555                 return true;
556         }
557
558         if (!reads && !writes && !waits)
559                 return false;
560         else if (reads && !writes)
561                 td->o.td_ddir = TD_DDIR_READ;
562         else if (!reads && writes)
563                 td->o.td_ddir = TD_DDIR_WRITE;
564         else
565                 td->o.td_ddir = TD_DDIR_RW;
566
567         return true;
568 }
569
570 static bool is_socket(const char *path)
571 {
572         struct stat buf;
573         int r;
574
575         r = stat(path, &buf);
576         if (r == -1)
577                 return false;
578
579         return S_ISSOCK(buf.st_mode);
580 }
581
582 static int open_socket(const char *path)
583 {
584         struct sockaddr_un addr;
585         int ret, fd;
586
587         fd = socket(AF_UNIX, SOCK_STREAM, 0);
588         if (fd < 0)
589                 return fd;
590
591         addr.sun_family = AF_UNIX;
592         if (snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path) >=
593             sizeof(addr.sun_path)) {
594                 log_err("%s: path name %s is too long for a Unix socket\n",
595                         __func__, path);
596         }
597
598         ret = connect(fd, (const struct sockaddr *)&addr, strlen(path) + sizeof(addr.sun_family));
599         if (!ret)
600                 return fd;
601
602         close(fd);
603         return -1;
604 }
605
606 /*
607  * open iolog, check version, and call appropriate parser
608  */
609 static bool init_iolog_read(struct thread_data *td)
610 {
611         char buffer[256], *p, *fname;
612         FILE *f = NULL;
613
614         fname = get_name_by_idx(td->o.read_iolog_file, td->subjob_number);
615         dprint(FD_IO, "iolog: name=%s\n", fname);
616
617         if (is_socket(fname)) {
618                 int fd;
619
620                 fd = open_socket(fname);
621                 if (fd >= 0)
622                         f = fdopen(fd, "r");
623         } else
624                 f = fopen(fname, "r");
625
626         free(fname);
627
628         if (!f) {
629                 perror("fopen read iolog");
630                 return false;
631         }
632
633         p = fgets(buffer, sizeof(buffer), f);
634         if (!p) {
635                 td_verror(td, errno, "iolog read");
636                 log_err("fio: unable to read iolog\n");
637                 fclose(f);
638                 return false;
639         }
640
641         /*
642          * version 2 of the iolog stores a specific string as the
643          * first line, check for that
644          */
645         if (!strncmp(iolog_ver2, buffer, strlen(iolog_ver2))) {
646                 free_release_files(td);
647                 td->io_log_rfile = f;
648                 return read_iolog2(td);
649         }
650
651         log_err("fio: iolog version 1 is no longer supported\n");
652         fclose(f);
653         return false;
654 }
655
656 /*
657  * Set up a log for storing io patterns.
658  */
659 static bool init_iolog_write(struct thread_data *td)
660 {
661         struct fio_file *ff;
662         FILE *f;
663         unsigned int i;
664
665         f = fopen(td->o.write_iolog_file, "a");
666         if (!f) {
667                 perror("fopen write iolog");
668                 return false;
669         }
670
671         /*
672          * That's it for writing, setup a log buffer and we're done.
673           */
674         td->iolog_f = f;
675         td->iolog_buf = malloc(8192);
676         setvbuf(f, td->iolog_buf, _IOFBF, 8192);
677
678         /*
679          * write our version line
680          */
681         if (fprintf(f, "%s\n", iolog_ver2) < 0) {
682                 perror("iolog init\n");
683                 return false;
684         }
685
686         /*
687          * add all known files
688          */
689         for_each_file(td, ff, i)
690                 log_file(td, ff, FIO_LOG_ADD_FILE);
691
692         return true;
693 }
694
695 bool init_iolog(struct thread_data *td)
696 {
697         bool ret;
698
699         if (td->o.read_iolog_file) {
700                 int need_swap;
701
702                 /*
703                  * Check if it's a blktrace file and load that if possible.
704                  * Otherwise assume it's a normal log file and load that.
705                  */
706                 if (is_blktrace(td->o.read_iolog_file, &need_swap))
707                         ret = load_blktrace(td, td->o.read_iolog_file, need_swap);
708                 else
709                         ret = init_iolog_read(td);
710         } else if (td->o.write_iolog_file)
711                 ret = init_iolog_write(td);
712         else
713                 ret = true;
714
715         if (!ret)
716                 td_verror(td, EINVAL, "failed initializing iolog");
717
718         return ret;
719 }
720
721 void setup_log(struct io_log **log, struct log_params *p,
722                const char *filename)
723 {
724         struct io_log *l;
725         int i;
726         struct io_u_plat_entry *entry;
727         struct flist_head *list;
728
729         l = scalloc(1, sizeof(*l));
730         INIT_FLIST_HEAD(&l->io_logs);
731         l->log_type = p->log_type;
732         l->log_offset = p->log_offset;
733         l->log_gz = p->log_gz;
734         l->log_gz_store = p->log_gz_store;
735         l->avg_msec = p->avg_msec;
736         l->hist_msec = p->hist_msec;
737         l->hist_coarseness = p->hist_coarseness;
738         l->filename = strdup(filename);
739         l->td = p->td;
740
741         /* Initialize histogram lists for each r/w direction,
742          * with initial io_u_plat of all zeros:
743          */
744         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
745                 list = &l->hist_window[i].list;
746                 INIT_FLIST_HEAD(list);
747                 entry = calloc(1, sizeof(struct io_u_plat_entry));
748                 flist_add(&entry->list, list);
749         }
750
751         if (l->td && l->td->o.io_submit_mode != IO_MODE_OFFLOAD) {
752                 unsigned int def_samples = DEF_LOG_ENTRIES;
753                 struct io_logs *__p;
754
755                 __p = calloc(1, sizeof(*l->pending));
756                 if (l->td->o.iodepth > DEF_LOG_ENTRIES)
757                         def_samples = roundup_pow2(l->td->o.iodepth);
758                 __p->max_samples = def_samples;
759                 __p->log = calloc(__p->max_samples, log_entry_sz(l));
760                 l->pending = __p;
761         }
762
763         if (l->log_offset)
764                 l->log_ddir_mask = LOG_OFFSET_SAMPLE_BIT;
765
766         INIT_FLIST_HEAD(&l->chunk_list);
767
768         if (l->log_gz && !p->td)
769                 l->log_gz = 0;
770         else if (l->log_gz || l->log_gz_store) {
771                 mutex_init_pshared(&l->chunk_lock);
772                 mutex_init_pshared(&l->deferred_free_lock);
773                 p->td->flags |= TD_F_COMPRESS_LOG;
774         }
775
776         *log = l;
777 }
778
779 #ifdef CONFIG_SETVBUF
780 static void *set_file_buffer(FILE *f)
781 {
782         size_t size = 1048576;
783         void *buf;
784
785         buf = malloc(size);
786         setvbuf(f, buf, _IOFBF, size);
787         return buf;
788 }
789
790 static void clear_file_buffer(void *buf)
791 {
792         free(buf);
793 }
794 #else
795 static void *set_file_buffer(FILE *f)
796 {
797         return NULL;
798 }
799
800 static void clear_file_buffer(void *buf)
801 {
802 }
803 #endif
804
805 void free_log(struct io_log *log)
806 {
807         while (!flist_empty(&log->io_logs)) {
808                 struct io_logs *cur_log;
809
810                 cur_log = flist_first_entry(&log->io_logs, struct io_logs, list);
811                 flist_del_init(&cur_log->list);
812                 free(cur_log->log);
813                 sfree(cur_log);
814         }
815
816         if (log->pending) {
817                 free(log->pending->log);
818                 free(log->pending);
819                 log->pending = NULL;
820         }
821
822         free(log->pending);
823         free(log->filename);
824         sfree(log);
825 }
826
827 uint64_t hist_sum(int j, int stride, uint64_t *io_u_plat,
828                 uint64_t *io_u_plat_last)
829 {
830         uint64_t sum;
831         int k;
832
833         if (io_u_plat_last) {
834                 for (k = sum = 0; k < stride; k++)
835                         sum += io_u_plat[j + k] - io_u_plat_last[j + k];
836         } else {
837                 for (k = sum = 0; k < stride; k++)
838                         sum += io_u_plat[j + k];
839         }
840
841         return sum;
842 }
843
844 static void flush_hist_samples(FILE *f, int hist_coarseness, void *samples,
845                                uint64_t sample_size)
846 {
847         struct io_sample *s;
848         int log_offset;
849         uint64_t i, j, nr_samples;
850         struct io_u_plat_entry *entry, *entry_before;
851         uint64_t *io_u_plat;
852         uint64_t *io_u_plat_before;
853
854         int stride = 1 << hist_coarseness;
855         
856         if (!sample_size)
857                 return;
858
859         s = __get_sample(samples, 0, 0);
860         log_offset = (s->__ddir & LOG_OFFSET_SAMPLE_BIT) != 0;
861
862         nr_samples = sample_size / __log_entry_sz(log_offset);
863
864         for (i = 0; i < nr_samples; i++) {
865                 s = __get_sample(samples, log_offset, i);
866
867                 entry = s->data.plat_entry;
868                 io_u_plat = entry->io_u_plat;
869
870                 entry_before = flist_first_entry(&entry->list, struct io_u_plat_entry, list);
871                 io_u_plat_before = entry_before->io_u_plat;
872
873                 fprintf(f, "%lu, %u, %llu, ", (unsigned long) s->time,
874                                                 io_sample_ddir(s), (unsigned long long) s->bs);
875                 for (j = 0; j < FIO_IO_U_PLAT_NR - stride; j += stride) {
876                         fprintf(f, "%llu, ", (unsigned long long)
877                                 hist_sum(j, stride, io_u_plat, io_u_plat_before));
878                 }
879                 fprintf(f, "%llu\n", (unsigned long long)
880                         hist_sum(FIO_IO_U_PLAT_NR - stride, stride, io_u_plat,
881                                         io_u_plat_before));
882
883                 flist_del(&entry_before->list);
884                 free(entry_before);
885         }
886 }
887
888 void flush_samples(FILE *f, void *samples, uint64_t sample_size)
889 {
890         struct io_sample *s;
891         int log_offset;
892         uint64_t i, nr_samples;
893
894         if (!sample_size)
895                 return;
896
897         s = __get_sample(samples, 0, 0);
898         log_offset = (s->__ddir & LOG_OFFSET_SAMPLE_BIT) != 0;
899
900         nr_samples = sample_size / __log_entry_sz(log_offset);
901
902         for (i = 0; i < nr_samples; i++) {
903                 s = __get_sample(samples, log_offset, i);
904
905                 if (!log_offset) {
906                         fprintf(f, "%lu, %" PRId64 ", %u, %llu, %u\n",
907                                         (unsigned long) s->time,
908                                         s->data.val,
909                                         io_sample_ddir(s), (unsigned long long) s->bs, s->priority_bit);
910                 } else {
911                         struct io_sample_offset *so = (void *) s;
912
913                         fprintf(f, "%lu, %" PRId64 ", %u, %llu, %llu, %u\n",
914                                         (unsigned long) s->time,
915                                         s->data.val,
916                                         io_sample_ddir(s), (unsigned long long) s->bs,
917                                         (unsigned long long) so->offset, s->priority_bit);
918                 }
919         }
920 }
921
922 #ifdef CONFIG_ZLIB
923
924 struct iolog_flush_data {
925         struct workqueue_work work;
926         struct io_log *log;
927         void *samples;
928         uint32_t nr_samples;
929         bool free;
930 };
931
932 #define GZ_CHUNK        131072
933
934 static struct iolog_compress *get_new_chunk(unsigned int seq)
935 {
936         struct iolog_compress *c;
937
938         c = malloc(sizeof(*c));
939         INIT_FLIST_HEAD(&c->list);
940         c->buf = malloc(GZ_CHUNK);
941         c->len = 0;
942         c->seq = seq;
943         return c;
944 }
945
946 static void free_chunk(struct iolog_compress *ic)
947 {
948         free(ic->buf);
949         free(ic);
950 }
951
952 static int z_stream_init(z_stream *stream, int gz_hdr)
953 {
954         int wbits = 15;
955
956         memset(stream, 0, sizeof(*stream));
957         stream->zalloc = Z_NULL;
958         stream->zfree = Z_NULL;
959         stream->opaque = Z_NULL;
960         stream->next_in = Z_NULL;
961
962         /*
963          * zlib magic - add 32 for auto-detection of gz header or not,
964          * if we decide to store files in a gzip friendly format.
965          */
966         if (gz_hdr)
967                 wbits += 32;
968
969         if (inflateInit2(stream, wbits) != Z_OK)
970                 return 1;
971
972         return 0;
973 }
974
975 struct inflate_chunk_iter {
976         unsigned int seq;
977         int err;
978         void *buf;
979         size_t buf_size;
980         size_t buf_used;
981         size_t chunk_sz;
982 };
983
984 static void finish_chunk(z_stream *stream, FILE *f,
985                          struct inflate_chunk_iter *iter)
986 {
987         int ret;
988
989         ret = inflateEnd(stream);
990         if (ret != Z_OK)
991                 log_err("fio: failed to end log inflation seq %d (%d)\n",
992                                 iter->seq, ret);
993
994         flush_samples(f, iter->buf, iter->buf_used);
995         free(iter->buf);
996         iter->buf = NULL;
997         iter->buf_size = iter->buf_used = 0;
998 }
999
1000 /*
1001  * Iterative chunk inflation. Handles cases where we cross into a new
1002  * sequence, doing flush finish of previous chunk if needed.
1003  */
1004 static size_t inflate_chunk(struct iolog_compress *ic, int gz_hdr, FILE *f,
1005                             z_stream *stream, struct inflate_chunk_iter *iter)
1006 {
1007         size_t ret;
1008
1009         dprint(FD_COMPRESS, "inflate chunk size=%lu, seq=%u\n",
1010                                 (unsigned long) ic->len, ic->seq);
1011
1012         if (ic->seq != iter->seq) {
1013                 if (iter->seq)
1014                         finish_chunk(stream, f, iter);
1015
1016                 z_stream_init(stream, gz_hdr);
1017                 iter->seq = ic->seq;
1018         }
1019
1020         stream->avail_in = ic->len;
1021         stream->next_in = ic->buf;
1022
1023         if (!iter->buf_size) {
1024                 iter->buf_size = iter->chunk_sz;
1025                 iter->buf = malloc(iter->buf_size);
1026         }
1027
1028         while (stream->avail_in) {
1029                 size_t this_out = iter->buf_size - iter->buf_used;
1030                 int err;
1031
1032                 stream->avail_out = this_out;
1033                 stream->next_out = iter->buf + iter->buf_used;
1034
1035                 err = inflate(stream, Z_NO_FLUSH);
1036                 if (err < 0) {
1037                         log_err("fio: failed inflating log: %d\n", err);
1038                         iter->err = err;
1039                         break;
1040                 }
1041
1042                 iter->buf_used += this_out - stream->avail_out;
1043
1044                 if (!stream->avail_out) {
1045                         iter->buf_size += iter->chunk_sz;
1046                         iter->buf = realloc(iter->buf, iter->buf_size);
1047                         continue;
1048                 }
1049
1050                 if (err == Z_STREAM_END)
1051                         break;
1052         }
1053
1054         ret = (void *) stream->next_in - ic->buf;
1055
1056         dprint(FD_COMPRESS, "inflated to size=%lu\n", (unsigned long) iter->buf_size);
1057
1058         return ret;
1059 }
1060
1061 /*
1062  * Inflate stored compressed chunks, or write them directly to the log
1063  * file if so instructed.
1064  */
1065 static int inflate_gz_chunks(struct io_log *log, FILE *f)
1066 {
1067         struct inflate_chunk_iter iter = { .chunk_sz = log->log_gz, };
1068         z_stream stream;
1069
1070         while (!flist_empty(&log->chunk_list)) {
1071                 struct iolog_compress *ic;
1072
1073                 ic = flist_first_entry(&log->chunk_list, struct iolog_compress, list);
1074                 flist_del(&ic->list);
1075
1076                 if (log->log_gz_store) {
1077                         size_t ret;
1078
1079                         dprint(FD_COMPRESS, "log write chunk size=%lu, "
1080                                 "seq=%u\n", (unsigned long) ic->len, ic->seq);
1081
1082                         ret = fwrite(ic->buf, ic->len, 1, f);
1083                         if (ret != 1 || ferror(f)) {
1084                                 iter.err = errno;
1085                                 log_err("fio: error writing compressed log\n");
1086                         }
1087                 } else
1088                         inflate_chunk(ic, log->log_gz_store, f, &stream, &iter);
1089
1090                 free_chunk(ic);
1091         }
1092
1093         if (iter.seq) {
1094                 finish_chunk(&stream, f, &iter);
1095                 free(iter.buf);
1096         }
1097
1098         return iter.err;
1099 }
1100
1101 /*
1102  * Open compressed log file and decompress the stored chunks and
1103  * write them to stdout. The chunks are stored sequentially in the
1104  * file, so we iterate over them and do them one-by-one.
1105  */
1106 int iolog_file_inflate(const char *file)
1107 {
1108         struct inflate_chunk_iter iter = { .chunk_sz = 64 * 1024 * 1024, };
1109         struct iolog_compress ic;
1110         z_stream stream;
1111         struct stat sb;
1112         size_t ret;
1113         size_t total;
1114         void *buf;
1115         FILE *f;
1116
1117         f = fopen(file, "r");
1118         if (!f) {
1119                 perror("fopen");
1120                 return 1;
1121         }
1122
1123         if (stat(file, &sb) < 0) {
1124                 fclose(f);
1125                 perror("stat");
1126                 return 1;
1127         }
1128
1129         ic.buf = buf = malloc(sb.st_size);
1130         ic.len = sb.st_size;
1131         ic.seq = 1;
1132
1133         ret = fread(ic.buf, ic.len, 1, f);
1134         if (ret == 0 && ferror(f)) {
1135                 perror("fread");
1136                 fclose(f);
1137                 free(buf);
1138                 return 1;
1139         } else if (ferror(f) || (!feof(f) && ret != 1)) {
1140                 log_err("fio: short read on reading log\n");
1141                 fclose(f);
1142                 free(buf);
1143                 return 1;
1144         }
1145
1146         fclose(f);
1147
1148         /*
1149          * Each chunk will return Z_STREAM_END. We don't know how many
1150          * chunks are in the file, so we just keep looping and incrementing
1151          * the sequence number until we have consumed the whole compressed
1152          * file.
1153          */
1154         total = ic.len;
1155         do {
1156                 size_t iret;
1157
1158                 iret = inflate_chunk(&ic,  1, stdout, &stream, &iter);
1159                 total -= iret;
1160                 if (!total)
1161                         break;
1162                 if (iter.err)
1163                         break;
1164
1165                 ic.seq++;
1166                 ic.len -= iret;
1167                 ic.buf += iret;
1168         } while (1);
1169
1170         if (iter.seq) {
1171                 finish_chunk(&stream, stdout, &iter);
1172                 free(iter.buf);
1173         }
1174
1175         free(buf);
1176         return iter.err;
1177 }
1178
1179 #else
1180
1181 static int inflate_gz_chunks(struct io_log *log, FILE *f)
1182 {
1183         return 0;
1184 }
1185
1186 int iolog_file_inflate(const char *file)
1187 {
1188         log_err("fio: log inflation not possible without zlib\n");
1189         return 1;
1190 }
1191
1192 #endif
1193
1194 void flush_log(struct io_log *log, bool do_append)
1195 {
1196         void *buf;
1197         FILE *f;
1198
1199         if (!do_append)
1200                 f = fopen(log->filename, "w");
1201         else
1202                 f = fopen(log->filename, "a");
1203         if (!f) {
1204                 perror("fopen log");
1205                 return;
1206         }
1207
1208         buf = set_file_buffer(f);
1209
1210         inflate_gz_chunks(log, f);
1211
1212         while (!flist_empty(&log->io_logs)) {
1213                 struct io_logs *cur_log;
1214
1215                 cur_log = flist_first_entry(&log->io_logs, struct io_logs, list);
1216                 flist_del_init(&cur_log->list);
1217                 
1218                 if (log->td && log == log->td->clat_hist_log)
1219                         flush_hist_samples(f, log->hist_coarseness, cur_log->log,
1220                                            log_sample_sz(log, cur_log));
1221                 else
1222                         flush_samples(f, cur_log->log, log_sample_sz(log, cur_log));
1223                 
1224                 sfree(cur_log);
1225         }
1226
1227         fclose(f);
1228         clear_file_buffer(buf);
1229 }
1230
1231 static int finish_log(struct thread_data *td, struct io_log *log, int trylock)
1232 {
1233         if (td->flags & TD_F_COMPRESS_LOG)
1234                 iolog_flush(log);
1235
1236         if (trylock) {
1237                 if (fio_trylock_file(log->filename))
1238                         return 1;
1239         } else
1240                 fio_lock_file(log->filename);
1241
1242         if (td->client_type == FIO_CLIENT_TYPE_GUI || is_backend)
1243                 fio_send_iolog(td, log, log->filename);
1244         else
1245                 flush_log(log, !td->o.per_job_logs);
1246
1247         fio_unlock_file(log->filename);
1248         free_log(log);
1249         return 0;
1250 }
1251
1252 size_t log_chunk_sizes(struct io_log *log)
1253 {
1254         struct flist_head *entry;
1255         size_t ret;
1256
1257         if (flist_empty(&log->chunk_list))
1258                 return 0;
1259
1260         ret = 0;
1261         pthread_mutex_lock(&log->chunk_lock);
1262         flist_for_each(entry, &log->chunk_list) {
1263                 struct iolog_compress *c;
1264
1265                 c = flist_entry(entry, struct iolog_compress, list);
1266                 ret += c->len;
1267         }
1268         pthread_mutex_unlock(&log->chunk_lock);
1269         return ret;
1270 }
1271
1272 #ifdef CONFIG_ZLIB
1273
1274 static void iolog_put_deferred(struct io_log *log, void *ptr)
1275 {
1276         if (!ptr)
1277                 return;
1278
1279         pthread_mutex_lock(&log->deferred_free_lock);
1280         if (log->deferred < IOLOG_MAX_DEFER) {
1281                 log->deferred_items[log->deferred] = ptr;
1282                 log->deferred++;
1283         } else if (!fio_did_warn(FIO_WARN_IOLOG_DROP))
1284                 log_err("fio: had to drop log entry free\n");
1285         pthread_mutex_unlock(&log->deferred_free_lock);
1286 }
1287
1288 static void iolog_free_deferred(struct io_log *log)
1289 {
1290         int i;
1291
1292         if (!log->deferred)
1293                 return;
1294
1295         pthread_mutex_lock(&log->deferred_free_lock);
1296
1297         for (i = 0; i < log->deferred; i++) {
1298                 free(log->deferred_items[i]);
1299                 log->deferred_items[i] = NULL;
1300         }
1301
1302         log->deferred = 0;
1303         pthread_mutex_unlock(&log->deferred_free_lock);
1304 }
1305
1306 static int gz_work(struct iolog_flush_data *data)
1307 {
1308         struct iolog_compress *c = NULL;
1309         struct flist_head list;
1310         unsigned int seq;
1311         z_stream stream;
1312         size_t total = 0;
1313         int ret;
1314
1315         INIT_FLIST_HEAD(&list);
1316
1317         memset(&stream, 0, sizeof(stream));
1318         stream.zalloc = Z_NULL;
1319         stream.zfree = Z_NULL;
1320         stream.opaque = Z_NULL;
1321
1322         ret = deflateInit(&stream, Z_DEFAULT_COMPRESSION);
1323         if (ret != Z_OK) {
1324                 log_err("fio: failed to init gz stream\n");
1325                 goto err;
1326         }
1327
1328         seq = ++data->log->chunk_seq;
1329
1330         stream.next_in = (void *) data->samples;
1331         stream.avail_in = data->nr_samples * log_entry_sz(data->log);
1332
1333         dprint(FD_COMPRESS, "deflate input size=%lu, seq=%u, log=%s\n",
1334                                 (unsigned long) stream.avail_in, seq,
1335                                 data->log->filename);
1336         do {
1337                 if (c)
1338                         dprint(FD_COMPRESS, "seq=%d, chunk=%lu\n", seq,
1339                                 (unsigned long) c->len);
1340                 c = get_new_chunk(seq);
1341                 stream.avail_out = GZ_CHUNK;
1342                 stream.next_out = c->buf;
1343                 ret = deflate(&stream, Z_NO_FLUSH);
1344                 if (ret < 0) {
1345                         log_err("fio: deflate log (%d)\n", ret);
1346                         free_chunk(c);
1347                         goto err;
1348                 }
1349
1350                 c->len = GZ_CHUNK - stream.avail_out;
1351                 flist_add_tail(&c->list, &list);
1352                 total += c->len;
1353         } while (stream.avail_in);
1354
1355         stream.next_out = c->buf + c->len;
1356         stream.avail_out = GZ_CHUNK - c->len;
1357
1358         ret = deflate(&stream, Z_FINISH);
1359         if (ret < 0) {
1360                 /*
1361                  * Z_BUF_ERROR is special, it just means we need more
1362                  * output space. We'll handle that below. Treat any other
1363                  * error as fatal.
1364                  */
1365                 if (ret != Z_BUF_ERROR) {
1366                         log_err("fio: deflate log (%d)\n", ret);
1367                         flist_del(&c->list);
1368                         free_chunk(c);
1369                         goto err;
1370                 }
1371         }
1372
1373         total -= c->len;
1374         c->len = GZ_CHUNK - stream.avail_out;
1375         total += c->len;
1376         dprint(FD_COMPRESS, "seq=%d, chunk=%lu\n", seq, (unsigned long) c->len);
1377
1378         if (ret != Z_STREAM_END) {
1379                 do {
1380                         c = get_new_chunk(seq);
1381                         stream.avail_out = GZ_CHUNK;
1382                         stream.next_out = c->buf;
1383                         ret = deflate(&stream, Z_FINISH);
1384                         c->len = GZ_CHUNK - stream.avail_out;
1385                         total += c->len;
1386                         flist_add_tail(&c->list, &list);
1387                         dprint(FD_COMPRESS, "seq=%d, chunk=%lu\n", seq,
1388                                 (unsigned long) c->len);
1389                 } while (ret != Z_STREAM_END);
1390         }
1391
1392         dprint(FD_COMPRESS, "deflated to size=%lu\n", (unsigned long) total);
1393
1394         ret = deflateEnd(&stream);
1395         if (ret != Z_OK)
1396                 log_err("fio: deflateEnd %d\n", ret);
1397
1398         iolog_put_deferred(data->log, data->samples);
1399
1400         if (!flist_empty(&list)) {
1401                 pthread_mutex_lock(&data->log->chunk_lock);
1402                 flist_splice_tail(&list, &data->log->chunk_list);
1403                 pthread_mutex_unlock(&data->log->chunk_lock);
1404         }
1405
1406         ret = 0;
1407 done:
1408         if (data->free)
1409                 sfree(data);
1410         return ret;
1411 err:
1412         while (!flist_empty(&list)) {
1413                 c = flist_first_entry(list.next, struct iolog_compress, list);
1414                 flist_del(&c->list);
1415                 free_chunk(c);
1416         }
1417         ret = 1;
1418         goto done;
1419 }
1420
1421 /*
1422  * Invoked from our compress helper thread, when logging would have exceeded
1423  * the specified memory limitation. Compresses the previously stored
1424  * entries.
1425  */
1426 static int gz_work_async(struct submit_worker *sw, struct workqueue_work *work)
1427 {
1428         return gz_work(container_of(work, struct iolog_flush_data, work));
1429 }
1430
1431 static int gz_init_worker(struct submit_worker *sw)
1432 {
1433         struct thread_data *td = sw->wq->td;
1434
1435         if (!fio_option_is_set(&td->o, log_gz_cpumask))
1436                 return 0;
1437
1438         if (fio_setaffinity(gettid(), td->o.log_gz_cpumask) == -1) {
1439                 log_err("gz: failed to set CPU affinity\n");
1440                 return 1;
1441         }
1442
1443         return 0;
1444 }
1445
1446 static struct workqueue_ops log_compress_wq_ops = {
1447         .fn             = gz_work_async,
1448         .init_worker_fn = gz_init_worker,
1449         .nice           = 1,
1450 };
1451
1452 int iolog_compress_init(struct thread_data *td, struct sk_out *sk_out)
1453 {
1454         if (!(td->flags & TD_F_COMPRESS_LOG))
1455                 return 0;
1456
1457         workqueue_init(td, &td->log_compress_wq, &log_compress_wq_ops, 1, sk_out);
1458         return 0;
1459 }
1460
1461 void iolog_compress_exit(struct thread_data *td)
1462 {
1463         if (!(td->flags & TD_F_COMPRESS_LOG))
1464                 return;
1465
1466         workqueue_exit(&td->log_compress_wq);
1467 }
1468
1469 /*
1470  * Queue work item to compress the existing log entries. We reset the
1471  * current log to a small size, and reference the existing log in the
1472  * data that we queue for compression. Once compression has been done,
1473  * this old log is freed. If called with finish == true, will not return
1474  * until the log compression has completed, and will flush all previous
1475  * logs too
1476  */
1477 static int iolog_flush(struct io_log *log)
1478 {
1479         struct iolog_flush_data *data;
1480
1481         data = malloc(sizeof(*data));
1482         if (!data)
1483                 return 1;
1484
1485         data->log = log;
1486         data->free = false;
1487
1488         while (!flist_empty(&log->io_logs)) {
1489                 struct io_logs *cur_log;
1490
1491                 cur_log = flist_first_entry(&log->io_logs, struct io_logs, list);
1492                 flist_del_init(&cur_log->list);
1493
1494                 data->samples = cur_log->log;
1495                 data->nr_samples = cur_log->nr_samples;
1496
1497                 sfree(cur_log);
1498
1499                 gz_work(data);
1500         }
1501
1502         free(data);
1503         return 0;
1504 }
1505
1506 int iolog_cur_flush(struct io_log *log, struct io_logs *cur_log)
1507 {
1508         struct iolog_flush_data *data;
1509
1510         data = smalloc(sizeof(*data));
1511         if (!data)
1512                 return 1;
1513
1514         data->log = log;
1515
1516         data->samples = cur_log->log;
1517         data->nr_samples = cur_log->nr_samples;
1518         data->free = true;
1519
1520         cur_log->nr_samples = cur_log->max_samples = 0;
1521         cur_log->log = NULL;
1522
1523         workqueue_enqueue(&log->td->log_compress_wq, &data->work);
1524
1525         iolog_free_deferred(log);
1526
1527         return 0;
1528 }
1529 #else
1530
1531 static int iolog_flush(struct io_log *log)
1532 {
1533         return 1;
1534 }
1535
1536 int iolog_cur_flush(struct io_log *log, struct io_logs *cur_log)
1537 {
1538         return 1;
1539 }
1540
1541 int iolog_compress_init(struct thread_data *td, struct sk_out *sk_out)
1542 {
1543         return 0;
1544 }
1545
1546 void iolog_compress_exit(struct thread_data *td)
1547 {
1548 }
1549
1550 #endif
1551
1552 struct io_logs *iolog_cur_log(struct io_log *log)
1553 {
1554         if (flist_empty(&log->io_logs))
1555                 return NULL;
1556
1557         return flist_last_entry(&log->io_logs, struct io_logs, list);
1558 }
1559
1560 uint64_t iolog_nr_samples(struct io_log *iolog)
1561 {
1562         struct flist_head *entry;
1563         uint64_t ret = 0;
1564
1565         flist_for_each(entry, &iolog->io_logs) {
1566                 struct io_logs *cur_log;
1567
1568                 cur_log = flist_entry(entry, struct io_logs, list);
1569                 ret += cur_log->nr_samples;
1570         }
1571
1572         return ret;
1573 }
1574
1575 static int __write_log(struct thread_data *td, struct io_log *log, int try)
1576 {
1577         if (log)
1578                 return finish_log(td, log, try);
1579
1580         return 0;
1581 }
1582
1583 static int write_iops_log(struct thread_data *td, int try, bool unit_log)
1584 {
1585         int ret;
1586
1587         if (per_unit_log(td->iops_log) != unit_log)
1588                 return 0;
1589
1590         ret = __write_log(td, td->iops_log, try);
1591         if (!ret)
1592                 td->iops_log = NULL;
1593
1594         return ret;
1595 }
1596
1597 static int write_slat_log(struct thread_data *td, int try, bool unit_log)
1598 {
1599         int ret;
1600
1601         if (!unit_log)
1602                 return 0;
1603
1604         ret = __write_log(td, td->slat_log, try);
1605         if (!ret)
1606                 td->slat_log = NULL;
1607
1608         return ret;
1609 }
1610
1611 static int write_clat_log(struct thread_data *td, int try, bool unit_log)
1612 {
1613         int ret;
1614
1615         if (!unit_log)
1616                 return 0;
1617
1618         ret = __write_log(td, td->clat_log, try);
1619         if (!ret)
1620                 td->clat_log = NULL;
1621
1622         return ret;
1623 }
1624
1625 static int write_clat_hist_log(struct thread_data *td, int try, bool unit_log)
1626 {
1627         int ret;
1628
1629         if (!unit_log)
1630                 return 0;
1631
1632         ret = __write_log(td, td->clat_hist_log, try);
1633         if (!ret)
1634                 td->clat_hist_log = NULL;
1635
1636         return ret;
1637 }
1638
1639 static int write_lat_log(struct thread_data *td, int try, bool unit_log)
1640 {
1641         int ret;
1642
1643         if (!unit_log)
1644                 return 0;
1645
1646         ret = __write_log(td, td->lat_log, try);
1647         if (!ret)
1648                 td->lat_log = NULL;
1649
1650         return ret;
1651 }
1652
1653 static int write_bandw_log(struct thread_data *td, int try, bool unit_log)
1654 {
1655         int ret;
1656
1657         if (per_unit_log(td->bw_log) != unit_log)
1658                 return 0;
1659
1660         ret = __write_log(td, td->bw_log, try);
1661         if (!ret)
1662                 td->bw_log = NULL;
1663
1664         return ret;
1665 }
1666
1667 enum {
1668         BW_LOG_MASK     = 1,
1669         LAT_LOG_MASK    = 2,
1670         SLAT_LOG_MASK   = 4,
1671         CLAT_LOG_MASK   = 8,
1672         IOPS_LOG_MASK   = 16,
1673         CLAT_HIST_LOG_MASK = 32,
1674
1675         ALL_LOG_NR      = 6,
1676 };
1677
1678 struct log_type {
1679         unsigned int mask;
1680         int (*fn)(struct thread_data *, int, bool);
1681 };
1682
1683 static struct log_type log_types[] = {
1684         {
1685                 .mask   = BW_LOG_MASK,
1686                 .fn     = write_bandw_log,
1687         },
1688         {
1689                 .mask   = LAT_LOG_MASK,
1690                 .fn     = write_lat_log,
1691         },
1692         {
1693                 .mask   = SLAT_LOG_MASK,
1694                 .fn     = write_slat_log,
1695         },
1696         {
1697                 .mask   = CLAT_LOG_MASK,
1698                 .fn     = write_clat_log,
1699         },
1700         {
1701                 .mask   = IOPS_LOG_MASK,
1702                 .fn     = write_iops_log,
1703         },
1704         {
1705                 .mask   = CLAT_HIST_LOG_MASK,
1706                 .fn     = write_clat_hist_log,
1707         }
1708 };
1709
1710 void td_writeout_logs(struct thread_data *td, bool unit_logs)
1711 {
1712         unsigned int log_mask = 0;
1713         unsigned int log_left = ALL_LOG_NR;
1714         int old_state, i;
1715
1716         old_state = td_bump_runstate(td, TD_FINISHING);
1717
1718         finalize_logs(td, unit_logs);
1719
1720         while (log_left) {
1721                 int prev_log_left = log_left;
1722
1723                 for (i = 0; i < ALL_LOG_NR && log_left; i++) {
1724                         struct log_type *lt = &log_types[i];
1725                         int ret;
1726
1727                         if (!(log_mask & lt->mask)) {
1728                                 ret = lt->fn(td, log_left != 1, unit_logs);
1729                                 if (!ret) {
1730                                         log_left--;
1731                                         log_mask |= lt->mask;
1732                                 }
1733                         }
1734                 }
1735
1736                 if (prev_log_left == log_left)
1737                         usleep(5000);
1738         }
1739
1740         td_restore_runstate(td, old_state);
1741 }
1742
1743 void fio_writeout_logs(bool unit_logs)
1744 {
1745         struct thread_data *td;
1746         int i;
1747
1748         for_each_td(td, i)
1749                 td_writeout_logs(td, unit_logs);
1750 }