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