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