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