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