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