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