fio: report percentiles for slat, clat, lat
[fio.git] / stat.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/time.h>
4 #include <sys/stat.h>
5 #include <math.h>
6
7 #include "fio.h"
8 #include "diskutil.h"
9 #include "lib/ieee754.h"
10 #include "json.h"
11 #include "lib/getrusage.h"
12 #include "idletime.h"
13 #include "lib/pow2.h"
14 #include "lib/output_buffer.h"
15 #include "helper_thread.h"
16 #include "smalloc.h"
17 #include "zbd.h"
18 #include "oslib/asprintf.h"
19
20 #define LOG_MSEC_SLACK  1
21
22 struct fio_sem *stat_sem;
23
24 void clear_rusage_stat(struct thread_data *td)
25 {
26         struct thread_stat *ts = &td->ts;
27
28         fio_getrusage(&td->ru_start);
29         ts->usr_time = ts->sys_time = 0;
30         ts->ctx = 0;
31         ts->minf = ts->majf = 0;
32 }
33
34 void update_rusage_stat(struct thread_data *td)
35 {
36         struct thread_stat *ts = &td->ts;
37
38         fio_getrusage(&td->ru_end);
39         ts->usr_time += mtime_since_tv(&td->ru_start.ru_utime,
40                                         &td->ru_end.ru_utime);
41         ts->sys_time += mtime_since_tv(&td->ru_start.ru_stime,
42                                         &td->ru_end.ru_stime);
43         ts->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw
44                         - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
45         ts->minf += td->ru_end.ru_minflt - td->ru_start.ru_minflt;
46         ts->majf += td->ru_end.ru_majflt - td->ru_start.ru_majflt;
47
48         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
49 }
50
51 /*
52  * Given a latency, return the index of the corresponding bucket in
53  * the structure tracking percentiles.
54  *
55  * (1) find the group (and error bits) that the value (latency)
56  * belongs to by looking at its MSB. (2) find the bucket number in the
57  * group by looking at the index bits.
58  *
59  */
60 static unsigned int plat_val_to_idx(unsigned long long val)
61 {
62         unsigned int msb, error_bits, base, offset, idx;
63
64         /* Find MSB starting from bit 0 */
65         if (val == 0)
66                 msb = 0;
67         else
68                 msb = (sizeof(val)*8) - __builtin_clzll(val) - 1;
69
70         /*
71          * MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
72          * all bits of the sample as index
73          */
74         if (msb <= FIO_IO_U_PLAT_BITS)
75                 return val;
76
77         /* Compute the number of error bits to discard*/
78         error_bits = msb - FIO_IO_U_PLAT_BITS;
79
80         /* Compute the number of buckets before the group */
81         base = (error_bits + 1) << FIO_IO_U_PLAT_BITS;
82
83         /*
84          * Discard the error bits and apply the mask to find the
85          * index for the buckets in the group
86          */
87         offset = (FIO_IO_U_PLAT_VAL - 1) & (val >> error_bits);
88
89         /* Make sure the index does not exceed (array size - 1) */
90         idx = (base + offset) < (FIO_IO_U_PLAT_NR - 1) ?
91                 (base + offset) : (FIO_IO_U_PLAT_NR - 1);
92
93         return idx;
94 }
95
96 /*
97  * Convert the given index of the bucket array to the value
98  * represented by the bucket
99  */
100 static unsigned long long plat_idx_to_val(unsigned int idx)
101 {
102         unsigned int error_bits;
103         unsigned long long k, base;
104
105         assert(idx < FIO_IO_U_PLAT_NR);
106
107         /* MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
108          * all bits of the sample as index */
109         if (idx < (FIO_IO_U_PLAT_VAL << 1))
110                 return idx;
111
112         /* Find the group and compute the minimum value of that group */
113         error_bits = (idx >> FIO_IO_U_PLAT_BITS) - 1;
114         base = ((unsigned long long) 1) << (error_bits + FIO_IO_U_PLAT_BITS);
115
116         /* Find its bucket number of the group */
117         k = idx % FIO_IO_U_PLAT_VAL;
118
119         /* Return the mean of the range of the bucket */
120         return base + ((k + 0.5) * (1 << error_bits));
121 }
122
123 static int double_cmp(const void *a, const void *b)
124 {
125         const fio_fp64_t fa = *(const fio_fp64_t *) a;
126         const fio_fp64_t fb = *(const fio_fp64_t *) b;
127         int cmp = 0;
128
129         if (fa.u.f > fb.u.f)
130                 cmp = 1;
131         else if (fa.u.f < fb.u.f)
132                 cmp = -1;
133
134         return cmp;
135 }
136
137 unsigned int calc_clat_percentiles(uint64_t *io_u_plat, unsigned long long nr,
138                                    fio_fp64_t *plist, unsigned long long **output,
139                                    unsigned long long *maxv, unsigned long long *minv)
140 {
141         unsigned long long sum = 0;
142         unsigned int len, i, j = 0;
143         unsigned long long *ovals = NULL;
144         bool is_last;
145
146         *minv = -1ULL;
147         *maxv = 0;
148
149         len = 0;
150         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
151                 len++;
152
153         if (!len)
154                 return 0;
155
156         /*
157          * Sort the percentile list. Note that it may already be sorted if
158          * we are using the default values, but since it's a short list this
159          * isn't a worry. Also note that this does not work for NaN values.
160          */
161         if (len > 1)
162                 qsort(plist, len, sizeof(plist[0]), double_cmp);
163
164         ovals = malloc(len * sizeof(*ovals));
165         if (!ovals)
166                 return 0;
167
168         /*
169          * Calculate bucket values, note down max and min values
170          */
171         is_last = false;
172         for (i = 0; i < FIO_IO_U_PLAT_NR && !is_last; i++) {
173                 sum += io_u_plat[i];
174                 while (sum >= ((long double) plist[j].u.f / 100.0 * nr)) {
175                         assert(plist[j].u.f <= 100.0);
176
177                         ovals[j] = plat_idx_to_val(i);
178                         if (ovals[j] < *minv)
179                                 *minv = ovals[j];
180                         if (ovals[j] > *maxv)
181                                 *maxv = ovals[j];
182
183                         is_last = (j == len - 1) != 0;
184                         if (is_last)
185                                 break;
186
187                         j++;
188                 }
189         }
190
191         if (!is_last)
192                 log_err("fio: error calculating latency percentiles\n");
193
194         *output = ovals;
195         return len;
196 }
197
198 /*
199  * Find and display the p-th percentile of clat
200  */
201 static void show_clat_percentiles(uint64_t *io_u_plat, unsigned long long nr,
202                                   fio_fp64_t *plist, unsigned int precision,
203                                   const char *pre, struct buf_output *out)
204 {
205         unsigned int divisor, len, i, j = 0;
206         unsigned long long minv, maxv;
207         unsigned long long *ovals;
208         int per_line, scale_down, time_width;
209         bool is_last;
210         char fmt[32];
211
212         len = calc_clat_percentiles(io_u_plat, nr, plist, &ovals, &maxv, &minv);
213         if (!len || !ovals)
214                 goto out;
215
216         /*
217          * We default to nsecs, but if the value range is such that we
218          * should scale down to usecs or msecs, do that.
219          */
220         if (minv > 2000000 && maxv > 99999999ULL) {
221                 scale_down = 2;
222                 divisor = 1000000;
223                 log_buf(out, "    %s percentiles (msec):\n     |", pre);
224         } else if (minv > 2000 && maxv > 99999) {
225                 scale_down = 1;
226                 divisor = 1000;
227                 log_buf(out, "    %s percentiles (usec):\n     |", pre);
228         } else {
229                 scale_down = 0;
230                 divisor = 1;
231                 log_buf(out, "    %s percentiles (nsec):\n     |", pre);
232         }
233
234
235         time_width = max(5, (int) (log10(maxv / divisor) + 1));
236         snprintf(fmt, sizeof(fmt), " %%%u.%ufth=[%%%dllu]%%c", precision + 3,
237                         precision, time_width);
238         /* fmt will be something like " %5.2fth=[%4llu]%c" */
239         per_line = (80 - 7) / (precision + 10 + time_width);
240
241         for (j = 0; j < len; j++) {
242                 /* for formatting */
243                 if (j != 0 && (j % per_line) == 0)
244                         log_buf(out, "     |");
245
246                 /* end of the list */
247                 is_last = (j == len - 1) != 0;
248
249                 for (i = 0; i < scale_down; i++)
250                         ovals[j] = (ovals[j] + 999) / 1000;
251
252                 log_buf(out, fmt, plist[j].u.f, ovals[j], is_last ? '\n' : ',');
253
254                 if (is_last)
255                         break;
256
257                 if ((j % per_line) == per_line - 1)     /* for formatting */
258                         log_buf(out, "\n");
259         }
260
261 out:
262         free(ovals);
263 }
264
265 bool calc_lat(struct io_stat *is, unsigned long long *min,
266               unsigned long long *max, double *mean, double *dev)
267 {
268         double n = (double) is->samples;
269
270         if (n == 0)
271                 return false;
272
273         *min = is->min_val;
274         *max = is->max_val;
275         *mean = is->mean.u.f;
276
277         if (n > 1.0)
278                 *dev = sqrt(is->S.u.f / (n - 1.0));
279         else
280                 *dev = 0;
281
282         return true;
283 }
284
285 void show_group_stats(struct group_run_stats *rs, struct buf_output *out)
286 {
287         char *io, *agg, *min, *max;
288         char *ioalt, *aggalt, *minalt, *maxalt;
289         const char *str[] = { "   READ", "  WRITE" , "   TRIM"};
290         int i;
291
292         log_buf(out, "\nRun status group %d (all jobs):\n", rs->groupid);
293
294         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
295                 const int i2p = is_power_of_2(rs->kb_base);
296
297                 if (!rs->max_run[i])
298                         continue;
299
300                 io = num2str(rs->iobytes[i], rs->sig_figs, 1, i2p, N2S_BYTE);
301                 ioalt = num2str(rs->iobytes[i], rs->sig_figs, 1, !i2p, N2S_BYTE);
302                 agg = num2str(rs->agg[i], rs->sig_figs, 1, i2p, rs->unit_base);
303                 aggalt = num2str(rs->agg[i], rs->sig_figs, 1, !i2p, rs->unit_base);
304                 min = num2str(rs->min_bw[i], rs->sig_figs, 1, i2p, rs->unit_base);
305                 minalt = num2str(rs->min_bw[i], rs->sig_figs, 1, !i2p, rs->unit_base);
306                 max = num2str(rs->max_bw[i], rs->sig_figs, 1, i2p, rs->unit_base);
307                 maxalt = num2str(rs->max_bw[i], rs->sig_figs, 1, !i2p, rs->unit_base);
308                 log_buf(out, "%s: bw=%s (%s), %s-%s (%s-%s), io=%s (%s), run=%llu-%llumsec\n",
309                                 rs->unified_rw_rep ? "  MIXED" : str[i],
310                                 agg, aggalt, min, max, minalt, maxalt, io, ioalt,
311                                 (unsigned long long) rs->min_run[i],
312                                 (unsigned long long) rs->max_run[i]);
313
314                 free(io);
315                 free(agg);
316                 free(min);
317                 free(max);
318                 free(ioalt);
319                 free(aggalt);
320                 free(minalt);
321                 free(maxalt);
322         }
323 }
324
325 void stat_calc_dist(uint64_t *map, unsigned long total, double *io_u_dist)
326 {
327         int i;
328
329         /*
330          * Do depth distribution calculations
331          */
332         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
333                 if (total) {
334                         io_u_dist[i] = (double) map[i] / (double) total;
335                         io_u_dist[i] *= 100.0;
336                         if (io_u_dist[i] < 0.1 && map[i])
337                                 io_u_dist[i] = 0.1;
338                 } else
339                         io_u_dist[i] = 0.0;
340         }
341 }
342
343 static void stat_calc_lat(struct thread_stat *ts, double *dst,
344                           uint64_t *src, int nr)
345 {
346         unsigned long total = ddir_rw_sum(ts->total_io_u);
347         int i;
348
349         /*
350          * Do latency distribution calculations
351          */
352         for (i = 0; i < nr; i++) {
353                 if (total) {
354                         dst[i] = (double) src[i] / (double) total;
355                         dst[i] *= 100.0;
356                         if (dst[i] < 0.01 && src[i])
357                                 dst[i] = 0.01;
358                 } else
359                         dst[i] = 0.0;
360         }
361 }
362
363 /*
364  * To keep the terse format unaltered, add all of the ns latency
365  * buckets to the first us latency bucket
366  */
367 static void stat_calc_lat_nu(struct thread_stat *ts, double *io_u_lat_u)
368 {
369         unsigned long ntotal = 0, total = ddir_rw_sum(ts->total_io_u);
370         int i;
371
372         stat_calc_lat(ts, io_u_lat_u, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
373
374         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
375                 ntotal += ts->io_u_lat_n[i];
376
377         io_u_lat_u[0] += 100.0 * (double) ntotal / (double) total;
378 }
379
380 void stat_calc_lat_n(struct thread_stat *ts, double *io_u_lat)
381 {
382         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_n, FIO_IO_U_LAT_N_NR);
383 }
384
385 void stat_calc_lat_u(struct thread_stat *ts, double *io_u_lat)
386 {
387         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
388 }
389
390 void stat_calc_lat_m(struct thread_stat *ts, double *io_u_lat)
391 {
392         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_m, FIO_IO_U_LAT_M_NR);
393 }
394
395 static void display_lat(const char *name, unsigned long long min,
396                         unsigned long long max, double mean, double dev,
397                         struct buf_output *out)
398 {
399         const char *base = "(nsec)";
400         char *minp, *maxp;
401
402         if (nsec_to_msec(&min, &max, &mean, &dev))
403                 base = "(msec)";
404         else if (nsec_to_usec(&min, &max, &mean, &dev))
405                 base = "(usec)";
406
407         minp = num2str(min, 6, 1, 0, N2S_NONE);
408         maxp = num2str(max, 6, 1, 0, N2S_NONE);
409
410         log_buf(out, "    %s %s: min=%s, max=%s, avg=%5.02f,"
411                  " stdev=%5.02f\n", name, base, minp, maxp, mean, dev);
412
413         free(minp);
414         free(maxp);
415 }
416
417 static void show_ddir_status(struct group_run_stats *rs, struct thread_stat *ts,
418                              int ddir, struct buf_output *out)
419 {
420         unsigned long runt;
421         unsigned long long min, max, bw, iops;
422         double mean, dev;
423         char *io_p, *bw_p, *bw_p_alt, *iops_p, *post_st = NULL;
424         int i2p;
425
426         if (ddir_sync(ddir)) {
427                 if (calc_lat(&ts->sync_stat, &min, &max, &mean, &dev)) {
428                         log_buf(out, "  %s:\n", "fsync/fdatasync/sync_file_range");
429                         display_lat(io_ddir_name(ddir), min, max, mean, dev, out);
430                         show_clat_percentiles(ts->io_u_sync_plat,
431                                                 ts->sync_stat.samples,
432                                                 ts->percentile_list,
433                                                 ts->percentile_precision,
434                                                 io_ddir_name(ddir), out);
435                 }
436                 return;
437         }
438
439         assert(ddir_rw(ddir));
440
441         if (!ts->runtime[ddir])
442                 return;
443
444         i2p = is_power_of_2(rs->kb_base);
445         runt = ts->runtime[ddir];
446
447         bw = (1000 * ts->io_bytes[ddir]) / runt;
448         io_p = num2str(ts->io_bytes[ddir], ts->sig_figs, 1, i2p, N2S_BYTE);
449         bw_p = num2str(bw, ts->sig_figs, 1, i2p, ts->unit_base);
450         bw_p_alt = num2str(bw, ts->sig_figs, 1, !i2p, ts->unit_base);
451
452         iops = (1000 * (uint64_t)ts->total_io_u[ddir]) / runt;
453         iops_p = num2str(iops, ts->sig_figs, 1, 0, N2S_NONE);
454         if (ddir == DDIR_WRITE)
455                 post_st = zbd_write_status(ts);
456         else if (ddir == DDIR_READ && ts->cachehit && ts->cachemiss) {
457                 uint64_t total;
458                 double hit;
459
460                 total = ts->cachehit + ts->cachemiss;
461                 hit = (double) ts->cachehit / (double) total;
462                 hit *= 100.0;
463                 if (asprintf(&post_st, "; Cachehit=%0.2f%%", hit) < 0)
464                         post_st = NULL;
465         }
466
467         log_buf(out, "  %s: IOPS=%s, BW=%s (%s)(%s/%llumsec)%s\n",
468                         rs->unified_rw_rep ? "mixed" : io_ddir_name(ddir),
469                         iops_p, bw_p, bw_p_alt, io_p,
470                         (unsigned long long) ts->runtime[ddir],
471                         post_st ? : "");
472
473         free(post_st);
474         free(io_p);
475         free(bw_p);
476         free(bw_p_alt);
477         free(iops_p);
478
479         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
480                 display_lat("slat", min, max, mean, dev, out);
481         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
482                 display_lat("clat", min, max, mean, dev, out);
483         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
484                 display_lat(" lat", min, max, mean, dev, out);
485         if (calc_lat(&ts->clat_high_prio_stat[ddir], &min, &max, &mean, &dev))
486                 display_lat("prio_clat", min, max, mean, dev, out);
487
488         if (ts->slat_percentiles && ts->slat_stat[ddir].samples > 0)
489                 show_clat_percentiles(ts->io_u_plat[FIO_SLAT][ddir],
490                                         ts->slat_stat[ddir].samples,
491                                         ts->percentile_list,
492                                         ts->percentile_precision, "slat", out);
493         if (ts->clat_percentiles && ts->clat_stat[ddir].samples > 0)
494                 show_clat_percentiles(ts->io_u_plat[FIO_CLAT][ddir],
495                                         ts->clat_stat[ddir].samples,
496                                         ts->percentile_list,
497                                         ts->percentile_precision, "clat", out);
498         if (ts->lat_percentiles && ts->lat_stat[ddir].samples > 0)
499                 show_clat_percentiles(ts->io_u_plat[FIO_LAT][ddir],
500                                         ts->lat_stat[ddir].samples,
501                                         ts->percentile_list,
502                                         ts->percentile_precision, "lat", out);
503
504         if (ts->clat_percentiles || ts->lat_percentiles) {
505                 const char *name = ts->lat_percentiles ? " lat" : "clat";
506                 char prio_name[32];
507                 uint64_t samples;
508
509                 if (ts->lat_percentiles)
510                         samples = ts->lat_stat[ddir].samples;
511                 else
512                         samples = ts->clat_stat[ddir].samples;
513
514                 /* Only print this if some high and low priority stats were collected */
515                 if (ts->clat_high_prio_stat[ddir].samples > 0 &&
516                         ts->clat_prio_stat[ddir].samples > 0)
517                 {
518                         sprintf(prio_name, "high prio (%.2f%%) %s",
519                                         100. * (double) ts->clat_high_prio_stat[ddir].samples / (double) samples,
520                                         name);
521                         show_clat_percentiles(ts->io_u_plat_high_prio[ddir],
522                                                 ts->clat_high_prio_stat[ddir].samples,
523                                                 ts->percentile_list,
524                                                 ts->percentile_precision, prio_name, out);
525
526                         sprintf(prio_name, "low prio (%.2f%%) %s",
527                                         100. * (double) ts->clat_prio_stat[ddir].samples / (double) samples,
528                                         name);
529                         show_clat_percentiles(ts->io_u_plat_prio[ddir],
530                                                 ts->clat_prio_stat[ddir].samples,
531                                                 ts->percentile_list,
532                                                 ts->percentile_precision, prio_name, out);
533                 }
534         }
535
536         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
537                 double p_of_agg = 100.0, fkb_base = (double)rs->kb_base;
538                 const char *bw_str;
539
540                 if ((rs->unit_base == 1) && i2p)
541                         bw_str = "Kibit";
542                 else if (rs->unit_base == 1)
543                         bw_str = "kbit";
544                 else if (i2p)
545                         bw_str = "KiB";
546                 else
547                         bw_str = "kB";
548
549                 if (rs->agg[ddir]) {
550                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
551                         if (p_of_agg > 100.0)
552                                 p_of_agg = 100.0;
553                 }
554
555                 if (rs->unit_base == 1) {
556                         min *= 8.0;
557                         max *= 8.0;
558                         mean *= 8.0;
559                         dev *= 8.0;
560                 }
561
562                 if (mean > fkb_base * fkb_base) {
563                         min /= fkb_base;
564                         max /= fkb_base;
565                         mean /= fkb_base;
566                         dev /= fkb_base;
567                         bw_str = (rs->unit_base == 1 ? "Mibit" : "MiB");
568                 }
569
570                 log_buf(out, "   bw (%5s/s): min=%5llu, max=%5llu, per=%3.2f%%, "
571                         "avg=%5.02f, stdev=%5.02f, samples=%" PRIu64 "\n",
572                         bw_str, min, max, p_of_agg, mean, dev,
573                         (&ts->bw_stat[ddir])->samples);
574         }
575         if (calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev)) {
576                 log_buf(out, "   iops        : min=%5llu, max=%5llu, "
577                         "avg=%5.02f, stdev=%5.02f, samples=%" PRIu64 "\n",
578                         min, max, mean, dev, (&ts->iops_stat[ddir])->samples);
579         }
580 }
581
582 static bool show_lat(double *io_u_lat, int nr, const char **ranges,
583                      const char *msg, struct buf_output *out)
584 {
585         bool new_line = true, shown = false;
586         int i, line = 0;
587
588         for (i = 0; i < nr; i++) {
589                 if (io_u_lat[i] <= 0.0)
590                         continue;
591                 shown = true;
592                 if (new_line) {
593                         if (line)
594                                 log_buf(out, "\n");
595                         log_buf(out, "  lat (%s)   : ", msg);
596                         new_line = false;
597                         line = 0;
598                 }
599                 if (line)
600                         log_buf(out, ", ");
601                 log_buf(out, "%s%3.2f%%", ranges[i], io_u_lat[i]);
602                 line++;
603                 if (line == 5)
604                         new_line = true;
605         }
606
607         if (shown)
608                 log_buf(out, "\n");
609
610         return true;
611 }
612
613 static void show_lat_n(double *io_u_lat_n, struct buf_output *out)
614 {
615         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
616                                  "250=", "500=", "750=", "1000=", };
617
618         show_lat(io_u_lat_n, FIO_IO_U_LAT_N_NR, ranges, "nsec", out);
619 }
620
621 static void show_lat_u(double *io_u_lat_u, struct buf_output *out)
622 {
623         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
624                                  "250=", "500=", "750=", "1000=", };
625
626         show_lat(io_u_lat_u, FIO_IO_U_LAT_U_NR, ranges, "usec", out);
627 }
628
629 static void show_lat_m(double *io_u_lat_m, struct buf_output *out)
630 {
631         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
632                                  "250=", "500=", "750=", "1000=", "2000=",
633                                  ">=2000=", };
634
635         show_lat(io_u_lat_m, FIO_IO_U_LAT_M_NR, ranges, "msec", out);
636 }
637
638 static void show_latencies(struct thread_stat *ts, struct buf_output *out)
639 {
640         double io_u_lat_n[FIO_IO_U_LAT_N_NR];
641         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
642         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
643
644         stat_calc_lat_n(ts, io_u_lat_n);
645         stat_calc_lat_u(ts, io_u_lat_u);
646         stat_calc_lat_m(ts, io_u_lat_m);
647
648         show_lat_n(io_u_lat_n, out);
649         show_lat_u(io_u_lat_u, out);
650         show_lat_m(io_u_lat_m, out);
651 }
652
653 static int block_state_category(int block_state)
654 {
655         switch (block_state) {
656         case BLOCK_STATE_UNINIT:
657                 return 0;
658         case BLOCK_STATE_TRIMMED:
659         case BLOCK_STATE_WRITTEN:
660                 return 1;
661         case BLOCK_STATE_WRITE_FAILURE:
662         case BLOCK_STATE_TRIM_FAILURE:
663                 return 2;
664         default:
665                 /* Silence compile warning on some BSDs and have a return */
666                 assert(0);
667                 return -1;
668         }
669 }
670
671 static int compare_block_infos(const void *bs1, const void *bs2)
672 {
673         uint64_t block1 = *(uint64_t *)bs1;
674         uint64_t block2 = *(uint64_t *)bs2;
675         int state1 = BLOCK_INFO_STATE(block1);
676         int state2 = BLOCK_INFO_STATE(block2);
677         int bscat1 = block_state_category(state1);
678         int bscat2 = block_state_category(state2);
679         int cycles1 = BLOCK_INFO_TRIMS(block1);
680         int cycles2 = BLOCK_INFO_TRIMS(block2);
681
682         if (bscat1 < bscat2)
683                 return -1;
684         if (bscat1 > bscat2)
685                 return 1;
686
687         if (cycles1 < cycles2)
688                 return -1;
689         if (cycles1 > cycles2)
690                 return 1;
691
692         if (state1 < state2)
693                 return -1;
694         if (state1 > state2)
695                 return 1;
696
697         assert(block1 == block2);
698         return 0;
699 }
700
701 static int calc_block_percentiles(int nr_block_infos, uint32_t *block_infos,
702                                   fio_fp64_t *plist, unsigned int **percentiles,
703                                   unsigned int *types)
704 {
705         int len = 0;
706         int i, nr_uninit;
707
708         qsort(block_infos, nr_block_infos, sizeof(uint32_t), compare_block_infos);
709
710         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
711                 len++;
712
713         if (!len)
714                 return 0;
715
716         /*
717          * Sort the percentile list. Note that it may already be sorted if
718          * we are using the default values, but since it's a short list this
719          * isn't a worry. Also note that this does not work for NaN values.
720          */
721         if (len > 1)
722                 qsort(plist, len, sizeof(plist[0]), double_cmp);
723
724         /* Start only after the uninit entries end */
725         for (nr_uninit = 0;
726              nr_uninit < nr_block_infos
727                 && BLOCK_INFO_STATE(block_infos[nr_uninit]) == BLOCK_STATE_UNINIT;
728              nr_uninit ++)
729                 ;
730
731         if (nr_uninit == nr_block_infos)
732                 return 0;
733
734         *percentiles = calloc(len, sizeof(**percentiles));
735
736         for (i = 0; i < len; i++) {
737                 int idx = (plist[i].u.f * (nr_block_infos - nr_uninit) / 100)
738                                 + nr_uninit;
739                 (*percentiles)[i] = BLOCK_INFO_TRIMS(block_infos[idx]);
740         }
741
742         memset(types, 0, sizeof(*types) * BLOCK_STATE_COUNT);
743         for (i = 0; i < nr_block_infos; i++)
744                 types[BLOCK_INFO_STATE(block_infos[i])]++;
745
746         return len;
747 }
748
749 static const char *block_state_names[] = {
750         [BLOCK_STATE_UNINIT] = "unwritten",
751         [BLOCK_STATE_TRIMMED] = "trimmed",
752         [BLOCK_STATE_WRITTEN] = "written",
753         [BLOCK_STATE_TRIM_FAILURE] = "trim failure",
754         [BLOCK_STATE_WRITE_FAILURE] = "write failure",
755 };
756
757 static void show_block_infos(int nr_block_infos, uint32_t *block_infos,
758                              fio_fp64_t *plist, struct buf_output *out)
759 {
760         int len, pos, i;
761         unsigned int *percentiles = NULL;
762         unsigned int block_state_counts[BLOCK_STATE_COUNT];
763
764         len = calc_block_percentiles(nr_block_infos, block_infos, plist,
765                                      &percentiles, block_state_counts);
766
767         log_buf(out, "  block lifetime percentiles :\n   |");
768         pos = 0;
769         for (i = 0; i < len; i++) {
770                 uint32_t block_info = percentiles[i];
771 #define LINE_LENGTH     75
772                 char str[LINE_LENGTH];
773                 int strln = snprintf(str, LINE_LENGTH, " %3.2fth=%u%c",
774                                      plist[i].u.f, block_info,
775                                      i == len - 1 ? '\n' : ',');
776                 assert(strln < LINE_LENGTH);
777                 if (pos + strln > LINE_LENGTH) {
778                         pos = 0;
779                         log_buf(out, "\n   |");
780                 }
781                 log_buf(out, "%s", str);
782                 pos += strln;
783 #undef LINE_LENGTH
784         }
785         if (percentiles)
786                 free(percentiles);
787
788         log_buf(out, "        states               :");
789         for (i = 0; i < BLOCK_STATE_COUNT; i++)
790                 log_buf(out, " %s=%u%c",
791                          block_state_names[i], block_state_counts[i],
792                          i == BLOCK_STATE_COUNT - 1 ? '\n' : ',');
793 }
794
795 static void show_ss_normal(struct thread_stat *ts, struct buf_output *out)
796 {
797         char *p1, *p1alt, *p2;
798         unsigned long long bw_mean, iops_mean;
799         const int i2p = is_power_of_2(ts->kb_base);
800
801         if (!ts->ss_dur)
802                 return;
803
804         bw_mean = steadystate_bw_mean(ts);
805         iops_mean = steadystate_iops_mean(ts);
806
807         p1 = num2str(bw_mean / ts->kb_base, ts->sig_figs, ts->kb_base, i2p, ts->unit_base);
808         p1alt = num2str(bw_mean / ts->kb_base, ts->sig_figs, ts->kb_base, !i2p, ts->unit_base);
809         p2 = num2str(iops_mean, ts->sig_figs, 1, 0, N2S_NONE);
810
811         log_buf(out, "  steadystate  : attained=%s, bw=%s (%s), iops=%s, %s%s=%.3f%s\n",
812                 ts->ss_state & FIO_SS_ATTAINED ? "yes" : "no",
813                 p1, p1alt, p2,
814                 ts->ss_state & FIO_SS_IOPS ? "iops" : "bw",
815                 ts->ss_state & FIO_SS_SLOPE ? " slope": " mean dev",
816                 ts->ss_criterion.u.f,
817                 ts->ss_state & FIO_SS_PCT ? "%" : "");
818
819         free(p1);
820         free(p1alt);
821         free(p2);
822 }
823
824 static void show_agg_stats(struct disk_util_agg *agg, int terse,
825                            struct buf_output *out)
826 {
827         if (!agg->slavecount)
828                 return;
829
830         if (!terse) {
831                 log_buf(out, ", aggrios=%llu/%llu, aggrmerge=%llu/%llu, "
832                          "aggrticks=%llu/%llu, aggrin_queue=%llu, "
833                          "aggrutil=%3.2f%%",
834                         (unsigned long long) agg->ios[0] / agg->slavecount,
835                         (unsigned long long) agg->ios[1] / agg->slavecount,
836                         (unsigned long long) agg->merges[0] / agg->slavecount,
837                         (unsigned long long) agg->merges[1] / agg->slavecount,
838                         (unsigned long long) agg->ticks[0] / agg->slavecount,
839                         (unsigned long long) agg->ticks[1] / agg->slavecount,
840                         (unsigned long long) agg->time_in_queue / agg->slavecount,
841                         agg->max_util.u.f);
842         } else {
843                 log_buf(out, ";slaves;%llu;%llu;%llu;%llu;%llu;%llu;%llu;%3.2f%%",
844                         (unsigned long long) agg->ios[0] / agg->slavecount,
845                         (unsigned long long) agg->ios[1] / agg->slavecount,
846                         (unsigned long long) agg->merges[0] / agg->slavecount,
847                         (unsigned long long) agg->merges[1] / agg->slavecount,
848                         (unsigned long long) agg->ticks[0] / agg->slavecount,
849                         (unsigned long long) agg->ticks[1] / agg->slavecount,
850                         (unsigned long long) agg->time_in_queue / agg->slavecount,
851                         agg->max_util.u.f);
852         }
853 }
854
855 static void aggregate_slaves_stats(struct disk_util *masterdu)
856 {
857         struct disk_util_agg *agg = &masterdu->agg;
858         struct disk_util_stat *dus;
859         struct flist_head *entry;
860         struct disk_util *slavedu;
861         double util;
862
863         flist_for_each(entry, &masterdu->slaves) {
864                 slavedu = flist_entry(entry, struct disk_util, slavelist);
865                 dus = &slavedu->dus;
866                 agg->ios[0] += dus->s.ios[0];
867                 agg->ios[1] += dus->s.ios[1];
868                 agg->merges[0] += dus->s.merges[0];
869                 agg->merges[1] += dus->s.merges[1];
870                 agg->sectors[0] += dus->s.sectors[0];
871                 agg->sectors[1] += dus->s.sectors[1];
872                 agg->ticks[0] += dus->s.ticks[0];
873                 agg->ticks[1] += dus->s.ticks[1];
874                 agg->time_in_queue += dus->s.time_in_queue;
875                 agg->slavecount++;
876
877                 util = (double) (100 * dus->s.io_ticks / (double) slavedu->dus.s.msec);
878                 /* System utilization is the utilization of the
879                  * component with the highest utilization.
880                  */
881                 if (util > agg->max_util.u.f)
882                         agg->max_util.u.f = util;
883
884         }
885
886         if (agg->max_util.u.f > 100.0)
887                 agg->max_util.u.f = 100.0;
888 }
889
890 void print_disk_util(struct disk_util_stat *dus, struct disk_util_agg *agg,
891                      int terse, struct buf_output *out)
892 {
893         double util = 0;
894
895         if (dus->s.msec)
896                 util = (double) 100 * dus->s.io_ticks / (double) dus->s.msec;
897         if (util > 100.0)
898                 util = 100.0;
899
900         if (!terse) {
901                 if (agg->slavecount)
902                         log_buf(out, "  ");
903
904                 log_buf(out, "  %s: ios=%llu/%llu, merge=%llu/%llu, "
905                          "ticks=%llu/%llu, in_queue=%llu, util=%3.2f%%",
906                                 dus->name,
907                                 (unsigned long long) dus->s.ios[0],
908                                 (unsigned long long) dus->s.ios[1],
909                                 (unsigned long long) dus->s.merges[0],
910                                 (unsigned long long) dus->s.merges[1],
911                                 (unsigned long long) dus->s.ticks[0],
912                                 (unsigned long long) dus->s.ticks[1],
913                                 (unsigned long long) dus->s.time_in_queue,
914                                 util);
915         } else {
916                 log_buf(out, ";%s;%llu;%llu;%llu;%llu;%llu;%llu;%llu;%3.2f%%",
917                                 dus->name,
918                                 (unsigned long long) dus->s.ios[0],
919                                 (unsigned long long) dus->s.ios[1],
920                                 (unsigned long long) dus->s.merges[0],
921                                 (unsigned long long) dus->s.merges[1],
922                                 (unsigned long long) dus->s.ticks[0],
923                                 (unsigned long long) dus->s.ticks[1],
924                                 (unsigned long long) dus->s.time_in_queue,
925                                 util);
926         }
927
928         /*
929          * If the device has slaves, aggregate the stats for
930          * those slave devices also.
931          */
932         show_agg_stats(agg, terse, out);
933
934         if (!terse)
935                 log_buf(out, "\n");
936 }
937
938 void json_array_add_disk_util(struct disk_util_stat *dus,
939                 struct disk_util_agg *agg, struct json_array *array)
940 {
941         struct json_object *obj;
942         double util = 0;
943
944         if (dus->s.msec)
945                 util = (double) 100 * dus->s.io_ticks / (double) dus->s.msec;
946         if (util > 100.0)
947                 util = 100.0;
948
949         obj = json_create_object();
950         json_array_add_value_object(array, obj);
951
952         json_object_add_value_string(obj, "name", dus->name);
953         json_object_add_value_int(obj, "read_ios", dus->s.ios[0]);
954         json_object_add_value_int(obj, "write_ios", dus->s.ios[1]);
955         json_object_add_value_int(obj, "read_merges", dus->s.merges[0]);
956         json_object_add_value_int(obj, "write_merges", dus->s.merges[1]);
957         json_object_add_value_int(obj, "read_ticks", dus->s.ticks[0]);
958         json_object_add_value_int(obj, "write_ticks", dus->s.ticks[1]);
959         json_object_add_value_int(obj, "in_queue", dus->s.time_in_queue);
960         json_object_add_value_float(obj, "util", util);
961
962         /*
963          * If the device has slaves, aggregate the stats for
964          * those slave devices also.
965          */
966         if (!agg->slavecount)
967                 return;
968         json_object_add_value_int(obj, "aggr_read_ios",
969                                 agg->ios[0] / agg->slavecount);
970         json_object_add_value_int(obj, "aggr_write_ios",
971                                 agg->ios[1] / agg->slavecount);
972         json_object_add_value_int(obj, "aggr_read_merges",
973                                 agg->merges[0] / agg->slavecount);
974         json_object_add_value_int(obj, "aggr_write_merge",
975                                 agg->merges[1] / agg->slavecount);
976         json_object_add_value_int(obj, "aggr_read_ticks",
977                                 agg->ticks[0] / agg->slavecount);
978         json_object_add_value_int(obj, "aggr_write_ticks",
979                                 agg->ticks[1] / agg->slavecount);
980         json_object_add_value_int(obj, "aggr_in_queue",
981                                 agg->time_in_queue / agg->slavecount);
982         json_object_add_value_float(obj, "aggr_util", agg->max_util.u.f);
983 }
984
985 static void json_object_add_disk_utils(struct json_object *obj,
986                                        struct flist_head *head)
987 {
988         struct json_array *array = json_create_array();
989         struct flist_head *entry;
990         struct disk_util *du;
991
992         json_object_add_value_array(obj, "disk_util", array);
993
994         flist_for_each(entry, head) {
995                 du = flist_entry(entry, struct disk_util, list);
996
997                 aggregate_slaves_stats(du);
998                 json_array_add_disk_util(&du->dus, &du->agg, array);
999         }
1000 }
1001
1002 void show_disk_util(int terse, struct json_object *parent,
1003                     struct buf_output *out)
1004 {
1005         struct flist_head *entry;
1006         struct disk_util *du;
1007         bool do_json;
1008
1009         if (!is_running_backend())
1010                 return;
1011
1012         if (flist_empty(&disk_list)) {
1013                 return;
1014         }
1015
1016         if ((output_format & FIO_OUTPUT_JSON) && parent)
1017                 do_json = true;
1018         else
1019                 do_json = false;
1020
1021         if (!terse && !do_json)
1022                 log_buf(out, "\nDisk stats (read/write):\n");
1023
1024         if (do_json)
1025                 json_object_add_disk_utils(parent, &disk_list);
1026         else if (output_format & ~(FIO_OUTPUT_JSON | FIO_OUTPUT_JSON_PLUS)) {
1027                 flist_for_each(entry, &disk_list) {
1028                         du = flist_entry(entry, struct disk_util, list);
1029
1030                         aggregate_slaves_stats(du);
1031                         print_disk_util(&du->dus, &du->agg, terse, out);
1032                 }
1033         }
1034 }
1035
1036 static void show_thread_status_normal(struct thread_stat *ts,
1037                                       struct group_run_stats *rs,
1038                                       struct buf_output *out)
1039 {
1040         double usr_cpu, sys_cpu;
1041         unsigned long runtime;
1042         double io_u_dist[FIO_IO_U_MAP_NR];
1043         time_t time_p;
1044         char time_buf[32];
1045
1046         if (!ddir_rw_sum(ts->io_bytes) && !ddir_rw_sum(ts->total_io_u))
1047                 return;
1048
1049         memset(time_buf, 0, sizeof(time_buf));
1050
1051         time(&time_p);
1052         os_ctime_r((const time_t *) &time_p, time_buf, sizeof(time_buf));
1053
1054         if (!ts->error) {
1055                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d: pid=%d: %s",
1056                                         ts->name, ts->groupid, ts->members,
1057                                         ts->error, (int) ts->pid, time_buf);
1058         } else {
1059                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d (%s): pid=%d: %s",
1060                                         ts->name, ts->groupid, ts->members,
1061                                         ts->error, ts->verror, (int) ts->pid,
1062                                         time_buf);
1063         }
1064
1065         if (strlen(ts->description))
1066                 log_buf(out, "  Description  : [%s]\n", ts->description);
1067
1068         if (ts->io_bytes[DDIR_READ])
1069                 show_ddir_status(rs, ts, DDIR_READ, out);
1070         if (ts->io_bytes[DDIR_WRITE])
1071                 show_ddir_status(rs, ts, DDIR_WRITE, out);
1072         if (ts->io_bytes[DDIR_TRIM])
1073                 show_ddir_status(rs, ts, DDIR_TRIM, out);
1074
1075         show_latencies(ts, out);
1076
1077         if (ts->sync_stat.samples)
1078                 show_ddir_status(rs, ts, DDIR_SYNC, out);
1079
1080         runtime = ts->total_run_time;
1081         if (runtime) {
1082                 double runt = (double) runtime;
1083
1084                 usr_cpu = (double) ts->usr_time * 100 / runt;
1085                 sys_cpu = (double) ts->sys_time * 100 / runt;
1086         } else {
1087                 usr_cpu = 0;
1088                 sys_cpu = 0;
1089         }
1090
1091         log_buf(out, "  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%llu,"
1092                  " majf=%llu, minf=%llu\n", usr_cpu, sys_cpu,
1093                         (unsigned long long) ts->ctx,
1094                         (unsigned long long) ts->majf,
1095                         (unsigned long long) ts->minf);
1096
1097         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1098         log_buf(out, "  IO depths    : 1=%3.1f%%, 2=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%,"
1099                  " 16=%3.1f%%, 32=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
1100                                         io_u_dist[1], io_u_dist[2],
1101                                         io_u_dist[3], io_u_dist[4],
1102                                         io_u_dist[5], io_u_dist[6]);
1103
1104         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
1105         log_buf(out, "     submit    : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
1106                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
1107                                         io_u_dist[1], io_u_dist[2],
1108                                         io_u_dist[3], io_u_dist[4],
1109                                         io_u_dist[5], io_u_dist[6]);
1110         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
1111         log_buf(out, "     complete  : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
1112                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
1113                                         io_u_dist[1], io_u_dist[2],
1114                                         io_u_dist[3], io_u_dist[4],
1115                                         io_u_dist[5], io_u_dist[6]);
1116         log_buf(out, "     issued rwts: total=%llu,%llu,%llu,%llu"
1117                                  " short=%llu,%llu,%llu,0"
1118                                  " dropped=%llu,%llu,%llu,0\n",
1119                                         (unsigned long long) ts->total_io_u[0],
1120                                         (unsigned long long) ts->total_io_u[1],
1121                                         (unsigned long long) ts->total_io_u[2],
1122                                         (unsigned long long) ts->total_io_u[3],
1123                                         (unsigned long long) ts->short_io_u[0],
1124                                         (unsigned long long) ts->short_io_u[1],
1125                                         (unsigned long long) ts->short_io_u[2],
1126                                         (unsigned long long) ts->drop_io_u[0],
1127                                         (unsigned long long) ts->drop_io_u[1],
1128                                         (unsigned long long) ts->drop_io_u[2]);
1129         if (ts->continue_on_error) {
1130                 log_buf(out, "     errors    : total=%llu, first_error=%d/<%s>\n",
1131                                         (unsigned long long)ts->total_err_count,
1132                                         ts->first_error,
1133                                         strerror(ts->first_error));
1134         }
1135         if (ts->latency_depth) {
1136                 log_buf(out, "     latency   : target=%llu, window=%llu, percentile=%.2f%%, depth=%u\n",
1137                                         (unsigned long long)ts->latency_target,
1138                                         (unsigned long long)ts->latency_window,
1139                                         ts->latency_percentile.u.f,
1140                                         ts->latency_depth);
1141         }
1142
1143         if (ts->nr_block_infos)
1144                 show_block_infos(ts->nr_block_infos, ts->block_infos,
1145                                   ts->percentile_list, out);
1146
1147         if (ts->ss_dur)
1148                 show_ss_normal(ts, out);
1149 }
1150
1151 static void show_ddir_status_terse(struct thread_stat *ts,
1152                                    struct group_run_stats *rs, int ddir,
1153                                    int ver, struct buf_output *out)
1154 {
1155         unsigned long long min, max, minv, maxv, bw, iops;
1156         unsigned long long *ovals = NULL;
1157         double mean, dev;
1158         unsigned int len;
1159         int i, bw_stat;
1160
1161         assert(ddir_rw(ddir));
1162
1163         iops = bw = 0;
1164         if (ts->runtime[ddir]) {
1165                 uint64_t runt = ts->runtime[ddir];
1166
1167                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024; /* KiB/s */
1168                 iops = (1000 * (uint64_t) ts->total_io_u[ddir]) / runt;
1169         }
1170
1171         log_buf(out, ";%llu;%llu;%llu;%llu",
1172                 (unsigned long long) ts->io_bytes[ddir] >> 10, bw, iops,
1173                                         (unsigned long long) ts->runtime[ddir]);
1174
1175         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
1176                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
1177         else
1178                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
1179
1180         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
1181                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
1182         else
1183                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
1184
1185         if (ts->lat_percentiles)
1186                 len = calc_clat_percentiles(ts->io_u_plat[FIO_LAT][ddir],
1187                                         ts->lat_stat[ddir].samples,
1188                                         ts->percentile_list, &ovals, &maxv,
1189                                         &minv);
1190         else if (ts->clat_percentiles)
1191                 len = calc_clat_percentiles(ts->io_u_plat[FIO_CLAT][ddir],
1192                                         ts->clat_stat[ddir].samples,
1193                                         ts->percentile_list, &ovals, &maxv,
1194                                         &minv);
1195         else
1196                 len = 0;
1197
1198         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
1199                 if (i >= len) {
1200                         log_buf(out, ";0%%=0");
1201                         continue;
1202                 }
1203                 log_buf(out, ";%f%%=%llu", ts->percentile_list[i].u.f, ovals[i]/1000);
1204         }
1205
1206         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
1207                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
1208         else
1209                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
1210
1211         free(ovals);
1212
1213         bw_stat = calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev);
1214         if (bw_stat) {
1215                 double p_of_agg = 100.0;
1216
1217                 if (rs->agg[ddir]) {
1218                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
1219                         if (p_of_agg > 100.0)
1220                                 p_of_agg = 100.0;
1221                 }
1222
1223                 log_buf(out, ";%llu;%llu;%f%%;%f;%f", min, max, p_of_agg, mean, dev);
1224         } else
1225                 log_buf(out, ";%llu;%llu;%f%%;%f;%f", 0ULL, 0ULL, 0.0, 0.0, 0.0);
1226
1227         if (ver == 5) {
1228                 if (bw_stat)
1229                         log_buf(out, ";%" PRIu64, (&ts->bw_stat[ddir])->samples);
1230                 else
1231                         log_buf(out, ";%lu", 0UL);
1232
1233                 if (calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev))
1234                         log_buf(out, ";%llu;%llu;%f;%f;%" PRIu64, min, max,
1235                                 mean, dev, (&ts->iops_stat[ddir])->samples);
1236                 else
1237                         log_buf(out, ";%llu;%llu;%f;%f;%lu", 0ULL, 0ULL, 0.0, 0.0, 0UL);
1238         }
1239 }
1240
1241 static struct json_object *add_ddir_lat_json(struct thread_stat *ts, uint32_t percentiles,
1242                 struct io_stat *lat_stat, uint64_t *io_u_plat)
1243 {
1244         char buf[120];
1245         double mean, dev;
1246         unsigned int i, len;
1247         struct json_object *lat_object, *percentile_object, *clat_bins_object;
1248         unsigned long long min, max, maxv, minv, *ovals = NULL;
1249
1250         if (!calc_lat(lat_stat, &min, &max, &mean, &dev)) {
1251                 min = max = 0;
1252                 mean = dev = 0.0;
1253         }
1254         lat_object = json_create_object();
1255         json_object_add_value_int(lat_object, "min", min);
1256         json_object_add_value_int(lat_object, "max", max);
1257         json_object_add_value_float(lat_object, "mean", mean);
1258         json_object_add_value_float(lat_object, "stddev", dev);
1259         json_object_add_value_int(lat_object, "N", lat_stat->samples);
1260
1261         if (percentiles && lat_stat->samples) {
1262                 len = calc_clat_percentiles(io_u_plat, lat_stat->samples,
1263                                 ts->percentile_list, &ovals, &maxv, &minv);
1264
1265                 if (len > FIO_IO_U_LIST_MAX_LEN)
1266                         len = FIO_IO_U_LIST_MAX_LEN;
1267
1268                 percentile_object = json_create_object();
1269                 json_object_add_value_object(lat_object, "percentile", percentile_object);
1270                 for (i = 0; i < len; i++) {
1271                         snprintf(buf, sizeof(buf), "%f", ts->percentile_list[i].u.f);
1272                         json_object_add_value_int(percentile_object, buf, ovals[i]);
1273                 }
1274                 free(ovals);
1275
1276                 if (output_format & FIO_OUTPUT_JSON_PLUS) {
1277                         clat_bins_object = json_create_object();
1278                         json_object_add_value_object(lat_object, "bins", clat_bins_object);
1279
1280                         for(i = 0; i < FIO_IO_U_PLAT_NR; i++)
1281                                 if (io_u_plat[i]) {
1282                                         snprintf(buf, sizeof(buf), "%llu", plat_idx_to_val(i));
1283                                         json_object_add_value_int(clat_bins_object, buf, io_u_plat[i]);
1284                                 }
1285                 }
1286         }
1287
1288         return lat_object;
1289 }
1290
1291 static void add_ddir_status_json(struct thread_stat *ts,
1292                 struct group_run_stats *rs, int ddir, struct json_object *parent)
1293 {
1294         unsigned long long min, max;
1295         unsigned long long bw_bytes, bw;
1296         double mean, dev, iops;
1297         struct json_object *dir_object, *tmp_object;
1298         double p_of_agg = 100.0;
1299
1300         assert(ddir_rw(ddir) || ddir_sync(ddir));
1301
1302         if (ts->unified_rw_rep && ddir != DDIR_READ)
1303                 return;
1304
1305         dir_object = json_create_object();
1306         json_object_add_value_object(parent,
1307                 ts->unified_rw_rep ? "mixed" : io_ddir_name(ddir), dir_object);
1308
1309         if (ddir_rw(ddir)) {
1310                 bw_bytes = 0;
1311                 bw = 0;
1312                 iops = 0.0;
1313                 if (ts->runtime[ddir]) {
1314                         uint64_t runt = ts->runtime[ddir];
1315
1316                         bw_bytes = ((1000 * ts->io_bytes[ddir]) / runt); /* Bytes/s */
1317                         bw = bw_bytes / 1024; /* KiB/s */
1318                         iops = (1000.0 * (uint64_t) ts->total_io_u[ddir]) / runt;
1319                 }
1320
1321                 json_object_add_value_int(dir_object, "io_bytes", ts->io_bytes[ddir]);
1322                 json_object_add_value_int(dir_object, "io_kbytes", ts->io_bytes[ddir] >> 10);
1323                 json_object_add_value_int(dir_object, "bw_bytes", bw_bytes);
1324                 json_object_add_value_int(dir_object, "bw", bw);
1325                 json_object_add_value_float(dir_object, "iops", iops);
1326                 json_object_add_value_int(dir_object, "runtime", ts->runtime[ddir]);
1327                 json_object_add_value_int(dir_object, "total_ios", ts->total_io_u[ddir]);
1328                 json_object_add_value_int(dir_object, "short_ios", ts->short_io_u[ddir]);
1329                 json_object_add_value_int(dir_object, "drop_ios", ts->drop_io_u[ddir]);
1330
1331                 tmp_object = add_ddir_lat_json(ts, ts->slat_percentiles,
1332                                 &ts->slat_stat[ddir], ts->io_u_plat[FIO_SLAT][ddir]);
1333                 json_object_add_value_object(dir_object, "slat_ns", tmp_object);
1334
1335                 tmp_object = add_ddir_lat_json(ts, ts->clat_percentiles,
1336                                 &ts->clat_stat[ddir], ts->io_u_plat[FIO_CLAT][ddir]);
1337                 json_object_add_value_object(dir_object, "clat_ns", tmp_object);
1338
1339                 tmp_object = add_ddir_lat_json(ts, ts->lat_percentiles,
1340                                 &ts->lat_stat[ddir], ts->io_u_plat[FIO_LAT][ddir]);
1341                 json_object_add_value_object(dir_object, "lat_ns", tmp_object);
1342         } else {
1343                 json_object_add_value_int(dir_object, "total_ios", ts->total_io_u[DDIR_SYNC]);
1344                 tmp_object = add_ddir_lat_json(ts, ts->lat_percentiles | ts->clat_percentiles,
1345                                 &ts->sync_stat, ts->io_u_sync_plat);
1346                 json_object_add_value_object(dir_object, "lat_ns", tmp_object);
1347         }
1348
1349         if (!ddir_rw(ddir))
1350                 return;
1351
1352         /* Only print PRIO latencies if some high priority samples were gathered */
1353         if (ts->clat_high_prio_stat[ddir].samples > 0) {
1354                 const char *high, *low;
1355
1356                 if (ts->lat_percentiles) {
1357                         high = "lat_prio";
1358                         low = "lat_low_prio";
1359                 } else {
1360                         high = "clat_prio";
1361                         low = "clat_low_prio";
1362                 }
1363
1364                 tmp_object = add_ddir_lat_json(ts, ts->clat_percentiles | ts->lat_percentiles,
1365                                 &ts->clat_high_prio_stat[ddir], ts->io_u_plat_high_prio[ddir]);
1366                 json_object_add_value_object(dir_object, high, tmp_object);
1367
1368                 tmp_object = add_ddir_lat_json(ts, ts->clat_percentiles | ts->lat_percentiles,
1369                                 &ts->clat_prio_stat[ddir], ts->io_u_plat_prio[ddir]);
1370                 json_object_add_value_object(dir_object, low, tmp_object);
1371         }
1372
1373         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
1374                 if (rs->agg[ddir]) {
1375                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
1376                         if (p_of_agg > 100.0)
1377                                 p_of_agg = 100.0;
1378                 }
1379         } else {
1380                 min = max = 0;
1381                 p_of_agg = mean = dev = 0.0;
1382         }
1383
1384         json_object_add_value_int(dir_object, "bw_min", min);
1385         json_object_add_value_int(dir_object, "bw_max", max);
1386         json_object_add_value_float(dir_object, "bw_agg", p_of_agg);
1387         json_object_add_value_float(dir_object, "bw_mean", mean);
1388         json_object_add_value_float(dir_object, "bw_dev", dev);
1389         json_object_add_value_int(dir_object, "bw_samples",
1390                                 (&ts->bw_stat[ddir])->samples);
1391
1392         if (!calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev)) {
1393                 min = max = 0;
1394                 mean = dev = 0.0;
1395         }
1396         json_object_add_value_int(dir_object, "iops_min", min);
1397         json_object_add_value_int(dir_object, "iops_max", max);
1398         json_object_add_value_float(dir_object, "iops_mean", mean);
1399         json_object_add_value_float(dir_object, "iops_stddev", dev);
1400         json_object_add_value_int(dir_object, "iops_samples",
1401                                 (&ts->iops_stat[ddir])->samples);
1402
1403         if (ts->cachehit + ts->cachemiss) {
1404                 uint64_t total;
1405                 double hit;
1406
1407                 total = ts->cachehit + ts->cachemiss;
1408                 hit = (double) ts->cachehit / (double) total;
1409                 hit *= 100.0;
1410                 json_object_add_value_float(dir_object, "cachehit", hit);
1411         }
1412 }
1413
1414 static void show_thread_status_terse_all(struct thread_stat *ts,
1415                                          struct group_run_stats *rs, int ver,
1416                                          struct buf_output *out)
1417 {
1418         double io_u_dist[FIO_IO_U_MAP_NR];
1419         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1420         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1421         double usr_cpu, sys_cpu;
1422         int i;
1423
1424         /* General Info */
1425         if (ver == 2)
1426                 log_buf(out, "2;%s;%d;%d", ts->name, ts->groupid, ts->error);
1427         else
1428                 log_buf(out, "%d;%s;%s;%d;%d", ver, fio_version_string,
1429                         ts->name, ts->groupid, ts->error);
1430
1431         /* Log Read Status */
1432         show_ddir_status_terse(ts, rs, DDIR_READ, ver, out);
1433         /* Log Write Status */
1434         show_ddir_status_terse(ts, rs, DDIR_WRITE, ver, out);
1435         /* Log Trim Status */
1436         if (ver == 2 || ver == 4 || ver == 5)
1437                 show_ddir_status_terse(ts, rs, DDIR_TRIM, ver, out);
1438
1439         /* CPU Usage */
1440         if (ts->total_run_time) {
1441                 double runt = (double) ts->total_run_time;
1442
1443                 usr_cpu = (double) ts->usr_time * 100 / runt;
1444                 sys_cpu = (double) ts->sys_time * 100 / runt;
1445         } else {
1446                 usr_cpu = 0;
1447                 sys_cpu = 0;
1448         }
1449
1450         log_buf(out, ";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
1451                                                 (unsigned long long) ts->ctx,
1452                                                 (unsigned long long) ts->majf,
1453                                                 (unsigned long long) ts->minf);
1454
1455         /* Calc % distribution of IO depths, usecond, msecond latency */
1456         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1457         stat_calc_lat_nu(ts, io_u_lat_u);
1458         stat_calc_lat_m(ts, io_u_lat_m);
1459
1460         /* Only show fixed 7 I/O depth levels*/
1461         log_buf(out, ";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
1462                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
1463                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
1464
1465         /* Microsecond latency */
1466         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1467                 log_buf(out, ";%3.2f%%", io_u_lat_u[i]);
1468         /* Millisecond latency */
1469         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1470                 log_buf(out, ";%3.2f%%", io_u_lat_m[i]);
1471
1472         /* disk util stats, if any */
1473         if (ver >= 3 && is_running_backend())
1474                 show_disk_util(1, NULL, out);
1475
1476         /* Additional output if continue_on_error set - default off*/
1477         if (ts->continue_on_error)
1478                 log_buf(out, ";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
1479
1480         /* Additional output if description is set */
1481         if (strlen(ts->description)) {
1482                 if (ver == 2)
1483                         log_buf(out, "\n");
1484                 log_buf(out, ";%s", ts->description);
1485         }
1486
1487         log_buf(out, "\n");
1488 }
1489
1490 static void json_add_job_opts(struct json_object *root, const char *name,
1491                               struct flist_head *opt_list)
1492 {
1493         struct json_object *dir_object;
1494         struct flist_head *entry;
1495         struct print_option *p;
1496
1497         if (flist_empty(opt_list))
1498                 return;
1499
1500         dir_object = json_create_object();
1501         json_object_add_value_object(root, name, dir_object);
1502
1503         flist_for_each(entry, opt_list) {
1504                 const char *pos = "";
1505
1506                 p = flist_entry(entry, struct print_option, list);
1507                 if (p->value)
1508                         pos = p->value;
1509                 json_object_add_value_string(dir_object, p->name, pos);
1510         }
1511 }
1512
1513 static struct json_object *show_thread_status_json(struct thread_stat *ts,
1514                                                    struct group_run_stats *rs,
1515                                                    struct flist_head *opt_list)
1516 {
1517         struct json_object *root, *tmp;
1518         struct jobs_eta *je;
1519         double io_u_dist[FIO_IO_U_MAP_NR];
1520         double io_u_lat_n[FIO_IO_U_LAT_N_NR];
1521         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1522         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1523         double usr_cpu, sys_cpu;
1524         int i;
1525         size_t size;
1526
1527         root = json_create_object();
1528         json_object_add_value_string(root, "jobname", ts->name);
1529         json_object_add_value_int(root, "groupid", ts->groupid);
1530         json_object_add_value_int(root, "error", ts->error);
1531
1532         /* ETA Info */
1533         je = get_jobs_eta(true, &size);
1534         if (je) {
1535                 json_object_add_value_int(root, "eta", je->eta_sec);
1536                 json_object_add_value_int(root, "elapsed", je->elapsed_sec);
1537         }
1538
1539         if (opt_list)
1540                 json_add_job_opts(root, "job options", opt_list);
1541
1542         add_ddir_status_json(ts, rs, DDIR_READ, root);
1543         add_ddir_status_json(ts, rs, DDIR_WRITE, root);
1544         add_ddir_status_json(ts, rs, DDIR_TRIM, root);
1545         add_ddir_status_json(ts, rs, DDIR_SYNC, root);
1546
1547         /* CPU Usage */
1548         if (ts->total_run_time) {
1549                 double runt = (double) ts->total_run_time;
1550
1551                 usr_cpu = (double) ts->usr_time * 100 / runt;
1552                 sys_cpu = (double) ts->sys_time * 100 / runt;
1553         } else {
1554                 usr_cpu = 0;
1555                 sys_cpu = 0;
1556         }
1557         json_object_add_value_int(root, "job_runtime", ts->total_run_time);
1558         json_object_add_value_float(root, "usr_cpu", usr_cpu);
1559         json_object_add_value_float(root, "sys_cpu", sys_cpu);
1560         json_object_add_value_int(root, "ctx", ts->ctx);
1561         json_object_add_value_int(root, "majf", ts->majf);
1562         json_object_add_value_int(root, "minf", ts->minf);
1563
1564         /* Calc % distribution of IO depths */
1565         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1566         tmp = json_create_object();
1567         json_object_add_value_object(root, "iodepth_level", tmp);
1568         /* Only show fixed 7 I/O depth levels*/
1569         for (i = 0; i < 7; i++) {
1570                 char name[20];
1571                 if (i < 6)
1572                         snprintf(name, 20, "%d", 1 << i);
1573                 else
1574                         snprintf(name, 20, ">=%d", 1 << i);
1575                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1576         }
1577
1578         /* Calc % distribution of submit IO depths */
1579         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
1580         tmp = json_create_object();
1581         json_object_add_value_object(root, "iodepth_submit", tmp);
1582         /* Only show fixed 7 I/O depth levels*/
1583         for (i = 0; i < 7; i++) {
1584                 char name[20];
1585                 if (i == 0)
1586                         snprintf(name, 20, "0");
1587                 else if (i < 6)
1588                         snprintf(name, 20, "%d", 1 << (i+1));
1589                 else
1590                         snprintf(name, 20, ">=%d", 1 << i);
1591                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1592         }
1593
1594         /* Calc % distribution of completion IO depths */
1595         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
1596         tmp = json_create_object();
1597         json_object_add_value_object(root, "iodepth_complete", tmp);
1598         /* Only show fixed 7 I/O depth levels*/
1599         for (i = 0; i < 7; i++) {
1600                 char name[20];
1601                 if (i == 0)
1602                         snprintf(name, 20, "0");
1603                 else if (i < 6)
1604                         snprintf(name, 20, "%d", 1 << (i+1));
1605                 else
1606                         snprintf(name, 20, ">=%d", 1 << i);
1607                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1608         }
1609
1610         /* Calc % distribution of nsecond, usecond, msecond latency */
1611         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1612         stat_calc_lat_n(ts, io_u_lat_n);
1613         stat_calc_lat_u(ts, io_u_lat_u);
1614         stat_calc_lat_m(ts, io_u_lat_m);
1615
1616         /* Nanosecond latency */
1617         tmp = json_create_object();
1618         json_object_add_value_object(root, "latency_ns", tmp);
1619         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++) {
1620                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1621                                  "250", "500", "750", "1000", };
1622                 json_object_add_value_float(tmp, ranges[i], io_u_lat_n[i]);
1623         }
1624         /* Microsecond latency */
1625         tmp = json_create_object();
1626         json_object_add_value_object(root, "latency_us", tmp);
1627         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++) {
1628                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1629                                  "250", "500", "750", "1000", };
1630                 json_object_add_value_float(tmp, ranges[i], io_u_lat_u[i]);
1631         }
1632         /* Millisecond latency */
1633         tmp = json_create_object();
1634         json_object_add_value_object(root, "latency_ms", tmp);
1635         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++) {
1636                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1637                                  "250", "500", "750", "1000", "2000",
1638                                  ">=2000", };
1639                 json_object_add_value_float(tmp, ranges[i], io_u_lat_m[i]);
1640         }
1641
1642         /* Additional output if continue_on_error set - default off*/
1643         if (ts->continue_on_error) {
1644                 json_object_add_value_int(root, "total_err", ts->total_err_count);
1645                 json_object_add_value_int(root, "first_error", ts->first_error);
1646         }
1647
1648         if (ts->latency_depth) {
1649                 json_object_add_value_int(root, "latency_depth", ts->latency_depth);
1650                 json_object_add_value_int(root, "latency_target", ts->latency_target);
1651                 json_object_add_value_float(root, "latency_percentile", ts->latency_percentile.u.f);
1652                 json_object_add_value_int(root, "latency_window", ts->latency_window);
1653         }
1654
1655         /* Additional output if description is set */
1656         if (strlen(ts->description))
1657                 json_object_add_value_string(root, "desc", ts->description);
1658
1659         if (ts->nr_block_infos) {
1660                 /* Block error histogram and types */
1661                 int len;
1662                 unsigned int *percentiles = NULL;
1663                 unsigned int block_state_counts[BLOCK_STATE_COUNT];
1664
1665                 len = calc_block_percentiles(ts->nr_block_infos, ts->block_infos,
1666                                              ts->percentile_list,
1667                                              &percentiles, block_state_counts);
1668
1669                 if (len) {
1670                         struct json_object *block, *percentile_object, *states;
1671                         int state;
1672                         block = json_create_object();
1673                         json_object_add_value_object(root, "block", block);
1674
1675                         percentile_object = json_create_object();
1676                         json_object_add_value_object(block, "percentiles",
1677                                                      percentile_object);
1678                         for (i = 0; i < len; i++) {
1679                                 char buf[20];
1680                                 snprintf(buf, sizeof(buf), "%f",
1681                                          ts->percentile_list[i].u.f);
1682                                 json_object_add_value_int(percentile_object,
1683                                                           buf,
1684                                                           percentiles[i]);
1685                         }
1686
1687                         states = json_create_object();
1688                         json_object_add_value_object(block, "states", states);
1689                         for (state = 0; state < BLOCK_STATE_COUNT; state++) {
1690                                 json_object_add_value_int(states,
1691                                         block_state_names[state],
1692                                         block_state_counts[state]);
1693                         }
1694                         free(percentiles);
1695                 }
1696         }
1697
1698         if (ts->ss_dur) {
1699                 struct json_object *data;
1700                 struct json_array *iops, *bw;
1701                 int j, k, l;
1702                 char ss_buf[64];
1703
1704                 snprintf(ss_buf, sizeof(ss_buf), "%s%s:%f%s",
1705                         ts->ss_state & FIO_SS_IOPS ? "iops" : "bw",
1706                         ts->ss_state & FIO_SS_SLOPE ? "_slope" : "",
1707                         (float) ts->ss_limit.u.f,
1708                         ts->ss_state & FIO_SS_PCT ? "%" : "");
1709
1710                 tmp = json_create_object();
1711                 json_object_add_value_object(root, "steadystate", tmp);
1712                 json_object_add_value_string(tmp, "ss", ss_buf);
1713                 json_object_add_value_int(tmp, "duration", (int)ts->ss_dur);
1714                 json_object_add_value_int(tmp, "attained", (ts->ss_state & FIO_SS_ATTAINED) > 0);
1715
1716                 snprintf(ss_buf, sizeof(ss_buf), "%f%s", (float) ts->ss_criterion.u.f,
1717                         ts->ss_state & FIO_SS_PCT ? "%" : "");
1718                 json_object_add_value_string(tmp, "criterion", ss_buf);
1719                 json_object_add_value_float(tmp, "max_deviation", ts->ss_deviation.u.f);
1720                 json_object_add_value_float(tmp, "slope", ts->ss_slope.u.f);
1721
1722                 data = json_create_object();
1723                 json_object_add_value_object(tmp, "data", data);
1724                 bw = json_create_array();
1725                 iops = json_create_array();
1726
1727                 /*
1728                 ** if ss was attained or the buffer is not full,
1729                 ** ss->head points to the first element in the list.
1730                 ** otherwise it actually points to the second element
1731                 ** in the list
1732                 */
1733                 if ((ts->ss_state & FIO_SS_ATTAINED) || !(ts->ss_state & FIO_SS_BUFFER_FULL))
1734                         j = ts->ss_head;
1735                 else
1736                         j = ts->ss_head == 0 ? ts->ss_dur - 1 : ts->ss_head - 1;
1737                 for (l = 0; l < ts->ss_dur; l++) {
1738                         k = (j + l) % ts->ss_dur;
1739                         json_array_add_value_int(bw, ts->ss_bw_data[k]);
1740                         json_array_add_value_int(iops, ts->ss_iops_data[k]);
1741                 }
1742                 json_object_add_value_int(data, "bw_mean", steadystate_bw_mean(ts));
1743                 json_object_add_value_int(data, "iops_mean", steadystate_iops_mean(ts));
1744                 json_object_add_value_array(data, "iops", iops);
1745                 json_object_add_value_array(data, "bw", bw);
1746         }
1747
1748         return root;
1749 }
1750
1751 static void show_thread_status_terse(struct thread_stat *ts,
1752                                      struct group_run_stats *rs,
1753                                      struct buf_output *out)
1754 {
1755         if (terse_version >= 2 && terse_version <= 5)
1756                 show_thread_status_terse_all(ts, rs, terse_version, out);
1757         else
1758                 log_err("fio: bad terse version!? %d\n", terse_version);
1759 }
1760
1761 struct json_object *show_thread_status(struct thread_stat *ts,
1762                                        struct group_run_stats *rs,
1763                                        struct flist_head *opt_list,
1764                                        struct buf_output *out)
1765 {
1766         struct json_object *ret = NULL;
1767
1768         if (output_format & FIO_OUTPUT_TERSE)
1769                 show_thread_status_terse(ts, rs,  out);
1770         if (output_format & FIO_OUTPUT_JSON)
1771                 ret = show_thread_status_json(ts, rs, opt_list);
1772         if (output_format & FIO_OUTPUT_NORMAL)
1773                 show_thread_status_normal(ts, rs,  out);
1774
1775         return ret;
1776 }
1777
1778 static void __sum_stat(struct io_stat *dst, struct io_stat *src, bool first)
1779 {
1780         double mean, S;
1781
1782         dst->min_val = min(dst->min_val, src->min_val);
1783         dst->max_val = max(dst->max_val, src->max_val);
1784
1785         /*
1786          * Compute new mean and S after the merge
1787          * <http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
1788          *  #Parallel_algorithm>
1789          */
1790         if (first) {
1791                 mean = src->mean.u.f;
1792                 S = src->S.u.f;
1793         } else {
1794                 double delta = src->mean.u.f - dst->mean.u.f;
1795
1796                 mean = ((src->mean.u.f * src->samples) +
1797                         (dst->mean.u.f * dst->samples)) /
1798                         (dst->samples + src->samples);
1799
1800                 S =  src->S.u.f + dst->S.u.f + pow(delta, 2.0) *
1801                         (dst->samples * src->samples) /
1802                         (dst->samples + src->samples);
1803         }
1804
1805         dst->samples += src->samples;
1806         dst->mean.u.f = mean;
1807         dst->S.u.f = S;
1808
1809 }
1810
1811 /*
1812  * We sum two kinds of stats - one that is time based, in which case we
1813  * apply the proper summing technique, and then one that is iops/bw
1814  * numbers. For group_reporting, we should just add those up, not make
1815  * them the mean of everything.
1816  */
1817 static void sum_stat(struct io_stat *dst, struct io_stat *src, bool first,
1818                      bool pure_sum)
1819 {
1820         if (src->samples == 0)
1821                 return;
1822
1823         if (!pure_sum) {
1824                 __sum_stat(dst, src, first);
1825                 return;
1826         }
1827
1828         if (first) {
1829                 dst->min_val = src->min_val;
1830                 dst->max_val = src->max_val;
1831                 dst->samples = src->samples;
1832                 dst->mean.u.f = src->mean.u.f;
1833                 dst->S.u.f = src->S.u.f;
1834         } else {
1835                 dst->min_val += src->min_val;
1836                 dst->max_val += src->max_val;
1837                 dst->samples += src->samples;
1838                 dst->mean.u.f += src->mean.u.f;
1839                 dst->S.u.f += src->S.u.f;
1840         }
1841 }
1842
1843 void sum_group_stats(struct group_run_stats *dst, struct group_run_stats *src)
1844 {
1845         int i;
1846
1847         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1848                 if (dst->max_run[i] < src->max_run[i])
1849                         dst->max_run[i] = src->max_run[i];
1850                 if (dst->min_run[i] && dst->min_run[i] > src->min_run[i])
1851                         dst->min_run[i] = src->min_run[i];
1852                 if (dst->max_bw[i] < src->max_bw[i])
1853                         dst->max_bw[i] = src->max_bw[i];
1854                 if (dst->min_bw[i] && dst->min_bw[i] > src->min_bw[i])
1855                         dst->min_bw[i] = src->min_bw[i];
1856
1857                 dst->iobytes[i] += src->iobytes[i];
1858                 dst->agg[i] += src->agg[i];
1859         }
1860
1861         if (!dst->kb_base)
1862                 dst->kb_base = src->kb_base;
1863         if (!dst->unit_base)
1864                 dst->unit_base = src->unit_base;
1865         if (!dst->sig_figs)
1866                 dst->sig_figs = src->sig_figs;
1867 }
1868
1869 void sum_thread_stats(struct thread_stat *dst, struct thread_stat *src,
1870                       bool first)
1871 {
1872         int k, l, m;
1873
1874         for (l = 0; l < DDIR_RWDIR_CNT; l++) {
1875                 if (!dst->unified_rw_rep) {
1876                         sum_stat(&dst->clat_stat[l], &src->clat_stat[l], first, false);
1877                         sum_stat(&dst->clat_high_prio_stat[l], &src->clat_high_prio_stat[l], first, false);
1878                         sum_stat(&dst->clat_prio_stat[l], &src->clat_prio_stat[l], first, false);
1879                         sum_stat(&dst->slat_stat[l], &src->slat_stat[l], first, false);
1880                         sum_stat(&dst->lat_stat[l], &src->lat_stat[l], first, false);
1881                         sum_stat(&dst->bw_stat[l], &src->bw_stat[l], first, true);
1882                         sum_stat(&dst->iops_stat[l], &src->iops_stat[l], first, true);
1883
1884                         dst->io_bytes[l] += src->io_bytes[l];
1885
1886                         if (dst->runtime[l] < src->runtime[l])
1887                                 dst->runtime[l] = src->runtime[l];
1888                 } else {
1889                         sum_stat(&dst->clat_stat[0], &src->clat_stat[l], first, false);
1890                         sum_stat(&dst->clat_high_prio_stat[l], &src->clat_high_prio_stat[l], first, false);
1891                         sum_stat(&dst->clat_prio_stat[l], &src->clat_prio_stat[l], first, false);
1892                         sum_stat(&dst->slat_stat[0], &src->slat_stat[l], first, false);
1893                         sum_stat(&dst->lat_stat[0], &src->lat_stat[l], first, false);
1894                         sum_stat(&dst->bw_stat[0], &src->bw_stat[l], first, true);
1895                         sum_stat(&dst->iops_stat[0], &src->iops_stat[l], first, true);
1896
1897                         dst->io_bytes[0] += src->io_bytes[l];
1898
1899                         if (dst->runtime[0] < src->runtime[l])
1900                                 dst->runtime[0] = src->runtime[l];
1901
1902                         /*
1903                          * We're summing to the same destination, so override
1904                          * 'first' after the first iteration of the loop
1905                          */
1906                         first = false;
1907                 }
1908         }
1909
1910         sum_stat(&dst->sync_stat, &src->sync_stat, first, false);
1911         dst->usr_time += src->usr_time;
1912         dst->sys_time += src->sys_time;
1913         dst->ctx += src->ctx;
1914         dst->majf += src->majf;
1915         dst->minf += src->minf;
1916
1917         for (k = 0; k < FIO_IO_U_MAP_NR; k++) {
1918                 dst->io_u_map[k] += src->io_u_map[k];
1919                 dst->io_u_submit[k] += src->io_u_submit[k];
1920                 dst->io_u_complete[k] += src->io_u_complete[k];
1921         }
1922
1923         for (k = 0; k < FIO_IO_U_LAT_N_NR; k++)
1924                 dst->io_u_lat_n[k] += src->io_u_lat_n[k];
1925         for (k = 0; k < FIO_IO_U_LAT_U_NR; k++)
1926                 dst->io_u_lat_u[k] += src->io_u_lat_u[k];
1927         for (k = 0; k < FIO_IO_U_LAT_M_NR; k++)
1928                 dst->io_u_lat_m[k] += src->io_u_lat_m[k];
1929
1930         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1931                 if (!dst->unified_rw_rep) {
1932                         dst->total_io_u[k] += src->total_io_u[k];
1933                         dst->short_io_u[k] += src->short_io_u[k];
1934                         dst->drop_io_u[k] += src->drop_io_u[k];
1935                 } else {
1936                         dst->total_io_u[0] += src->total_io_u[k];
1937                         dst->short_io_u[0] += src->short_io_u[k];
1938                         dst->drop_io_u[0] += src->drop_io_u[k];
1939                 }
1940         }
1941
1942         dst->total_io_u[DDIR_SYNC] += src->total_io_u[DDIR_SYNC];
1943
1944         for (k = 0; k < FIO_LAT_CNT; k++)
1945                 for (l = 0; l < DDIR_RWDIR_CNT; l++)
1946                         for (m = 0; m < FIO_IO_U_PLAT_NR; m++)
1947                                 if (!dst->unified_rw_rep)
1948                                         dst->io_u_plat[k][l][m] += src->io_u_plat[k][l][m];
1949                                 else
1950                                         dst->io_u_plat[k][0][m] += src->io_u_plat[k][l][m];
1951
1952         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
1953                 dst->io_u_sync_plat[k] += src->io_u_sync_plat[k];
1954
1955         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1956                 for (m = 0; m < FIO_IO_U_PLAT_NR; m++) {
1957                         if (!dst->unified_rw_rep) {
1958                                 dst->io_u_plat_high_prio[k][m] += src->io_u_plat_high_prio[k][m];
1959                                 dst->io_u_plat_prio[k][m] += src->io_u_plat_prio[k][m];
1960                         } else {
1961                                 dst->io_u_plat_high_prio[0][m] += src->io_u_plat_high_prio[k][m];
1962                                 dst->io_u_plat_prio[0][m] += src->io_u_plat_prio[k][m];
1963                         }
1964
1965                 }
1966         }
1967
1968         dst->total_run_time += src->total_run_time;
1969         dst->total_submit += src->total_submit;
1970         dst->total_complete += src->total_complete;
1971         dst->nr_zone_resets += src->nr_zone_resets;
1972         dst->cachehit += src->cachehit;
1973         dst->cachemiss += src->cachemiss;
1974 }
1975
1976 void init_group_run_stat(struct group_run_stats *gs)
1977 {
1978         int i;
1979         memset(gs, 0, sizeof(*gs));
1980
1981         for (i = 0; i < DDIR_RWDIR_CNT; i++)
1982                 gs->min_bw[i] = gs->min_run[i] = ~0UL;
1983 }
1984
1985 void init_thread_stat(struct thread_stat *ts)
1986 {
1987         int j;
1988
1989         memset(ts, 0, sizeof(*ts));
1990
1991         for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1992                 ts->lat_stat[j].min_val = -1UL;
1993                 ts->clat_stat[j].min_val = -1UL;
1994                 ts->slat_stat[j].min_val = -1UL;
1995                 ts->bw_stat[j].min_val = -1UL;
1996                 ts->iops_stat[j].min_val = -1UL;
1997                 ts->clat_high_prio_stat[j].min_val = -1UL;
1998                 ts->clat_prio_stat[j].min_val = -1UL;
1999         }
2000         ts->sync_stat.min_val = -1UL;
2001         ts->groupid = -1;
2002 }
2003
2004 void __show_run_stats(void)
2005 {
2006         struct group_run_stats *runstats, *rs;
2007         struct thread_data *td;
2008         struct thread_stat *threadstats, *ts;
2009         int i, j, k, nr_ts, last_ts, idx;
2010         bool kb_base_warned = false;
2011         bool unit_base_warned = false;
2012         struct json_object *root = NULL;
2013         struct json_array *array = NULL;
2014         struct buf_output output[FIO_OUTPUT_NR];
2015         struct flist_head **opt_lists;
2016
2017         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
2018
2019         for (i = 0; i < groupid + 1; i++)
2020                 init_group_run_stat(&runstats[i]);
2021
2022         /*
2023          * find out how many threads stats we need. if group reporting isn't
2024          * enabled, it's one-per-td.
2025          */
2026         nr_ts = 0;
2027         last_ts = -1;
2028         for_each_td(td, i) {
2029                 if (!td->o.group_reporting) {
2030                         nr_ts++;
2031                         continue;
2032                 }
2033                 if (last_ts == td->groupid)
2034                         continue;
2035                 if (!td->o.stats)
2036                         continue;
2037
2038                 last_ts = td->groupid;
2039                 nr_ts++;
2040         }
2041
2042         threadstats = malloc(nr_ts * sizeof(struct thread_stat));
2043         opt_lists = malloc(nr_ts * sizeof(struct flist_head *));
2044
2045         for (i = 0; i < nr_ts; i++) {
2046                 init_thread_stat(&threadstats[i]);
2047                 opt_lists[i] = NULL;
2048         }
2049
2050         j = 0;
2051         last_ts = -1;
2052         idx = 0;
2053         for_each_td(td, i) {
2054                 if (!td->o.stats)
2055                         continue;
2056                 if (idx && (!td->o.group_reporting ||
2057                     (td->o.group_reporting && last_ts != td->groupid))) {
2058                         idx = 0;
2059                         j++;
2060                 }
2061
2062                 last_ts = td->groupid;
2063
2064                 ts = &threadstats[j];
2065
2066                 ts->clat_percentiles = td->o.clat_percentiles;
2067                 ts->lat_percentiles = td->o.lat_percentiles;
2068                 ts->slat_percentiles = td->o.slat_percentiles;
2069                 ts->percentile_precision = td->o.percentile_precision;
2070                 memcpy(ts->percentile_list, td->o.percentile_list, sizeof(td->o.percentile_list));
2071                 opt_lists[j] = &td->opt_list;
2072
2073                 idx++;
2074                 ts->members++;
2075
2076                 if (ts->groupid == -1) {
2077                         /*
2078                          * These are per-group shared already
2079                          */
2080                         snprintf(ts->name, sizeof(ts->name), "%s", td->o.name);
2081                         if (td->o.description)
2082                                 snprintf(ts->description,
2083                                          sizeof(ts->description), "%s",
2084                                          td->o.description);
2085                         else
2086                                 memset(ts->description, 0, FIO_JOBDESC_SIZE);
2087
2088                         /*
2089                          * If multiple entries in this group, this is
2090                          * the first member.
2091                          */
2092                         ts->thread_number = td->thread_number;
2093                         ts->groupid = td->groupid;
2094
2095                         /*
2096                          * first pid in group, not very useful...
2097                          */
2098                         ts->pid = td->pid;
2099
2100                         ts->kb_base = td->o.kb_base;
2101                         ts->unit_base = td->o.unit_base;
2102                         ts->sig_figs = td->o.sig_figs;
2103                         ts->unified_rw_rep = td->o.unified_rw_rep;
2104                 } else if (ts->kb_base != td->o.kb_base && !kb_base_warned) {
2105                         log_info("fio: kb_base differs for jobs in group, using"
2106                                  " %u as the base\n", ts->kb_base);
2107                         kb_base_warned = true;
2108                 } else if (ts->unit_base != td->o.unit_base && !unit_base_warned) {
2109                         log_info("fio: unit_base differs for jobs in group, using"
2110                                  " %u as the base\n", ts->unit_base);
2111                         unit_base_warned = true;
2112                 }
2113
2114                 ts->continue_on_error = td->o.continue_on_error;
2115                 ts->total_err_count += td->total_err_count;
2116                 ts->first_error = td->first_error;
2117                 if (!ts->error) {
2118                         if (!td->error && td->o.continue_on_error &&
2119                             td->first_error) {
2120                                 ts->error = td->first_error;
2121                                 snprintf(ts->verror, sizeof(ts->verror), "%s",
2122                                          td->verror);
2123                         } else  if (td->error) {
2124                                 ts->error = td->error;
2125                                 snprintf(ts->verror, sizeof(ts->verror), "%s",
2126                                          td->verror);
2127                         }
2128                 }
2129
2130                 ts->latency_depth = td->latency_qd;
2131                 ts->latency_target = td->o.latency_target;
2132                 ts->latency_percentile = td->o.latency_percentile;
2133                 ts->latency_window = td->o.latency_window;
2134
2135                 ts->nr_block_infos = td->ts.nr_block_infos;
2136                 for (k = 0; k < ts->nr_block_infos; k++)
2137                         ts->block_infos[k] = td->ts.block_infos[k];
2138
2139                 sum_thread_stats(ts, &td->ts, idx == 1);
2140
2141                 if (td->o.ss_dur) {
2142                         ts->ss_state = td->ss.state;
2143                         ts->ss_dur = td->ss.dur;
2144                         ts->ss_head = td->ss.head;
2145                         ts->ss_bw_data = td->ss.bw_data;
2146                         ts->ss_iops_data = td->ss.iops_data;
2147                         ts->ss_limit.u.f = td->ss.limit;
2148                         ts->ss_slope.u.f = td->ss.slope;
2149                         ts->ss_deviation.u.f = td->ss.deviation;
2150                         ts->ss_criterion.u.f = td->ss.criterion;
2151                 }
2152                 else
2153                         ts->ss_dur = ts->ss_state = 0;
2154         }
2155
2156         for (i = 0; i < nr_ts; i++) {
2157                 unsigned long long bw;
2158
2159                 ts = &threadstats[i];
2160                 if (ts->groupid == -1)
2161                         continue;
2162                 rs = &runstats[ts->groupid];
2163                 rs->kb_base = ts->kb_base;
2164                 rs->unit_base = ts->unit_base;
2165                 rs->sig_figs = ts->sig_figs;
2166                 rs->unified_rw_rep += ts->unified_rw_rep;
2167
2168                 for (j = 0; j < DDIR_RWDIR_CNT; j++) {
2169                         if (!ts->runtime[j])
2170                                 continue;
2171                         if (ts->runtime[j] < rs->min_run[j] || !rs->min_run[j])
2172                                 rs->min_run[j] = ts->runtime[j];
2173                         if (ts->runtime[j] > rs->max_run[j])
2174                                 rs->max_run[j] = ts->runtime[j];
2175
2176                         bw = 0;
2177                         if (ts->runtime[j])
2178                                 bw = ts->io_bytes[j] * 1000 / ts->runtime[j];
2179                         if (bw < rs->min_bw[j])
2180                                 rs->min_bw[j] = bw;
2181                         if (bw > rs->max_bw[j])
2182                                 rs->max_bw[j] = bw;
2183
2184                         rs->iobytes[j] += ts->io_bytes[j];
2185                 }
2186         }
2187
2188         for (i = 0; i < groupid + 1; i++) {
2189                 int ddir;
2190
2191                 rs = &runstats[i];
2192
2193                 for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
2194                         if (rs->max_run[ddir])
2195                                 rs->agg[ddir] = (rs->iobytes[ddir] * 1000) /
2196                                                 rs->max_run[ddir];
2197                 }
2198         }
2199
2200         for (i = 0; i < FIO_OUTPUT_NR; i++)
2201                 buf_output_init(&output[i]);
2202
2203         /*
2204          * don't overwrite last signal output
2205          */
2206         if (output_format & FIO_OUTPUT_NORMAL)
2207                 log_buf(&output[__FIO_OUTPUT_NORMAL], "\n");
2208         if (output_format & FIO_OUTPUT_JSON) {
2209                 struct thread_data *global;
2210                 char time_buf[32];
2211                 struct timeval now;
2212                 unsigned long long ms_since_epoch;
2213                 time_t tv_sec;
2214
2215                 gettimeofday(&now, NULL);
2216                 ms_since_epoch = (unsigned long long)(now.tv_sec) * 1000 +
2217                                  (unsigned long long)(now.tv_usec) / 1000;
2218
2219                 tv_sec = now.tv_sec;
2220                 os_ctime_r(&tv_sec, time_buf, sizeof(time_buf));
2221                 if (time_buf[strlen(time_buf) - 1] == '\n')
2222                         time_buf[strlen(time_buf) - 1] = '\0';
2223
2224                 root = json_create_object();
2225                 json_object_add_value_string(root, "fio version", fio_version_string);
2226                 json_object_add_value_int(root, "timestamp", now.tv_sec);
2227                 json_object_add_value_int(root, "timestamp_ms", ms_since_epoch);
2228                 json_object_add_value_string(root, "time", time_buf);
2229                 global = get_global_options();
2230                 json_add_job_opts(root, "global options", &global->opt_list);
2231                 array = json_create_array();
2232                 json_object_add_value_array(root, "jobs", array);
2233         }
2234
2235         if (is_backend)
2236                 fio_server_send_job_options(&get_global_options()->opt_list, -1U);
2237
2238         for (i = 0; i < nr_ts; i++) {
2239                 ts = &threadstats[i];
2240                 rs = &runstats[ts->groupid];
2241
2242                 if (is_backend) {
2243                         fio_server_send_job_options(opt_lists[i], i);
2244                         fio_server_send_ts(ts, rs);
2245                 } else {
2246                         if (output_format & FIO_OUTPUT_TERSE)
2247                                 show_thread_status_terse(ts, rs, &output[__FIO_OUTPUT_TERSE]);
2248                         if (output_format & FIO_OUTPUT_JSON) {
2249                                 struct json_object *tmp = show_thread_status_json(ts, rs, opt_lists[i]);
2250                                 json_array_add_value_object(array, tmp);
2251                         }
2252                         if (output_format & FIO_OUTPUT_NORMAL)
2253                                 show_thread_status_normal(ts, rs, &output[__FIO_OUTPUT_NORMAL]);
2254                 }
2255         }
2256         if (!is_backend && (output_format & FIO_OUTPUT_JSON)) {
2257                 /* disk util stats, if any */
2258                 show_disk_util(1, root, &output[__FIO_OUTPUT_JSON]);
2259
2260                 show_idle_prof_stats(FIO_OUTPUT_JSON, root, &output[__FIO_OUTPUT_JSON]);
2261
2262                 json_print_object(root, &output[__FIO_OUTPUT_JSON]);
2263                 log_buf(&output[__FIO_OUTPUT_JSON], "\n");
2264                 json_free_object(root);
2265         }
2266
2267         for (i = 0; i < groupid + 1; i++) {
2268                 rs = &runstats[i];
2269
2270                 rs->groupid = i;
2271                 if (is_backend)
2272                         fio_server_send_gs(rs);
2273                 else if (output_format & FIO_OUTPUT_NORMAL)
2274                         show_group_stats(rs, &output[__FIO_OUTPUT_NORMAL]);
2275         }
2276
2277         if (is_backend)
2278                 fio_server_send_du();
2279         else if (output_format & FIO_OUTPUT_NORMAL) {
2280                 show_disk_util(0, NULL, &output[__FIO_OUTPUT_NORMAL]);
2281                 show_idle_prof_stats(FIO_OUTPUT_NORMAL, NULL, &output[__FIO_OUTPUT_NORMAL]);
2282         }
2283
2284         for (i = 0; i < FIO_OUTPUT_NR; i++) {
2285                 struct buf_output *out = &output[i];
2286
2287                 log_info_buf(out->buf, out->buflen);
2288                 buf_output_free(out);
2289         }
2290
2291         fio_idle_prof_cleanup();
2292
2293         log_info_flush();
2294         free(runstats);
2295         free(threadstats);
2296         free(opt_lists);
2297 }
2298
2299 void __show_running_run_stats(void)
2300 {
2301         struct thread_data *td;
2302         unsigned long long *rt;
2303         struct timespec ts;
2304         int i;
2305
2306         fio_sem_down(stat_sem);
2307
2308         rt = malloc(thread_number * sizeof(unsigned long long));
2309         fio_gettime(&ts, NULL);
2310
2311         for_each_td(td, i) {
2312                 td->update_rusage = 1;
2313                 td->ts.io_bytes[DDIR_READ] = td->io_bytes[DDIR_READ];
2314                 td->ts.io_bytes[DDIR_WRITE] = td->io_bytes[DDIR_WRITE];
2315                 td->ts.io_bytes[DDIR_TRIM] = td->io_bytes[DDIR_TRIM];
2316                 td->ts.total_run_time = mtime_since(&td->epoch, &ts);
2317
2318                 rt[i] = mtime_since(&td->start, &ts);
2319                 if (td_read(td) && td->ts.io_bytes[DDIR_READ])
2320                         td->ts.runtime[DDIR_READ] += rt[i];
2321                 if (td_write(td) && td->ts.io_bytes[DDIR_WRITE])
2322                         td->ts.runtime[DDIR_WRITE] += rt[i];
2323                 if (td_trim(td) && td->ts.io_bytes[DDIR_TRIM])
2324                         td->ts.runtime[DDIR_TRIM] += rt[i];
2325         }
2326
2327         for_each_td(td, i) {
2328                 if (td->runstate >= TD_EXITED)
2329                         continue;
2330                 if (td->rusage_sem) {
2331                         td->update_rusage = 1;
2332                         fio_sem_down(td->rusage_sem);
2333                 }
2334                 td->update_rusage = 0;
2335         }
2336
2337         __show_run_stats();
2338
2339         for_each_td(td, i) {
2340                 if (td_read(td) && td->ts.io_bytes[DDIR_READ])
2341                         td->ts.runtime[DDIR_READ] -= rt[i];
2342                 if (td_write(td) && td->ts.io_bytes[DDIR_WRITE])
2343                         td->ts.runtime[DDIR_WRITE] -= rt[i];
2344                 if (td_trim(td) && td->ts.io_bytes[DDIR_TRIM])
2345                         td->ts.runtime[DDIR_TRIM] -= rt[i];
2346         }
2347
2348         free(rt);
2349         fio_sem_up(stat_sem);
2350 }
2351
2352 static bool status_interval_init;
2353 static struct timespec status_time;
2354 static bool status_file_disabled;
2355
2356 #define FIO_STATUS_FILE         "fio-dump-status"
2357
2358 static int check_status_file(void)
2359 {
2360         struct stat sb;
2361         const char *temp_dir;
2362         char fio_status_file_path[PATH_MAX];
2363
2364         if (status_file_disabled)
2365                 return 0;
2366
2367         temp_dir = getenv("TMPDIR");
2368         if (temp_dir == NULL) {
2369                 temp_dir = getenv("TEMP");
2370                 if (temp_dir && strlen(temp_dir) >= PATH_MAX)
2371                         temp_dir = NULL;
2372         }
2373         if (temp_dir == NULL)
2374                 temp_dir = "/tmp";
2375 #ifdef __COVERITY__
2376         __coverity_tainted_data_sanitize__(temp_dir);
2377 #endif
2378
2379         snprintf(fio_status_file_path, sizeof(fio_status_file_path), "%s/%s", temp_dir, FIO_STATUS_FILE);
2380
2381         if (stat(fio_status_file_path, &sb))
2382                 return 0;
2383
2384         if (unlink(fio_status_file_path) < 0) {
2385                 log_err("fio: failed to unlink %s: %s\n", fio_status_file_path,
2386                                                         strerror(errno));
2387                 log_err("fio: disabling status file updates\n");
2388                 status_file_disabled = true;
2389         }
2390
2391         return 1;
2392 }
2393
2394 void check_for_running_stats(void)
2395 {
2396         if (status_interval) {
2397                 if (!status_interval_init) {
2398                         fio_gettime(&status_time, NULL);
2399                         status_interval_init = true;
2400                 } else if (mtime_since_now(&status_time) >= status_interval) {
2401                         show_running_run_stats();
2402                         fio_gettime(&status_time, NULL);
2403                         return;
2404                 }
2405         }
2406         if (check_status_file()) {
2407                 show_running_run_stats();
2408                 return;
2409         }
2410 }
2411
2412 static inline void add_stat_sample(struct io_stat *is, unsigned long long data)
2413 {
2414         double val = data;
2415         double delta;
2416
2417         if (data > is->max_val)
2418                 is->max_val = data;
2419         if (data < is->min_val)
2420                 is->min_val = data;
2421
2422         delta = val - is->mean.u.f;
2423         if (delta) {
2424                 is->mean.u.f += delta / (is->samples + 1.0);
2425                 is->S.u.f += delta * (val - is->mean.u.f);
2426         }
2427
2428         is->samples++;
2429 }
2430
2431 /*
2432  * Return a struct io_logs, which is added to the tail of the log
2433  * list for 'iolog'.
2434  */
2435 static struct io_logs *get_new_log(struct io_log *iolog)
2436 {
2437         size_t new_size, new_samples;
2438         struct io_logs *cur_log;
2439
2440         /*
2441          * Cap the size at MAX_LOG_ENTRIES, so we don't keep doubling
2442          * forever
2443          */
2444         if (!iolog->cur_log_max)
2445                 new_samples = DEF_LOG_ENTRIES;
2446         else {
2447                 new_samples = iolog->cur_log_max * 2;
2448                 if (new_samples > MAX_LOG_ENTRIES)
2449                         new_samples = MAX_LOG_ENTRIES;
2450         }
2451
2452         new_size = new_samples * log_entry_sz(iolog);
2453
2454         cur_log = smalloc(sizeof(*cur_log));
2455         if (cur_log) {
2456                 INIT_FLIST_HEAD(&cur_log->list);
2457                 cur_log->log = malloc(new_size);
2458                 if (cur_log->log) {
2459                         cur_log->nr_samples = 0;
2460                         cur_log->max_samples = new_samples;
2461                         flist_add_tail(&cur_log->list, &iolog->io_logs);
2462                         iolog->cur_log_max = new_samples;
2463                         return cur_log;
2464                 }
2465                 sfree(cur_log);
2466         }
2467
2468         return NULL;
2469 }
2470
2471 /*
2472  * Add and return a new log chunk, or return current log if big enough
2473  */
2474 static struct io_logs *regrow_log(struct io_log *iolog)
2475 {
2476         struct io_logs *cur_log;
2477         int i;
2478
2479         if (!iolog || iolog->disabled)
2480                 goto disable;
2481
2482         cur_log = iolog_cur_log(iolog);
2483         if (!cur_log) {
2484                 cur_log = get_new_log(iolog);
2485                 if (!cur_log)
2486                         return NULL;
2487         }
2488
2489         if (cur_log->nr_samples < cur_log->max_samples)
2490                 return cur_log;
2491
2492         /*
2493          * No room for a new sample. If we're compressing on the fly, flush
2494          * out the current chunk
2495          */
2496         if (iolog->log_gz) {
2497                 if (iolog_cur_flush(iolog, cur_log)) {
2498                         log_err("fio: failed flushing iolog! Will stop logging.\n");
2499                         return NULL;
2500                 }
2501         }
2502
2503         /*
2504          * Get a new log array, and add to our list
2505          */
2506         cur_log = get_new_log(iolog);
2507         if (!cur_log) {
2508                 log_err("fio: failed extending iolog! Will stop logging.\n");
2509                 return NULL;
2510         }
2511
2512         if (!iolog->pending || !iolog->pending->nr_samples)
2513                 return cur_log;
2514
2515         /*
2516          * Flush pending items to new log
2517          */
2518         for (i = 0; i < iolog->pending->nr_samples; i++) {
2519                 struct io_sample *src, *dst;
2520
2521                 src = get_sample(iolog, iolog->pending, i);
2522                 dst = get_sample(iolog, cur_log, i);
2523                 memcpy(dst, src, log_entry_sz(iolog));
2524         }
2525         cur_log->nr_samples = iolog->pending->nr_samples;
2526
2527         iolog->pending->nr_samples = 0;
2528         return cur_log;
2529 disable:
2530         if (iolog)
2531                 iolog->disabled = true;
2532         return NULL;
2533 }
2534
2535 void regrow_logs(struct thread_data *td)
2536 {
2537         regrow_log(td->slat_log);
2538         regrow_log(td->clat_log);
2539         regrow_log(td->clat_hist_log);
2540         regrow_log(td->lat_log);
2541         regrow_log(td->bw_log);
2542         regrow_log(td->iops_log);
2543         td->flags &= ~TD_F_REGROW_LOGS;
2544 }
2545
2546 static struct io_logs *get_cur_log(struct io_log *iolog)
2547 {
2548         struct io_logs *cur_log;
2549
2550         cur_log = iolog_cur_log(iolog);
2551         if (!cur_log) {
2552                 cur_log = get_new_log(iolog);
2553                 if (!cur_log)
2554                         return NULL;
2555         }
2556
2557         if (cur_log->nr_samples < cur_log->max_samples)
2558                 return cur_log;
2559
2560         /*
2561          * Out of space. If we're in IO offload mode, or we're not doing
2562          * per unit logging (hence logging happens outside of the IO thread
2563          * as well), add a new log chunk inline. If we're doing inline
2564          * submissions, flag 'td' as needing a log regrow and we'll take
2565          * care of it on the submission side.
2566          */
2567         if ((iolog->td && iolog->td->o.io_submit_mode == IO_MODE_OFFLOAD) ||
2568             !per_unit_log(iolog))
2569                 return regrow_log(iolog);
2570
2571         if (iolog->td)
2572                 iolog->td->flags |= TD_F_REGROW_LOGS;
2573         if (iolog->pending)
2574                 assert(iolog->pending->nr_samples < iolog->pending->max_samples);
2575         return iolog->pending;
2576 }
2577
2578 static void __add_log_sample(struct io_log *iolog, union io_sample_data data,
2579                              enum fio_ddir ddir, unsigned long long bs,
2580                              unsigned long t, uint64_t offset, uint8_t priority_bit)
2581 {
2582         struct io_logs *cur_log;
2583
2584         if (iolog->disabled)
2585                 return;
2586         if (flist_empty(&iolog->io_logs))
2587                 iolog->avg_last[ddir] = t;
2588
2589         cur_log = get_cur_log(iolog);
2590         if (cur_log) {
2591                 struct io_sample *s;
2592
2593                 s = get_sample(iolog, cur_log, cur_log->nr_samples);
2594
2595                 s->data = data;
2596                 s->time = t + (iolog->td ? iolog->td->unix_epoch : 0);
2597                 io_sample_set_ddir(iolog, s, ddir);
2598                 s->bs = bs;
2599                 s->priority_bit = priority_bit;
2600
2601                 if (iolog->log_offset) {
2602                         struct io_sample_offset *so = (void *) s;
2603
2604                         so->offset = offset;
2605                 }
2606
2607                 cur_log->nr_samples++;
2608                 return;
2609         }
2610
2611         iolog->disabled = true;
2612 }
2613
2614 static inline void reset_io_stat(struct io_stat *ios)
2615 {
2616         ios->min_val = -1ULL;
2617         ios->max_val = ios->samples = 0;
2618         ios->mean.u.f = ios->S.u.f = 0;
2619 }
2620
2621 void reset_io_stats(struct thread_data *td)
2622 {
2623         struct thread_stat *ts = &td->ts;
2624         int i, j, k;
2625
2626         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
2627                 reset_io_stat(&ts->clat_high_prio_stat[i]);
2628                 reset_io_stat(&ts->clat_prio_stat[i]);
2629                 reset_io_stat(&ts->clat_stat[i]);
2630                 reset_io_stat(&ts->slat_stat[i]);
2631                 reset_io_stat(&ts->lat_stat[i]);
2632                 reset_io_stat(&ts->bw_stat[i]);
2633                 reset_io_stat(&ts->iops_stat[i]);
2634
2635                 ts->io_bytes[i] = 0;
2636                 ts->runtime[i] = 0;
2637                 ts->total_io_u[i] = 0;
2638                 ts->short_io_u[i] = 0;
2639                 ts->drop_io_u[i] = 0;
2640
2641                 for (j = 0; j < FIO_IO_U_PLAT_NR; j++) {
2642                         ts->io_u_plat_high_prio[i][j] = 0;
2643                         ts->io_u_plat_prio[i][j] = 0;
2644                         if (!i)
2645                                 ts->io_u_sync_plat[j] = 0;
2646                 }
2647         }
2648
2649         for (i = 0; i < FIO_LAT_CNT; i++)
2650                 for (j = 0; j < DDIR_RWDIR_CNT; j++)
2651                         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
2652                                 ts->io_u_plat[i][j][k] = 0;
2653
2654         ts->total_io_u[DDIR_SYNC] = 0;
2655
2656         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
2657                 ts->io_u_map[i] = 0;
2658                 ts->io_u_submit[i] = 0;
2659                 ts->io_u_complete[i] = 0;
2660         }
2661
2662         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
2663                 ts->io_u_lat_n[i] = 0;
2664         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
2665                 ts->io_u_lat_u[i] = 0;
2666         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
2667                 ts->io_u_lat_m[i] = 0;
2668
2669         ts->total_submit = 0;
2670         ts->total_complete = 0;
2671         ts->nr_zone_resets = 0;
2672         ts->cachehit = ts->cachemiss = 0;
2673 }
2674
2675 static void __add_stat_to_log(struct io_log *iolog, enum fio_ddir ddir,
2676                               unsigned long elapsed, bool log_max, uint8_t priority_bit)
2677 {
2678         /*
2679          * Note an entry in the log. Use the mean from the logged samples,
2680          * making sure to properly round up. Only write a log entry if we
2681          * had actual samples done.
2682          */
2683         if (iolog->avg_window[ddir].samples) {
2684                 union io_sample_data data;
2685
2686                 if (log_max)
2687                         data.val = iolog->avg_window[ddir].max_val;
2688                 else
2689                         data.val = iolog->avg_window[ddir].mean.u.f + 0.50;
2690
2691                 __add_log_sample(iolog, data, ddir, 0, elapsed, 0, priority_bit);
2692         }
2693
2694         reset_io_stat(&iolog->avg_window[ddir]);
2695 }
2696
2697 static void _add_stat_to_log(struct io_log *iolog, unsigned long elapsed,
2698                              bool log_max, uint8_t priority_bit)
2699 {
2700         int ddir;
2701
2702         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++)
2703                 __add_stat_to_log(iolog, ddir, elapsed, log_max, priority_bit);
2704 }
2705
2706 static unsigned long add_log_sample(struct thread_data *td,
2707                                     struct io_log *iolog,
2708                                     union io_sample_data data,
2709                                     enum fio_ddir ddir, unsigned long long bs,
2710                                     uint64_t offset, uint8_t priority_bit)
2711 {
2712         unsigned long elapsed, this_window;
2713
2714         if (!ddir_rw(ddir))
2715                 return 0;
2716
2717         elapsed = mtime_since_now(&td->epoch);
2718
2719         /*
2720          * If no time averaging, just add the log sample.
2721          */
2722         if (!iolog->avg_msec) {
2723                 __add_log_sample(iolog, data, ddir, bs, elapsed, offset, priority_bit);
2724                 return 0;
2725         }
2726
2727         /*
2728          * Add the sample. If the time period has passed, then
2729          * add that entry to the log and clear.
2730          */
2731         add_stat_sample(&iolog->avg_window[ddir], data.val);
2732
2733         /*
2734          * If period hasn't passed, adding the above sample is all we
2735          * need to do.
2736          */
2737         this_window = elapsed - iolog->avg_last[ddir];
2738         if (elapsed < iolog->avg_last[ddir])
2739                 return iolog->avg_last[ddir] - elapsed;
2740         else if (this_window < iolog->avg_msec) {
2741                 unsigned long diff = iolog->avg_msec - this_window;
2742
2743                 if (inline_log(iolog) || diff > LOG_MSEC_SLACK)
2744                         return diff;
2745         }
2746
2747         _add_stat_to_log(iolog, elapsed, td->o.log_max != 0, priority_bit);
2748
2749         iolog->avg_last[ddir] = elapsed - (this_window - iolog->avg_msec);
2750         return iolog->avg_msec;
2751 }
2752
2753 void finalize_logs(struct thread_data *td, bool unit_logs)
2754 {
2755         unsigned long elapsed;
2756
2757         elapsed = mtime_since_now(&td->epoch);
2758
2759         if (td->clat_log && unit_logs)
2760                 _add_stat_to_log(td->clat_log, elapsed, td->o.log_max != 0, 0);
2761         if (td->slat_log && unit_logs)
2762                 _add_stat_to_log(td->slat_log, elapsed, td->o.log_max != 0, 0);
2763         if (td->lat_log && unit_logs)
2764                 _add_stat_to_log(td->lat_log, elapsed, td->o.log_max != 0, 0);
2765         if (td->bw_log && (unit_logs == per_unit_log(td->bw_log)))
2766                 _add_stat_to_log(td->bw_log, elapsed, td->o.log_max != 0, 0);
2767         if (td->iops_log && (unit_logs == per_unit_log(td->iops_log)))
2768                 _add_stat_to_log(td->iops_log, elapsed, td->o.log_max != 0, 0);
2769 }
2770
2771 void add_agg_sample(union io_sample_data data, enum fio_ddir ddir, unsigned long long bs,
2772                                         uint8_t priority_bit)
2773 {
2774         struct io_log *iolog;
2775
2776         if (!ddir_rw(ddir))
2777                 return;
2778
2779         iolog = agg_io_log[ddir];
2780         __add_log_sample(iolog, data, ddir, bs, mtime_since_genesis(), 0, priority_bit);
2781 }
2782
2783 void add_sync_clat_sample(struct thread_stat *ts, unsigned long long nsec)
2784 {
2785         unsigned int idx = plat_val_to_idx(nsec);
2786         assert(idx < FIO_IO_U_PLAT_NR);
2787
2788         ts->io_u_sync_plat[idx]++;
2789         add_stat_sample(&ts->sync_stat, nsec);
2790 }
2791
2792 static void add_lat_percentile_sample_noprio(struct thread_stat *ts,
2793                                 unsigned long long nsec, enum fio_ddir ddir, enum fio_lat lat)
2794 {
2795         unsigned int idx = plat_val_to_idx(nsec);
2796         assert(idx < FIO_IO_U_PLAT_NR);
2797
2798         ts->io_u_plat[lat][ddir][idx]++;
2799 }
2800
2801 static void add_lat_percentile_sample(struct thread_stat *ts,
2802                                 unsigned long long nsec, enum fio_ddir ddir, uint8_t priority_bit,
2803                                 enum fio_lat lat)
2804 {
2805         unsigned int idx = plat_val_to_idx(nsec);
2806
2807         add_lat_percentile_sample_noprio(ts, nsec, ddir, lat);
2808
2809         if (!priority_bit)
2810                 ts->io_u_plat_prio[ddir][idx]++;
2811         else
2812                 ts->io_u_plat_high_prio[ddir][idx]++;
2813 }
2814
2815 void add_clat_sample(struct thread_data *td, enum fio_ddir ddir,
2816                      unsigned long long nsec, unsigned long long bs,
2817                      uint64_t offset, uint8_t priority_bit)
2818 {
2819         const bool needs_lock = td_async_processing(td);
2820         unsigned long elapsed, this_window;
2821         struct thread_stat *ts = &td->ts;
2822         struct io_log *iolog = td->clat_hist_log;
2823
2824         if (needs_lock)
2825                 __td_io_u_lock(td);
2826
2827         add_stat_sample(&ts->clat_stat[ddir], nsec);
2828
2829         if (priority_bit) {
2830                 add_stat_sample(&ts->clat_high_prio_stat[ddir], nsec);
2831         } else {
2832                 add_stat_sample(&ts->clat_prio_stat[ddir], nsec);
2833         }
2834
2835         if (td->clat_log)
2836                 add_log_sample(td, td->clat_log, sample_val(nsec), ddir, bs,
2837                                offset, priority_bit);
2838
2839         if (ts->clat_percentiles) {
2840                 if (ts->lat_percentiles)
2841                         add_lat_percentile_sample_noprio(ts, nsec, ddir, FIO_CLAT);
2842                 else
2843                         add_lat_percentile_sample(ts, nsec, ddir, priority_bit, FIO_CLAT);
2844         }
2845
2846         if (iolog && iolog->hist_msec) {
2847                 struct io_hist *hw = &iolog->hist_window[ddir];
2848
2849                 hw->samples++;
2850                 elapsed = mtime_since_now(&td->epoch);
2851                 if (!hw->hist_last)
2852                         hw->hist_last = elapsed;
2853                 this_window = elapsed - hw->hist_last;
2854
2855                 if (this_window >= iolog->hist_msec) {
2856                         uint64_t *io_u_plat;
2857                         struct io_u_plat_entry *dst;
2858
2859                         /*
2860                          * Make a byte-for-byte copy of the latency histogram
2861                          * stored in td->ts.io_u_plat[ddir], recording it in a
2862                          * log sample. Note that the matching call to free() is
2863                          * located in iolog.c after printing this sample to the
2864                          * log file.
2865                          */
2866                         io_u_plat = (uint64_t *) td->ts.io_u_plat[FIO_CLAT][ddir];
2867                         dst = malloc(sizeof(struct io_u_plat_entry));
2868                         memcpy(&(dst->io_u_plat), io_u_plat,
2869                                 FIO_IO_U_PLAT_NR * sizeof(uint64_t));
2870                         flist_add(&dst->list, &hw->list);
2871                         __add_log_sample(iolog, sample_plat(dst), ddir, bs,
2872                                                 elapsed, offset, priority_bit);
2873
2874                         /*
2875                          * Update the last time we recorded as being now, minus
2876                          * any drift in time we encountered before actually
2877                          * making the record.
2878                          */
2879                         hw->hist_last = elapsed - (this_window - iolog->hist_msec);
2880                         hw->samples = 0;
2881                 }
2882         }
2883
2884         if (needs_lock)
2885                 __td_io_u_unlock(td);
2886 }
2887
2888 void add_slat_sample(struct thread_data *td, enum fio_ddir ddir,
2889                         unsigned long long nsec, unsigned long long bs, uint64_t offset,
2890                         uint8_t priority_bit)
2891 {
2892         const bool needs_lock = td_async_processing(td);
2893         struct thread_stat *ts = &td->ts;
2894
2895         if (!ddir_rw(ddir))
2896                 return;
2897
2898         if (needs_lock)
2899                 __td_io_u_lock(td);
2900
2901         add_stat_sample(&ts->slat_stat[ddir], nsec);
2902
2903         if (td->slat_log)
2904                 add_log_sample(td, td->slat_log, sample_val(nsec), ddir, bs, offset,
2905                         priority_bit);
2906
2907         if (ts->slat_percentiles)
2908                 add_lat_percentile_sample_noprio(ts, nsec, ddir, FIO_SLAT);
2909
2910         if (needs_lock)
2911                 __td_io_u_unlock(td);
2912 }
2913
2914 void add_lat_sample(struct thread_data *td, enum fio_ddir ddir,
2915                     unsigned long long nsec, unsigned long long bs,
2916                     uint64_t offset, uint8_t priority_bit)
2917 {
2918         const bool needs_lock = td_async_processing(td);
2919         struct thread_stat *ts = &td->ts;
2920
2921         if (!ddir_rw(ddir))
2922                 return;
2923
2924         if (needs_lock)
2925                 __td_io_u_lock(td);
2926
2927         add_stat_sample(&ts->lat_stat[ddir], nsec);
2928
2929         if (td->lat_log)
2930                 add_log_sample(td, td->lat_log, sample_val(nsec), ddir, bs,
2931                                offset, priority_bit);
2932
2933         if (ts->lat_percentiles)
2934                 add_lat_percentile_sample(ts, nsec, ddir, priority_bit, FIO_LAT);
2935
2936         if (needs_lock)
2937                 __td_io_u_unlock(td);
2938 }
2939
2940 void add_bw_sample(struct thread_data *td, struct io_u *io_u,
2941                    unsigned int bytes, unsigned long long spent)
2942 {
2943         const bool needs_lock = td_async_processing(td);
2944         struct thread_stat *ts = &td->ts;
2945         unsigned long rate;
2946
2947         if (spent)
2948                 rate = (unsigned long) (bytes * 1000000ULL / spent);
2949         else
2950                 rate = 0;
2951
2952         if (needs_lock)
2953                 __td_io_u_lock(td);
2954
2955         add_stat_sample(&ts->bw_stat[io_u->ddir], rate);
2956
2957         if (td->bw_log)
2958                 add_log_sample(td, td->bw_log, sample_val(rate), io_u->ddir,
2959                                bytes, io_u->offset, io_u_is_prio(io_u));
2960
2961         td->stat_io_bytes[io_u->ddir] = td->this_io_bytes[io_u->ddir];
2962
2963         if (needs_lock)
2964                 __td_io_u_unlock(td);
2965 }
2966
2967 static int __add_samples(struct thread_data *td, struct timespec *parent_tv,
2968                          struct timespec *t, unsigned int avg_time,
2969                          uint64_t *this_io_bytes, uint64_t *stat_io_bytes,
2970                          struct io_stat *stat, struct io_log *log,
2971                          bool is_kb)
2972 {
2973         const bool needs_lock = td_async_processing(td);
2974         unsigned long spent, rate;
2975         enum fio_ddir ddir;
2976         unsigned long next, next_log;
2977
2978         next_log = avg_time;
2979
2980         spent = mtime_since(parent_tv, t);
2981         if (spent < avg_time && avg_time - spent >= LOG_MSEC_SLACK)
2982                 return avg_time - spent;
2983
2984         if (needs_lock)
2985                 __td_io_u_lock(td);
2986
2987         /*
2988          * Compute both read and write rates for the interval.
2989          */
2990         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
2991                 uint64_t delta;
2992
2993                 delta = this_io_bytes[ddir] - stat_io_bytes[ddir];
2994                 if (!delta)
2995                         continue; /* No entries for interval */
2996
2997                 if (spent) {
2998                         if (is_kb)
2999                                 rate = delta * 1000 / spent / 1024; /* KiB/s */
3000                         else
3001                                 rate = (delta * 1000) / spent;
3002                 } else
3003                         rate = 0;
3004
3005                 add_stat_sample(&stat[ddir], rate);
3006
3007                 if (log) {
3008                         unsigned long long bs = 0;
3009
3010                         if (td->o.min_bs[ddir] == td->o.max_bs[ddir])
3011                                 bs = td->o.min_bs[ddir];
3012
3013                         next = add_log_sample(td, log, sample_val(rate), ddir, bs, 0, 0);
3014                         next_log = min(next_log, next);
3015                 }
3016
3017                 stat_io_bytes[ddir] = this_io_bytes[ddir];
3018         }
3019
3020         *parent_tv = *t;
3021
3022         if (needs_lock)
3023                 __td_io_u_unlock(td);
3024
3025         if (spent <= avg_time)
3026                 next = avg_time;
3027         else
3028                 next = avg_time - (1 + spent - avg_time);
3029
3030         return min(next, next_log);
3031 }
3032
3033 static int add_bw_samples(struct thread_data *td, struct timespec *t)
3034 {
3035         return __add_samples(td, &td->bw_sample_time, t, td->o.bw_avg_time,
3036                                 td->this_io_bytes, td->stat_io_bytes,
3037                                 td->ts.bw_stat, td->bw_log, true);
3038 }
3039
3040 void add_iops_sample(struct thread_data *td, struct io_u *io_u,
3041                      unsigned int bytes)
3042 {
3043         const bool needs_lock = td_async_processing(td);
3044         struct thread_stat *ts = &td->ts;
3045
3046         if (needs_lock)
3047                 __td_io_u_lock(td);
3048
3049         add_stat_sample(&ts->iops_stat[io_u->ddir], 1);
3050
3051         if (td->iops_log)
3052                 add_log_sample(td, td->iops_log, sample_val(1), io_u->ddir,
3053                                bytes, io_u->offset, io_u_is_prio(io_u));
3054
3055         td->stat_io_blocks[io_u->ddir] = td->this_io_blocks[io_u->ddir];
3056
3057         if (needs_lock)
3058                 __td_io_u_unlock(td);
3059 }
3060
3061 static int add_iops_samples(struct thread_data *td, struct timespec *t)
3062 {
3063         return __add_samples(td, &td->iops_sample_time, t, td->o.iops_avg_time,
3064                                 td->this_io_blocks, td->stat_io_blocks,
3065                                 td->ts.iops_stat, td->iops_log, false);
3066 }
3067
3068 /*
3069  * Returns msecs to next event
3070  */
3071 int calc_log_samples(void)
3072 {
3073         struct thread_data *td;
3074         unsigned int next = ~0U, tmp;
3075         struct timespec now;
3076         int i;
3077
3078         fio_gettime(&now, NULL);
3079
3080         for_each_td(td, i) {
3081                 if (!td->o.stats)
3082                         continue;
3083                 if (in_ramp_time(td) ||
3084                     !(td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING)) {
3085                         next = min(td->o.iops_avg_time, td->o.bw_avg_time);
3086                         continue;
3087                 }
3088                 if (!td->bw_log ||
3089                         (td->bw_log && !per_unit_log(td->bw_log))) {
3090                         tmp = add_bw_samples(td, &now);
3091                         if (tmp < next)
3092                                 next = tmp;
3093                 }
3094                 if (!td->iops_log ||
3095                         (td->iops_log && !per_unit_log(td->iops_log))) {
3096                         tmp = add_iops_samples(td, &now);
3097                         if (tmp < next)
3098                                 next = tmp;
3099                 }
3100         }
3101
3102         return next == ~0U ? 0 : next;
3103 }
3104
3105 void stat_init(void)
3106 {
3107         stat_sem = fio_sem_init(FIO_SEM_UNLOCKED);
3108 }
3109
3110 void stat_exit(void)
3111 {
3112         /*
3113          * When we have the mutex, we know out-of-band access to it
3114          * have ended.
3115          */
3116         fio_sem_down(stat_sem);
3117         fio_sem_remove(stat_sem);
3118 }
3119
3120 /*
3121  * Called from signal handler. Wake up status thread.
3122  */
3123 void show_running_run_stats(void)
3124 {
3125         helper_do_stat();
3126 }
3127
3128 uint32_t *io_u_block_info(struct thread_data *td, struct io_u *io_u)
3129 {
3130         /* Ignore io_u's which span multiple blocks--they will just get
3131          * inaccurate counts. */
3132         int idx = (io_u->offset - io_u->file->file_offset)
3133                         / td->o.bs[DDIR_TRIM];
3134         uint32_t *info = &td->ts.block_infos[idx];
3135         assert(idx < td->ts.nr_block_infos);
3136         return info;
3137 }