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