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