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