e47b510f55d20f65e065d0807a20f81dd3402182
[fio.git] / stat.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/time.h>
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <dirent.h>
7 #include <libgen.h>
8 #include <math.h>
9
10 #include "fio.h"
11 #include "diskutil.h"
12 #include "lib/ieee754.h"
13 #include "json.h"
14 #include "lib/getrusage.h"
15 #include "idletime.h"
16 #include "lib/pow2.h"
17 #include "lib/output_buffer.h"
18
19 struct fio_mutex *stat_mutex;
20
21 void clear_rusage_stat(struct thread_data *td)
22 {
23         struct thread_stat *ts = &td->ts;
24
25         fio_getrusage(&td->ru_start);
26         ts->usr_time = ts->sys_time = 0;
27         ts->ctx = 0;
28         ts->minf = ts->majf = 0;
29 }
30
31 void update_rusage_stat(struct thread_data *td)
32 {
33         struct thread_stat *ts = &td->ts;
34
35         fio_getrusage(&td->ru_end);
36         ts->usr_time += mtime_since(&td->ru_start.ru_utime,
37                                         &td->ru_end.ru_utime);
38         ts->sys_time += mtime_since(&td->ru_start.ru_stime,
39                                         &td->ru_end.ru_stime);
40         ts->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw
41                         - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
42         ts->minf += td->ru_end.ru_minflt - td->ru_start.ru_minflt;
43         ts->majf += td->ru_end.ru_majflt - td->ru_start.ru_majflt;
44
45         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
46 }
47
48 /*
49  * Given a latency, return the index of the corresponding bucket in
50  * the structure tracking percentiles.
51  *
52  * (1) find the group (and error bits) that the value (latency)
53  * belongs to by looking at its MSB. (2) find the bucket number in the
54  * group by looking at the index bits.
55  *
56  */
57 static unsigned int plat_val_to_idx(unsigned int val)
58 {
59         unsigned int msb, error_bits, base, offset, idx;
60
61         /* Find MSB starting from bit 0 */
62         if (val == 0)
63                 msb = 0;
64         else
65                 msb = (sizeof(val)*8) - __builtin_clz(val) - 1;
66
67         /*
68          * MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
69          * all bits of the sample as index
70          */
71         if (msb <= FIO_IO_U_PLAT_BITS)
72                 return val;
73
74         /* Compute the number of error bits to discard*/
75         error_bits = msb - FIO_IO_U_PLAT_BITS;
76
77         /* Compute the number of buckets before the group */
78         base = (error_bits + 1) << FIO_IO_U_PLAT_BITS;
79
80         /*
81          * Discard the error bits and apply the mask to find the
82          * index for the buckets in the group
83          */
84         offset = (FIO_IO_U_PLAT_VAL - 1) & (val >> error_bits);
85
86         /* Make sure the index does not exceed (array size - 1) */
87         idx = (base + offset) < (FIO_IO_U_PLAT_NR - 1) ?
88                 (base + offset) : (FIO_IO_U_PLAT_NR - 1);
89
90         return idx;
91 }
92
93 /*
94  * Convert the given index of the bucket array to the value
95  * represented by the bucket
96  */
97 static unsigned int plat_idx_to_val(unsigned int idx)
98 {
99         unsigned int error_bits, k, base;
100
101         assert(idx < FIO_IO_U_PLAT_NR);
102
103         /* MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
104          * all bits of the sample as index */
105         if (idx < (FIO_IO_U_PLAT_VAL << 1))
106                 return idx;
107
108         /* Find the group and compute the minimum value of that group */
109         error_bits = (idx >> FIO_IO_U_PLAT_BITS) - 1;
110         base = 1 << (error_bits + FIO_IO_U_PLAT_BITS);
111
112         /* Find its bucket number of the group */
113         k = idx % FIO_IO_U_PLAT_VAL;
114
115         /* Return the mean of the range of the bucket */
116         return base + ((k + 0.5) * (1 << error_bits));
117 }
118
119 static int double_cmp(const void *a, const void *b)
120 {
121         const fio_fp64_t fa = *(const fio_fp64_t *) a;
122         const fio_fp64_t fb = *(const fio_fp64_t *) b;
123         int cmp = 0;
124
125         if (fa.u.f > fb.u.f)
126                 cmp = 1;
127         else if (fa.u.f < fb.u.f)
128                 cmp = -1;
129
130         return cmp;
131 }
132
133 unsigned int calc_clat_percentiles(unsigned int *io_u_plat, unsigned long nr,
134                                    fio_fp64_t *plist, unsigned int **output,
135                                    unsigned int *maxv, unsigned int *minv)
136 {
137         unsigned long sum = 0;
138         unsigned int len, i, j = 0;
139         unsigned int oval_len = 0;
140         unsigned int *ovals = NULL;
141         int is_last;
142
143         *minv = -1U;
144         *maxv = 0;
145
146         len = 0;
147         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
148                 len++;
149
150         if (!len)
151                 return 0;
152
153         /*
154          * Sort the percentile list. Note that it may already be sorted if
155          * we are using the default values, but since it's a short list this
156          * isn't a worry. Also note that this does not work for NaN values.
157          */
158         if (len > 1)
159                 qsort((void *)plist, len, sizeof(plist[0]), double_cmp);
160
161         /*
162          * Calculate bucket values, note down max and min values
163          */
164         is_last = 0;
165         for (i = 0; i < FIO_IO_U_PLAT_NR && !is_last; i++) {
166                 sum += io_u_plat[i];
167                 while (sum >= (plist[j].u.f / 100.0 * nr)) {
168                         assert(plist[j].u.f <= 100.0);
169
170                         if (j == oval_len) {
171                                 oval_len += 100;
172                                 ovals = realloc(ovals, oval_len * sizeof(unsigned int));
173                         }
174
175                         ovals[j] = plat_idx_to_val(i);
176                         if (ovals[j] < *minv)
177                                 *minv = ovals[j];
178                         if (ovals[j] > *maxv)
179                                 *maxv = ovals[j];
180
181                         is_last = (j == len - 1);
182                         if (is_last)
183                                 break;
184
185                         j++;
186                 }
187         }
188
189         *output = ovals;
190         return len;
191 }
192
193 /*
194  * Find and display the p-th percentile of clat
195  */
196 static void show_clat_percentiles(unsigned int *io_u_plat, unsigned long nr,
197                                   fio_fp64_t *plist, unsigned int precision,
198                                   struct buf_output *out)
199 {
200         unsigned int len, j = 0, minv, maxv;
201         unsigned int *ovals;
202         int is_last, per_line, scale_down;
203         char fmt[32];
204
205         len = calc_clat_percentiles(io_u_plat, nr, plist, &ovals, &maxv, &minv);
206         if (!len)
207                 goto out;
208
209         /*
210          * We default to usecs, but if the value range is such that we
211          * should scale down to msecs, do that.
212          */
213         if (minv > 2000 && maxv > 99999) {
214                 scale_down = 1;
215                 log_buf(out, "    clat percentiles (msec):\n     |");
216         } else {
217                 scale_down = 0;
218                 log_buf(out, "    clat percentiles (usec):\n     |");
219         }
220
221         snprintf(fmt, sizeof(fmt), "%%1.%uf", precision);
222         per_line = (80 - 7) / (precision + 14);
223
224         for (j = 0; j < len; j++) {
225                 char fbuf[16], *ptr = fbuf;
226
227                 /* for formatting */
228                 if (j != 0 && (j % per_line) == 0)
229                         log_buf(out, "     |");
230
231                 /* end of the list */
232                 is_last = (j == len - 1);
233
234                 if (plist[j].u.f < 10.0)
235                         ptr += sprintf(fbuf, " ");
236
237                 snprintf(ptr, sizeof(fbuf), fmt, plist[j].u.f);
238
239                 if (scale_down)
240                         ovals[j] = (ovals[j] + 999) / 1000;
241
242                 log_buf(out, " %sth=[%5u]%c", fbuf, ovals[j], is_last ? '\n' : ',');
243
244                 if (is_last)
245                         break;
246
247                 if ((j % per_line) == per_line - 1)     /* for formatting */
248                         log_buf(out, "\n");
249         }
250
251 out:
252         if (ovals)
253                 free(ovals);
254 }
255
256 int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
257              double *mean, double *dev)
258 {
259         double n = (double) is->samples;
260
261         if (n == 0)
262                 return 0;
263
264         *min = is->min_val;
265         *max = is->max_val;
266         *mean = is->mean.u.f;
267
268         if (n > 1.0)
269                 *dev = sqrt(is->S.u.f / (n - 1.0));
270         else
271                 *dev = 0;
272
273         return 1;
274 }
275
276 void show_group_stats(struct group_run_stats *rs, struct buf_output *out)
277 {
278         char *p1, *p2, *p3, *p4;
279         const char *str[] = { "   READ", "  WRITE" , "   TRIM"};
280         int i;
281
282         log_buf(out, "\nRun status group %d (all jobs):\n", rs->groupid);
283
284         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
285                 const int i2p = is_power_of_2(rs->kb_base);
286
287                 if (!rs->max_run[i])
288                         continue;
289
290                 p1 = num2str(rs->io_kb[i], 6, rs->kb_base, i2p, 8);
291                 p2 = num2str(rs->agg[i], 6, rs->kb_base, i2p, rs->unit_base);
292                 p3 = num2str(rs->min_bw[i], 6, rs->kb_base, i2p, rs->unit_base);
293                 p4 = num2str(rs->max_bw[i], 6, rs->kb_base, i2p, rs->unit_base);
294
295                 log_buf(out, "%s: io=%s, aggrb=%s/s, minb=%s/s, maxb=%s/s,"
296                          " mint=%llumsec, maxt=%llumsec\n",
297                                 rs->unified_rw_rep ? "  MIXED" : str[i],
298                                 p1, p2, p3, p4,
299                                 (unsigned long long) rs->min_run[i],
300                                 (unsigned long long) rs->max_run[i]);
301
302                 free(p1);
303                 free(p2);
304                 free(p3);
305                 free(p4);
306         }
307 }
308
309 void stat_calc_dist(unsigned int *map, unsigned long total, double *io_u_dist)
310 {
311         int i;
312
313         /*
314          * Do depth distribution calculations
315          */
316         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
317                 if (total) {
318                         io_u_dist[i] = (double) map[i] / (double) total;
319                         io_u_dist[i] *= 100.0;
320                         if (io_u_dist[i] < 0.1 && map[i])
321                                 io_u_dist[i] = 0.1;
322                 } else
323                         io_u_dist[i] = 0.0;
324         }
325 }
326
327 static void stat_calc_lat(struct thread_stat *ts, double *dst,
328                           unsigned int *src, int nr)
329 {
330         unsigned long total = ddir_rw_sum(ts->total_io_u);
331         int i;
332
333         /*
334          * Do latency distribution calculations
335          */
336         for (i = 0; i < nr; i++) {
337                 if (total) {
338                         dst[i] = (double) src[i] / (double) total;
339                         dst[i] *= 100.0;
340                         if (dst[i] < 0.01 && src[i])
341                                 dst[i] = 0.01;
342                 } else
343                         dst[i] = 0.0;
344         }
345 }
346
347 void stat_calc_lat_u(struct thread_stat *ts, double *io_u_lat)
348 {
349         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
350 }
351
352 void stat_calc_lat_m(struct thread_stat *ts, double *io_u_lat)
353 {
354         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_m, FIO_IO_U_LAT_M_NR);
355 }
356
357 static void display_lat(const char *name, unsigned long min, unsigned long max,
358                         double mean, double dev, struct buf_output *out)
359 {
360         const char *base = "(usec)";
361         char *minp, *maxp;
362
363         if (!usec_to_msec(&min, &max, &mean, &dev))
364                 base = "(msec)";
365
366         minp = num2str(min, 6, 1, 0, 0);
367         maxp = num2str(max, 6, 1, 0, 0);
368
369         log_buf(out, "    %s %s: min=%s, max=%s, avg=%5.02f,"
370                  " stdev=%5.02f\n", name, base, minp, maxp, mean, dev);
371
372         free(minp);
373         free(maxp);
374 }
375
376 static void show_ddir_status(struct group_run_stats *rs, struct thread_stat *ts,
377                              int ddir, struct buf_output *out)
378 {
379         const char *str[] = { "read ", "write", "trim" };
380         unsigned long min, max, runt;
381         unsigned long long bw, iops;
382         double mean, dev;
383         char *io_p, *bw_p, *iops_p;
384         int i2p;
385
386         assert(ddir_rw(ddir));
387
388         if (!ts->runtime[ddir])
389                 return;
390
391         i2p = is_power_of_2(rs->kb_base);
392         runt = ts->runtime[ddir];
393
394         bw = (1000 * ts->io_bytes[ddir]) / runt;
395         io_p = num2str(ts->io_bytes[ddir], 6, 1, i2p, 8);
396         bw_p = num2str(bw, 6, 1, i2p, ts->unit_base);
397
398         iops = (1000 * (uint64_t)ts->total_io_u[ddir]) / runt;
399         iops_p = num2str(iops, 6, 1, 0, 0);
400
401         log_buf(out, "  %s: io=%s, bw=%s/s, iops=%s, runt=%6llumsec\n",
402                                 rs->unified_rw_rep ? "mixed" : str[ddir],
403                                 io_p, bw_p, iops_p,
404                                 (unsigned long long) ts->runtime[ddir]);
405
406         free(io_p);
407         free(bw_p);
408         free(iops_p);
409
410         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
411                 display_lat("slat", min, max, mean, dev, out);
412         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
413                 display_lat("clat", min, max, mean, dev, out);
414         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
415                 display_lat(" lat", min, max, mean, dev, out);
416
417         if (ts->clat_percentiles) {
418                 show_clat_percentiles(ts->io_u_plat[ddir],
419                                         ts->clat_stat[ddir].samples,
420                                         ts->percentile_list,
421                                         ts->percentile_precision, out);
422         }
423         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
424                 double p_of_agg = 100.0, fkb_base = (double)rs->kb_base;
425                 const char *bw_str = (rs->unit_base == 1 ? "Kbit" : "KB");
426
427                 if (rs->unit_base == 1) {
428                         min *= 8.0;
429                         max *= 8.0;
430                         mean *= 8.0;
431                         dev *= 8.0;
432                 }
433
434                 if (rs->agg[ddir]) {
435                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
436                         if (p_of_agg > 100.0)
437                                 p_of_agg = 100.0;
438                 }
439
440                 if (mean > fkb_base * fkb_base) {
441                         min /= fkb_base;
442                         max /= fkb_base;
443                         mean /= fkb_base;
444                         dev /= fkb_base;
445                         bw_str = (rs->unit_base == 1 ? "Mbit" : "MB");
446                 }
447
448                 log_buf(out, "    bw (%-4s/s): min=%5lu, max=%5lu, per=%3.2f%%,"
449                          " avg=%5.02f, stdev=%5.02f\n", bw_str, min, max,
450                                                         p_of_agg, mean, dev);
451         }
452 }
453
454 static int show_lat(double *io_u_lat, int nr, const char **ranges,
455                     const char *msg, struct buf_output *out)
456 {
457         int new_line = 1, i, line = 0, shown = 0;
458
459         for (i = 0; i < nr; i++) {
460                 if (io_u_lat[i] <= 0.0)
461                         continue;
462                 shown = 1;
463                 if (new_line) {
464                         if (line)
465                                 log_buf(out, "\n");
466                         log_buf(out, "    lat (%s) : ", msg);
467                         new_line = 0;
468                         line = 0;
469                 }
470                 if (line)
471                         log_buf(out, ", ");
472                 log_buf(out, "%s%3.2f%%", ranges[i], io_u_lat[i]);
473                 line++;
474                 if (line == 5)
475                         new_line = 1;
476         }
477
478         if (shown)
479                 log_buf(out, "\n");
480
481         return shown;
482 }
483
484 static void show_lat_u(double *io_u_lat_u, struct buf_output *out)
485 {
486         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
487                                  "250=", "500=", "750=", "1000=", };
488
489         show_lat(io_u_lat_u, FIO_IO_U_LAT_U_NR, ranges, "usec", out);
490 }
491
492 static void show_lat_m(double *io_u_lat_m, struct buf_output *out)
493 {
494         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
495                                  "250=", "500=", "750=", "1000=", "2000=",
496                                  ">=2000=", };
497
498         show_lat(io_u_lat_m, FIO_IO_U_LAT_M_NR, ranges, "msec", out);
499 }
500
501 static void show_latencies(struct thread_stat *ts, struct buf_output *out)
502 {
503         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
504         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
505
506         stat_calc_lat_u(ts, io_u_lat_u);
507         stat_calc_lat_m(ts, io_u_lat_m);
508
509         show_lat_u(io_u_lat_u, out);
510         show_lat_m(io_u_lat_m, out);
511 }
512
513 static int block_state_category(int block_state)
514 {
515         switch (block_state) {
516         case BLOCK_STATE_UNINIT:
517                 return 0;
518         case BLOCK_STATE_TRIMMED:
519         case BLOCK_STATE_WRITTEN:
520                 return 1;
521         case BLOCK_STATE_WRITE_FAILURE:
522         case BLOCK_STATE_TRIM_FAILURE:
523                 return 2;
524         default:
525                 /* Silence compile warning on some BSDs and have a return */
526                 assert(0);
527                 return -1;
528         }
529 }
530
531 static int compare_block_infos(const void *bs1, const void *bs2)
532 {
533         uint32_t block1 = *(uint32_t *)bs1;
534         uint32_t block2 = *(uint32_t *)bs2;
535         int state1 = BLOCK_INFO_STATE(block1);
536         int state2 = BLOCK_INFO_STATE(block2);
537         int bscat1 = block_state_category(state1);
538         int bscat2 = block_state_category(state2);
539         int cycles1 = BLOCK_INFO_TRIMS(block1);
540         int cycles2 = BLOCK_INFO_TRIMS(block2);
541
542         if (bscat1 < bscat2)
543                 return -1;
544         if (bscat1 > bscat2)
545                 return 1;
546
547         if (cycles1 < cycles2)
548                 return -1;
549         if (cycles1 > cycles2)
550                 return 1;
551
552         if (state1 < state2)
553                 return -1;
554         if (state1 > state2)
555                 return 1;
556
557         assert(block1 == block2);
558         return 0;
559 }
560
561 static int calc_block_percentiles(int nr_block_infos, uint32_t *block_infos,
562                                   fio_fp64_t *plist, unsigned int **percentiles,
563                                   unsigned int *types)
564 {
565         int len = 0;
566         int i, nr_uninit;
567
568         qsort(block_infos, nr_block_infos, sizeof(uint32_t), compare_block_infos);
569
570         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
571                 len++;
572
573         if (!len)
574                 return 0;
575
576         /*
577          * Sort the percentile list. Note that it may already be sorted if
578          * we are using the default values, but since it's a short list this
579          * isn't a worry. Also note that this does not work for NaN values.
580          */
581         if (len > 1)
582                 qsort((void *)plist, len, sizeof(plist[0]), double_cmp);
583
584         nr_uninit = 0;
585         /* Start only after the uninit entries end */
586         for (nr_uninit = 0;
587              nr_uninit < nr_block_infos
588                 && BLOCK_INFO_STATE(block_infos[nr_uninit]) == BLOCK_STATE_UNINIT;
589              nr_uninit ++)
590                 ;
591
592         if (nr_uninit == nr_block_infos)
593                 return 0;
594
595         *percentiles = calloc(len, sizeof(**percentiles));
596
597         for (i = 0; i < len; i++) {
598                 int idx = (plist[i].u.f * (nr_block_infos - nr_uninit) / 100)
599                                 + nr_uninit;
600                 (*percentiles)[i] = BLOCK_INFO_TRIMS(block_infos[idx]);
601         }
602
603         memset(types, 0, sizeof(*types) * BLOCK_STATE_COUNT);
604         for (i = 0; i < nr_block_infos; i++)
605                 types[BLOCK_INFO_STATE(block_infos[i])]++;
606
607         return len;
608 }
609
610 static const char *block_state_names[] = {
611         [BLOCK_STATE_UNINIT] = "unwritten",
612         [BLOCK_STATE_TRIMMED] = "trimmed",
613         [BLOCK_STATE_WRITTEN] = "written",
614         [BLOCK_STATE_TRIM_FAILURE] = "trim failure",
615         [BLOCK_STATE_WRITE_FAILURE] = "write failure",
616 };
617
618 static void show_block_infos(int nr_block_infos, uint32_t *block_infos,
619                              fio_fp64_t *plist, struct buf_output *out)
620 {
621         int len, pos, i;
622         unsigned int *percentiles = NULL;
623         unsigned int block_state_counts[BLOCK_STATE_COUNT];
624
625         len = calc_block_percentiles(nr_block_infos, block_infos, plist,
626                                      &percentiles, block_state_counts);
627
628         log_buf(out, "  block lifetime percentiles :\n   |");
629         pos = 0;
630         for (i = 0; i < len; i++) {
631                 uint32_t block_info = percentiles[i];
632 #define LINE_LENGTH     75
633                 char str[LINE_LENGTH];
634                 int strln = snprintf(str, LINE_LENGTH, " %3.2fth=%u%c",
635                                      plist[i].u.f, block_info,
636                                      i == len - 1 ? '\n' : ',');
637                 assert(strln < LINE_LENGTH);
638                 if (pos + strln > LINE_LENGTH) {
639                         pos = 0;
640                         log_buf(out, "\n   |");
641                 }
642                 log_buf(out, "%s", str);
643                 pos += strln;
644 #undef LINE_LENGTH
645         }
646         if (percentiles)
647                 free(percentiles);
648
649         log_buf(out, "        states               :");
650         for (i = 0; i < BLOCK_STATE_COUNT; i++)
651                 log_buf(out, " %s=%u%c",
652                          block_state_names[i], block_state_counts[i],
653                          i == BLOCK_STATE_COUNT - 1 ? '\n' : ',');
654 }
655
656 static void show_thread_status_normal(struct thread_stat *ts,
657                                       struct group_run_stats *rs,
658                                       struct buf_output *out)
659 {
660         double usr_cpu, sys_cpu;
661         unsigned long runtime;
662         double io_u_dist[FIO_IO_U_MAP_NR];
663         time_t time_p;
664         char time_buf[32];
665
666         if (!ddir_rw_sum(ts->io_bytes) && !ddir_rw_sum(ts->total_io_u))
667                 return;
668
669         time(&time_p);
670         os_ctime_r((const time_t *) &time_p, time_buf, sizeof(time_buf));
671
672         if (!ts->error) {
673                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d: pid=%d: %s",
674                                         ts->name, ts->groupid, ts->members,
675                                         ts->error, (int) ts->pid, time_buf);
676         } else {
677                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d (%s): pid=%d: %s",
678                                         ts->name, ts->groupid, ts->members,
679                                         ts->error, ts->verror, (int) ts->pid,
680                                         time_buf);
681         }
682
683         if (strlen(ts->description))
684                 log_buf(out, "  Description  : [%s]\n", ts->description);
685
686         if (ts->io_bytes[DDIR_READ])
687                 show_ddir_status(rs, ts, DDIR_READ, out);
688         if (ts->io_bytes[DDIR_WRITE])
689                 show_ddir_status(rs, ts, DDIR_WRITE, out);
690         if (ts->io_bytes[DDIR_TRIM])
691                 show_ddir_status(rs, ts, DDIR_TRIM, out);
692
693         show_latencies(ts, out);
694
695         runtime = ts->total_run_time;
696         if (runtime) {
697                 double runt = (double) runtime;
698
699                 usr_cpu = (double) ts->usr_time * 100 / runt;
700                 sys_cpu = (double) ts->sys_time * 100 / runt;
701         } else {
702                 usr_cpu = 0;
703                 sys_cpu = 0;
704         }
705
706         log_buf(out, "  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%llu,"
707                  " majf=%llu, minf=%llu\n", usr_cpu, sys_cpu,
708                         (unsigned long long) ts->ctx,
709                         (unsigned long long) ts->majf,
710                         (unsigned long long) ts->minf);
711
712         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
713         log_buf(out, "  IO depths    : 1=%3.1f%%, 2=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%,"
714                  " 16=%3.1f%%, 32=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
715                                         io_u_dist[1], io_u_dist[2],
716                                         io_u_dist[3], io_u_dist[4],
717                                         io_u_dist[5], io_u_dist[6]);
718
719         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
720         log_buf(out, "     submit    : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
721                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
722                                         io_u_dist[1], io_u_dist[2],
723                                         io_u_dist[3], io_u_dist[4],
724                                         io_u_dist[5], io_u_dist[6]);
725         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
726         log_buf(out, "     complete  : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
727                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
728                                         io_u_dist[1], io_u_dist[2],
729                                         io_u_dist[3], io_u_dist[4],
730                                         io_u_dist[5], io_u_dist[6]);
731         log_buf(out, "     issued    : total=r=%llu/w=%llu/d=%llu,"
732                                  " short=r=%llu/w=%llu/d=%llu,"
733                                  " drop=r=%llu/w=%llu/d=%llu\n",
734                                         (unsigned long long) ts->total_io_u[0],
735                                         (unsigned long long) ts->total_io_u[1],
736                                         (unsigned long long) ts->total_io_u[2],
737                                         (unsigned long long) ts->short_io_u[0],
738                                         (unsigned long long) ts->short_io_u[1],
739                                         (unsigned long long) ts->short_io_u[2],
740                                         (unsigned long long) ts->drop_io_u[0],
741                                         (unsigned long long) ts->drop_io_u[1],
742                                         (unsigned long long) ts->drop_io_u[2]);
743         if (ts->continue_on_error) {
744                 log_buf(out, "     errors    : total=%llu, first_error=%d/<%s>\n",
745                                         (unsigned long long)ts->total_err_count,
746                                         ts->first_error,
747                                         strerror(ts->first_error));
748         }
749         if (ts->latency_depth) {
750                 log_buf(out, "     latency   : target=%llu, window=%llu, percentile=%.2f%%, depth=%u\n",
751                                         (unsigned long long)ts->latency_target,
752                                         (unsigned long long)ts->latency_window,
753                                         ts->latency_percentile.u.f,
754                                         ts->latency_depth);
755         }
756
757         if (ts->nr_block_infos)
758                 show_block_infos(ts->nr_block_infos, ts->block_infos,
759                                   ts->percentile_list, out);
760 }
761
762 static void show_ddir_status_terse(struct thread_stat *ts,
763                                    struct group_run_stats *rs, int ddir,
764                                    struct buf_output *out)
765 {
766         unsigned long min, max;
767         unsigned long long bw, iops;
768         unsigned int *ovals = NULL;
769         double mean, dev;
770         unsigned int len, minv, maxv;
771         int i;
772
773         assert(ddir_rw(ddir));
774
775         iops = bw = 0;
776         if (ts->runtime[ddir]) {
777                 uint64_t runt = ts->runtime[ddir];
778
779                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024;
780                 iops = (1000 * (uint64_t) ts->total_io_u[ddir]) / runt;
781         }
782
783         log_buf(out, ";%llu;%llu;%llu;%llu",
784                 (unsigned long long) ts->io_bytes[ddir] >> 10, bw, iops,
785                                         (unsigned long long) ts->runtime[ddir]);
786
787         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
788                 log_buf(out, ";%lu;%lu;%f;%f", min, max, mean, dev);
789         else
790                 log_buf(out, ";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
791
792         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
793                 log_buf(out, ";%lu;%lu;%f;%f", min, max, mean, dev);
794         else
795                 log_buf(out, ";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
796
797         if (ts->clat_percentiles) {
798                 len = calc_clat_percentiles(ts->io_u_plat[ddir],
799                                         ts->clat_stat[ddir].samples,
800                                         ts->percentile_list, &ovals, &maxv,
801                                         &minv);
802         } else
803                 len = 0;
804
805         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
806                 if (i >= len) {
807                         log_buf(out, ";0%%=0");
808                         continue;
809                 }
810                 log_buf(out, ";%f%%=%u", ts->percentile_list[i].u.f, ovals[i]);
811         }
812
813         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
814                 log_buf(out, ";%lu;%lu;%f;%f", min, max, mean, dev);
815         else
816                 log_buf(out, ";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
817
818         if (ovals)
819                 free(ovals);
820
821         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
822                 double p_of_agg = 100.0;
823
824                 if (rs->agg[ddir]) {
825                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
826                         if (p_of_agg > 100.0)
827                                 p_of_agg = 100.0;
828                 }
829
830                 log_buf(out, ";%lu;%lu;%f%%;%f;%f", min, max, p_of_agg, mean, dev);
831         } else
832                 log_buf(out, ";%lu;%lu;%f%%;%f;%f", 0UL, 0UL, 0.0, 0.0, 0.0);
833 }
834
835 static void add_ddir_status_json(struct thread_stat *ts,
836                 struct group_run_stats *rs, int ddir, struct json_object *parent)
837 {
838         unsigned long min, max;
839         unsigned long long bw;
840         unsigned int *ovals = NULL;
841         double mean, dev, iops;
842         unsigned int len, minv, maxv;
843         int i;
844         const char *ddirname[] = {"read", "write", "trim"};
845         struct json_object *dir_object, *tmp_object, *percentile_object, *clat_bins_object;
846         char buf[120];
847         double p_of_agg = 100.0;
848
849         assert(ddir_rw(ddir));
850
851         if (ts->unified_rw_rep && ddir != DDIR_READ)
852                 return;
853
854         dir_object = json_create_object();
855         json_object_add_value_object(parent,
856                 ts->unified_rw_rep ? "mixed" : ddirname[ddir], dir_object);
857
858         bw = 0;
859         iops = 0.0;
860         if (ts->runtime[ddir]) {
861                 uint64_t runt = ts->runtime[ddir];
862
863                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024;
864                 iops = (1000.0 * (uint64_t) ts->total_io_u[ddir]) / runt;
865         }
866
867         json_object_add_value_int(dir_object, "io_bytes", ts->io_bytes[ddir] >> 10);
868         json_object_add_value_int(dir_object, "bw", bw);
869         json_object_add_value_float(dir_object, "iops", iops);
870         json_object_add_value_int(dir_object, "runtime", ts->runtime[ddir]);
871         json_object_add_value_int(dir_object, "total_ios", ts->total_io_u[ddir]);
872         json_object_add_value_int(dir_object, "short_ios", ts->short_io_u[ddir]);
873         json_object_add_value_int(dir_object, "drop_ios", ts->drop_io_u[ddir]);
874
875         if (!calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev)) {
876                 min = max = 0;
877                 mean = dev = 0.0;
878         }
879         tmp_object = json_create_object();
880         json_object_add_value_object(dir_object, "slat", tmp_object);
881         json_object_add_value_int(tmp_object, "min", min);
882         json_object_add_value_int(tmp_object, "max", max);
883         json_object_add_value_float(tmp_object, "mean", mean);
884         json_object_add_value_float(tmp_object, "stddev", dev);
885
886         if (!calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev)) {
887                 min = max = 0;
888                 mean = dev = 0.0;
889         }
890         tmp_object = json_create_object();
891         json_object_add_value_object(dir_object, "clat", tmp_object);
892         json_object_add_value_int(tmp_object, "min", min);
893         json_object_add_value_int(tmp_object, "max", max);
894         json_object_add_value_float(tmp_object, "mean", mean);
895         json_object_add_value_float(tmp_object, "stddev", dev);
896
897         if (ts->clat_percentiles) {
898                 len = calc_clat_percentiles(ts->io_u_plat[ddir],
899                                         ts->clat_stat[ddir].samples,
900                                         ts->percentile_list, &ovals, &maxv,
901                                         &minv);
902         } else
903                 len = 0;
904
905         percentile_object = json_create_object();
906         json_object_add_value_object(tmp_object, "percentile", percentile_object);
907         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
908                 if (i >= len) {
909                         json_object_add_value_int(percentile_object, "0.00", 0);
910                         continue;
911                 }
912                 snprintf(buf, sizeof(buf), "%f", ts->percentile_list[i].u.f);
913                 json_object_add_value_int(percentile_object, (const char *)buf, ovals[i]);
914         }
915
916         if (output_format & FIO_OUTPUT_JSON_PLUS) {
917                 clat_bins_object = json_create_object();
918                 json_object_add_value_object(tmp_object, "bins", clat_bins_object);
919                 for(i = 0; i < FIO_IO_U_PLAT_NR; i++) {
920                         snprintf(buf, sizeof(buf), "%d", i);
921                         json_object_add_value_int(clat_bins_object, (const char *)buf, ts->io_u_plat[ddir][i]);
922                 }
923                 json_object_add_value_int(clat_bins_object, "FIO_IO_U_PLAT_BITS", FIO_IO_U_PLAT_BITS);
924                 json_object_add_value_int(clat_bins_object, "FIO_IO_U_PLAT_VAL", FIO_IO_U_PLAT_VAL);
925                 json_object_add_value_int(clat_bins_object, "FIO_IO_U_PLAT_NR", FIO_IO_U_PLAT_NR);
926         }
927
928         if (!calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev)) {
929                 min = max = 0;
930                 mean = dev = 0.0;
931         }
932         tmp_object = json_create_object();
933         json_object_add_value_object(dir_object, "lat", tmp_object);
934         json_object_add_value_int(tmp_object, "min", min);
935         json_object_add_value_int(tmp_object, "max", max);
936         json_object_add_value_float(tmp_object, "mean", mean);
937         json_object_add_value_float(tmp_object, "stddev", dev);
938         if (ovals)
939                 free(ovals);
940
941         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
942                 if (rs->agg[ddir]) {
943                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
944                         if (p_of_agg > 100.0)
945                                 p_of_agg = 100.0;
946                 }
947         } else {
948                 min = max = 0;
949                 p_of_agg = mean = dev = 0.0;
950         }
951         json_object_add_value_int(dir_object, "bw_min", min);
952         json_object_add_value_int(dir_object, "bw_max", max);
953         json_object_add_value_float(dir_object, "bw_agg", p_of_agg);
954         json_object_add_value_float(dir_object, "bw_mean", mean);
955         json_object_add_value_float(dir_object, "bw_dev", dev);
956 }
957
958 static void show_thread_status_terse_v2(struct thread_stat *ts,
959                                         struct group_run_stats *rs,
960                                         struct buf_output *out)
961 {
962         double io_u_dist[FIO_IO_U_MAP_NR];
963         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
964         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
965         double usr_cpu, sys_cpu;
966         int i;
967
968         /* General Info */
969         log_buf(out, "2;%s;%d;%d", ts->name, ts->groupid, ts->error);
970         /* Log Read Status */
971         show_ddir_status_terse(ts, rs, DDIR_READ, out);
972         /* Log Write Status */
973         show_ddir_status_terse(ts, rs, DDIR_WRITE, out);
974         /* Log Trim Status */
975         show_ddir_status_terse(ts, rs, DDIR_TRIM, out);
976
977         /* CPU Usage */
978         if (ts->total_run_time) {
979                 double runt = (double) ts->total_run_time;
980
981                 usr_cpu = (double) ts->usr_time * 100 / runt;
982                 sys_cpu = (double) ts->sys_time * 100 / runt;
983         } else {
984                 usr_cpu = 0;
985                 sys_cpu = 0;
986         }
987
988         log_buf(out, ";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
989                                                 (unsigned long long) ts->ctx,
990                                                 (unsigned long long) ts->majf,
991                                                 (unsigned long long) ts->minf);
992
993         /* Calc % distribution of IO depths, usecond, msecond latency */
994         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
995         stat_calc_lat_u(ts, io_u_lat_u);
996         stat_calc_lat_m(ts, io_u_lat_m);
997
998         /* Only show fixed 7 I/O depth levels*/
999         log_buf(out, ";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
1000                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
1001                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
1002
1003         /* Microsecond latency */
1004         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1005                 log_buf(out, ";%3.2f%%", io_u_lat_u[i]);
1006         /* Millisecond latency */
1007         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1008                 log_buf(out, ";%3.2f%%", io_u_lat_m[i]);
1009         /* Additional output if continue_on_error set - default off*/
1010         if (ts->continue_on_error)
1011                 log_buf(out, ";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
1012         log_buf(out, "\n");
1013
1014         /* Additional output if description is set */
1015         if (strlen(ts->description))
1016                 log_buf(out, ";%s", ts->description);
1017
1018         log_buf(out, "\n");
1019 }
1020
1021 static void show_thread_status_terse_v3_v4(struct thread_stat *ts,
1022                                            struct group_run_stats *rs, int ver,
1023                                            struct buf_output *out)
1024 {
1025         double io_u_dist[FIO_IO_U_MAP_NR];
1026         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1027         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1028         double usr_cpu, sys_cpu;
1029         int i;
1030
1031         /* General Info */
1032         log_buf(out, "%d;%s;%s;%d;%d", ver, fio_version_string,
1033                                         ts->name, ts->groupid, ts->error);
1034         /* Log Read Status */
1035         show_ddir_status_terse(ts, rs, DDIR_READ, out);
1036         /* Log Write Status */
1037         show_ddir_status_terse(ts, rs, DDIR_WRITE, out);
1038         /* Log Trim Status */
1039         if (ver == 4)
1040                 show_ddir_status_terse(ts, rs, DDIR_TRIM, out);
1041
1042         /* CPU Usage */
1043         if (ts->total_run_time) {
1044                 double runt = (double) ts->total_run_time;
1045
1046                 usr_cpu = (double) ts->usr_time * 100 / runt;
1047                 sys_cpu = (double) ts->sys_time * 100 / runt;
1048         } else {
1049                 usr_cpu = 0;
1050                 sys_cpu = 0;
1051         }
1052
1053         log_buf(out, ";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
1054                                                 (unsigned long long) ts->ctx,
1055                                                 (unsigned long long) ts->majf,
1056                                                 (unsigned long long) ts->minf);
1057
1058         /* Calc % distribution of IO depths, usecond, msecond latency */
1059         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1060         stat_calc_lat_u(ts, io_u_lat_u);
1061         stat_calc_lat_m(ts, io_u_lat_m);
1062
1063         /* Only show fixed 7 I/O depth levels*/
1064         log_buf(out, ";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
1065                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
1066                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
1067
1068         /* Microsecond latency */
1069         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1070                 log_buf(out, ";%3.2f%%", io_u_lat_u[i]);
1071         /* Millisecond latency */
1072         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1073                 log_buf(out, ";%3.2f%%", io_u_lat_m[i]);
1074
1075         /* disk util stats, if any */
1076         show_disk_util(1, NULL, out);
1077
1078         /* Additional output if continue_on_error set - default off*/
1079         if (ts->continue_on_error)
1080                 log_buf(out, ";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
1081
1082         /* Additional output if description is set */
1083         if (strlen(ts->description))
1084                 log_buf(out, ";%s", ts->description);
1085
1086         log_buf(out, "\n");
1087 }
1088
1089 static void json_add_job_opts(struct json_object *root, const char *name,
1090                               struct flist_head *opt_list)
1091 {
1092         struct json_object *dir_object;
1093         struct flist_head *entry;
1094         struct print_option *p;
1095
1096         if (flist_empty(opt_list))
1097                 return;
1098
1099         dir_object = json_create_object();
1100         json_object_add_value_object(root, name, dir_object);
1101
1102         flist_for_each(entry, opt_list) {
1103                 const char *pos = "";
1104
1105                 p = flist_entry(entry, struct print_option, list);
1106                 if (p->value)
1107                         pos = p->value;
1108                 json_object_add_value_string(dir_object, p->name, pos);
1109         }
1110 }
1111
1112 static struct json_object *show_thread_status_json(struct thread_stat *ts,
1113                                                    struct group_run_stats *rs,
1114                                                    struct flist_head *opt_list)
1115 {
1116         struct json_object *root, *tmp;
1117         struct jobs_eta *je;
1118         double io_u_dist[FIO_IO_U_MAP_NR];
1119         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1120         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1121         double usr_cpu, sys_cpu;
1122         int i;
1123         size_t size;
1124
1125         root = json_create_object();
1126         json_object_add_value_string(root, "jobname", ts->name);
1127         json_object_add_value_int(root, "groupid", ts->groupid);
1128         json_object_add_value_int(root, "error", ts->error);
1129
1130         /* ETA Info */
1131         je = get_jobs_eta(true, &size);
1132         if (je) {
1133                 json_object_add_value_int(root, "eta", je->eta_sec);
1134                 json_object_add_value_int(root, "elapsed", je->elapsed_sec);
1135         }
1136
1137         if (opt_list)
1138                 json_add_job_opts(root, "job options", opt_list);
1139
1140         add_ddir_status_json(ts, rs, DDIR_READ, root);
1141         add_ddir_status_json(ts, rs, DDIR_WRITE, root);
1142         add_ddir_status_json(ts, rs, DDIR_TRIM, root);
1143
1144         /* CPU Usage */
1145         if (ts->total_run_time) {
1146                 double runt = (double) ts->total_run_time;
1147
1148                 usr_cpu = (double) ts->usr_time * 100 / runt;
1149                 sys_cpu = (double) ts->sys_time * 100 / runt;
1150         } else {
1151                 usr_cpu = 0;
1152                 sys_cpu = 0;
1153         }
1154         json_object_add_value_float(root, "usr_cpu", usr_cpu);
1155         json_object_add_value_float(root, "sys_cpu", sys_cpu);
1156         json_object_add_value_int(root, "ctx", ts->ctx);
1157         json_object_add_value_int(root, "majf", ts->majf);
1158         json_object_add_value_int(root, "minf", ts->minf);
1159
1160
1161         /* Calc % distribution of IO depths, usecond, msecond latency */
1162         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1163         stat_calc_lat_u(ts, io_u_lat_u);
1164         stat_calc_lat_m(ts, io_u_lat_m);
1165
1166         tmp = json_create_object();
1167         json_object_add_value_object(root, "iodepth_level", tmp);
1168         /* Only show fixed 7 I/O depth levels*/
1169         for (i = 0; i < 7; i++) {
1170                 char name[20];
1171                 if (i < 6)
1172                         snprintf(name, 20, "%d", 1 << i);
1173                 else
1174                         snprintf(name, 20, ">=%d", 1 << i);
1175                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1176         }
1177
1178         tmp = json_create_object();
1179         json_object_add_value_object(root, "latency_us", tmp);
1180         /* Microsecond latency */
1181         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++) {
1182                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1183                                  "250", "500", "750", "1000", };
1184                 json_object_add_value_float(tmp, ranges[i], io_u_lat_u[i]);
1185         }
1186         /* Millisecond latency */
1187         tmp = json_create_object();
1188         json_object_add_value_object(root, "latency_ms", tmp);
1189         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++) {
1190                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1191                                  "250", "500", "750", "1000", "2000",
1192                                  ">=2000", };
1193                 json_object_add_value_float(tmp, ranges[i], io_u_lat_m[i]);
1194         }
1195
1196         /* Additional output if continue_on_error set - default off*/
1197         if (ts->continue_on_error) {
1198                 json_object_add_value_int(root, "total_err", ts->total_err_count);
1199                 json_object_add_value_int(root, "first_error", ts->first_error);
1200         }
1201
1202         if (ts->latency_depth) {
1203                 json_object_add_value_int(root, "latency_depth", ts->latency_depth);
1204                 json_object_add_value_int(root, "latency_target", ts->latency_target);
1205                 json_object_add_value_float(root, "latency_percentile", ts->latency_percentile.u.f);
1206                 json_object_add_value_int(root, "latency_window", ts->latency_window);
1207         }
1208
1209         /* Additional output if description is set */
1210         if (strlen(ts->description))
1211                 json_object_add_value_string(root, "desc", ts->description);
1212
1213         if (ts->nr_block_infos) {
1214                 /* Block error histogram and types */
1215                 int len;
1216                 unsigned int *percentiles = NULL;
1217                 unsigned int block_state_counts[BLOCK_STATE_COUNT];
1218
1219                 len = calc_block_percentiles(ts->nr_block_infos, ts->block_infos,
1220                                              ts->percentile_list,
1221                                              &percentiles, block_state_counts);
1222
1223                 if (len) {
1224                         struct json_object *block, *percentile_object, *states;
1225                         int state;
1226                         block = json_create_object();
1227                         json_object_add_value_object(root, "block", block);
1228
1229                         percentile_object = json_create_object();
1230                         json_object_add_value_object(block, "percentiles",
1231                                                      percentile_object);
1232                         for (i = 0; i < len; i++) {
1233                                 char buf[20];
1234                                 snprintf(buf, sizeof(buf), "%f",
1235                                          ts->percentile_list[i].u.f);
1236                                 json_object_add_value_int(percentile_object,
1237                                                           (const char *)buf,
1238                                                           percentiles[i]);
1239                         }
1240
1241                         states = json_create_object();
1242                         json_object_add_value_object(block, "states", states);
1243                         for (state = 0; state < BLOCK_STATE_COUNT; state++) {
1244                                 json_object_add_value_int(states,
1245                                         block_state_names[state],
1246                                         block_state_counts[state]);
1247                         }
1248                         free(percentiles);
1249                 }
1250         }
1251
1252         return root;
1253 }
1254
1255 static void show_thread_status_terse(struct thread_stat *ts,
1256                                      struct group_run_stats *rs,
1257                                      struct buf_output *out)
1258 {
1259         if (terse_version == 2)
1260                 show_thread_status_terse_v2(ts, rs, out);
1261         else if (terse_version == 3 || terse_version == 4)
1262                 show_thread_status_terse_v3_v4(ts, rs, terse_version, out);
1263         else
1264                 log_err("fio: bad terse version!? %d\n", terse_version);
1265 }
1266
1267 struct json_object *show_thread_status(struct thread_stat *ts,
1268                                        struct group_run_stats *rs,
1269                                        struct buf_output *out)
1270 {
1271         struct json_object *ret = NULL;
1272
1273         if (output_format & FIO_OUTPUT_TERSE)
1274                 show_thread_status_terse(ts, rs,  out);
1275         if (output_format & FIO_OUTPUT_JSON)
1276                 ret = show_thread_status_json(ts, rs, NULL);
1277         if (output_format & FIO_OUTPUT_NORMAL)
1278                 show_thread_status_normal(ts, rs,  out);
1279
1280         return ret;
1281 }
1282
1283 static void sum_stat(struct io_stat *dst, struct io_stat *src, bool first)
1284 {
1285         double mean, S;
1286
1287         if (src->samples == 0)
1288                 return;
1289
1290         dst->min_val = min(dst->min_val, src->min_val);
1291         dst->max_val = max(dst->max_val, src->max_val);
1292
1293         /*
1294          * Compute new mean and S after the merge
1295          * <http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
1296          *  #Parallel_algorithm>
1297          */
1298         if (first) {
1299                 mean = src->mean.u.f;
1300                 S = src->S.u.f;
1301         } else {
1302                 double delta = src->mean.u.f - dst->mean.u.f;
1303
1304                 mean = ((src->mean.u.f * src->samples) +
1305                         (dst->mean.u.f * dst->samples)) /
1306                         (dst->samples + src->samples);
1307
1308                 S =  src->S.u.f + dst->S.u.f + pow(delta, 2.0) *
1309                         (dst->samples * src->samples) /
1310                         (dst->samples + src->samples);
1311         }
1312
1313         dst->samples += src->samples;
1314         dst->mean.u.f = mean;
1315         dst->S.u.f = S;
1316 }
1317
1318 void sum_group_stats(struct group_run_stats *dst, struct group_run_stats *src)
1319 {
1320         int i;
1321
1322         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1323                 if (dst->max_run[i] < src->max_run[i])
1324                         dst->max_run[i] = src->max_run[i];
1325                 if (dst->min_run[i] && dst->min_run[i] > src->min_run[i])
1326                         dst->min_run[i] = src->min_run[i];
1327                 if (dst->max_bw[i] < src->max_bw[i])
1328                         dst->max_bw[i] = src->max_bw[i];
1329                 if (dst->min_bw[i] && dst->min_bw[i] > src->min_bw[i])
1330                         dst->min_bw[i] = src->min_bw[i];
1331
1332                 dst->io_kb[i] += src->io_kb[i];
1333                 dst->agg[i] += src->agg[i];
1334         }
1335
1336         if (!dst->kb_base)
1337                 dst->kb_base = src->kb_base;
1338         if (!dst->unit_base)
1339                 dst->unit_base = src->unit_base;
1340 }
1341
1342 void sum_thread_stats(struct thread_stat *dst, struct thread_stat *src,
1343                       bool first)
1344 {
1345         int l, k;
1346
1347         for (l = 0; l < DDIR_RWDIR_CNT; l++) {
1348                 if (!dst->unified_rw_rep) {
1349                         sum_stat(&dst->clat_stat[l], &src->clat_stat[l], first);
1350                         sum_stat(&dst->slat_stat[l], &src->slat_stat[l], first);
1351                         sum_stat(&dst->lat_stat[l], &src->lat_stat[l], first);
1352                         sum_stat(&dst->bw_stat[l], &src->bw_stat[l], first);
1353
1354                         dst->io_bytes[l] += src->io_bytes[l];
1355
1356                         if (dst->runtime[l] < src->runtime[l])
1357                                 dst->runtime[l] = src->runtime[l];
1358                 } else {
1359                         sum_stat(&dst->clat_stat[0], &src->clat_stat[l], first);
1360                         sum_stat(&dst->slat_stat[0], &src->slat_stat[l], first);
1361                         sum_stat(&dst->lat_stat[0], &src->lat_stat[l], first);
1362                         sum_stat(&dst->bw_stat[0], &src->bw_stat[l], first);
1363
1364                         dst->io_bytes[0] += src->io_bytes[l];
1365
1366                         if (dst->runtime[0] < src->runtime[l])
1367                                 dst->runtime[0] = src->runtime[l];
1368
1369                         /*
1370                          * We're summing to the same destination, so override
1371                          * 'first' after the first iteration of the loop
1372                          */
1373                         first = false;
1374                 }
1375         }
1376
1377         dst->usr_time += src->usr_time;
1378         dst->sys_time += src->sys_time;
1379         dst->ctx += src->ctx;
1380         dst->majf += src->majf;
1381         dst->minf += src->minf;
1382
1383         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1384                 dst->io_u_map[k] += src->io_u_map[k];
1385         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1386                 dst->io_u_submit[k] += src->io_u_submit[k];
1387         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1388                 dst->io_u_complete[k] += src->io_u_complete[k];
1389         for (k = 0; k < FIO_IO_U_LAT_U_NR; k++)
1390                 dst->io_u_lat_u[k] += src->io_u_lat_u[k];
1391         for (k = 0; k < FIO_IO_U_LAT_M_NR; k++)
1392                 dst->io_u_lat_m[k] += src->io_u_lat_m[k];
1393
1394         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1395                 if (!dst->unified_rw_rep) {
1396                         dst->total_io_u[k] += src->total_io_u[k];
1397                         dst->short_io_u[k] += src->short_io_u[k];
1398                         dst->drop_io_u[k] += src->drop_io_u[k];
1399                 } else {
1400                         dst->total_io_u[0] += src->total_io_u[k];
1401                         dst->short_io_u[0] += src->short_io_u[k];
1402                         dst->drop_io_u[0] += src->drop_io_u[k];
1403                 }
1404         }
1405
1406         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1407                 int m;
1408
1409                 for (m = 0; m < FIO_IO_U_PLAT_NR; m++) {
1410                         if (!dst->unified_rw_rep)
1411                                 dst->io_u_plat[k][m] += src->io_u_plat[k][m];
1412                         else
1413                                 dst->io_u_plat[0][m] += src->io_u_plat[k][m];
1414                 }
1415         }
1416
1417         dst->total_run_time += src->total_run_time;
1418         dst->total_submit += src->total_submit;
1419         dst->total_complete += src->total_complete;
1420 }
1421
1422 void init_group_run_stat(struct group_run_stats *gs)
1423 {
1424         int i;
1425         memset(gs, 0, sizeof(*gs));
1426
1427         for (i = 0; i < DDIR_RWDIR_CNT; i++)
1428                 gs->min_bw[i] = gs->min_run[i] = ~0UL;
1429 }
1430
1431 void init_thread_stat(struct thread_stat *ts)
1432 {
1433         int j;
1434
1435         memset(ts, 0, sizeof(*ts));
1436
1437         for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1438                 ts->lat_stat[j].min_val = -1UL;
1439                 ts->clat_stat[j].min_val = -1UL;
1440                 ts->slat_stat[j].min_val = -1UL;
1441                 ts->bw_stat[j].min_val = -1UL;
1442         }
1443         ts->groupid = -1;
1444 }
1445
1446 void __show_run_stats(void)
1447 {
1448         struct group_run_stats *runstats, *rs;
1449         struct thread_data *td;
1450         struct thread_stat *threadstats, *ts;
1451         int i, j, k, nr_ts, last_ts, idx;
1452         int kb_base_warned = 0;
1453         int unit_base_warned = 0;
1454         struct json_object *root = NULL;
1455         struct json_array *array = NULL;
1456         struct buf_output output[FIO_OUTPUT_NR];
1457         struct flist_head **opt_lists;
1458
1459         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
1460
1461         for (i = 0; i < groupid + 1; i++)
1462                 init_group_run_stat(&runstats[i]);
1463
1464         /*
1465          * find out how many threads stats we need. if group reporting isn't
1466          * enabled, it's one-per-td.
1467          */
1468         nr_ts = 0;
1469         last_ts = -1;
1470         for_each_td(td, i) {
1471                 if (!td->o.group_reporting) {
1472                         nr_ts++;
1473                         continue;
1474                 }
1475                 if (last_ts == td->groupid)
1476                         continue;
1477
1478                 last_ts = td->groupid;
1479                 nr_ts++;
1480         }
1481
1482         threadstats = malloc(nr_ts * sizeof(struct thread_stat));
1483         opt_lists = malloc(nr_ts * sizeof(struct flist_head *));
1484
1485         for (i = 0; i < nr_ts; i++) {
1486                 init_thread_stat(&threadstats[i]);
1487                 opt_lists[i] = NULL;
1488         }
1489
1490         j = 0;
1491         last_ts = -1;
1492         idx = 0;
1493         for_each_td(td, i) {
1494                 if (idx && (!td->o.group_reporting ||
1495                     (td->o.group_reporting && last_ts != td->groupid))) {
1496                         idx = 0;
1497                         j++;
1498                 }
1499
1500                 last_ts = td->groupid;
1501
1502                 ts = &threadstats[j];
1503
1504                 ts->clat_percentiles = td->o.clat_percentiles;
1505                 ts->percentile_precision = td->o.percentile_precision;
1506                 memcpy(ts->percentile_list, td->o.percentile_list, sizeof(td->o.percentile_list));
1507                 opt_lists[j] = &td->opt_list;
1508
1509                 idx++;
1510                 ts->members++;
1511
1512                 if (ts->groupid == -1) {
1513                         /*
1514                          * These are per-group shared already
1515                          */
1516                         strncpy(ts->name, td->o.name, FIO_JOBNAME_SIZE - 1);
1517                         if (td->o.description)
1518                                 strncpy(ts->description, td->o.description,
1519                                                 FIO_JOBDESC_SIZE - 1);
1520                         else
1521                                 memset(ts->description, 0, FIO_JOBDESC_SIZE);
1522
1523                         /*
1524                          * If multiple entries in this group, this is
1525                          * the first member.
1526                          */
1527                         ts->thread_number = td->thread_number;
1528                         ts->groupid = td->groupid;
1529
1530                         /*
1531                          * first pid in group, not very useful...
1532                          */
1533                         ts->pid = td->pid;
1534
1535                         ts->kb_base = td->o.kb_base;
1536                         ts->unit_base = td->o.unit_base;
1537                         ts->unified_rw_rep = td->o.unified_rw_rep;
1538                 } else if (ts->kb_base != td->o.kb_base && !kb_base_warned) {
1539                         log_info("fio: kb_base differs for jobs in group, using"
1540                                  " %u as the base\n", ts->kb_base);
1541                         kb_base_warned = 1;
1542                 } else if (ts->unit_base != td->o.unit_base && !unit_base_warned) {
1543                         log_info("fio: unit_base differs for jobs in group, using"
1544                                  " %u as the base\n", ts->unit_base);
1545                         unit_base_warned = 1;
1546                 }
1547
1548                 ts->continue_on_error = td->o.continue_on_error;
1549                 ts->total_err_count += td->total_err_count;
1550                 ts->first_error = td->first_error;
1551                 if (!ts->error) {
1552                         if (!td->error && td->o.continue_on_error &&
1553                             td->first_error) {
1554                                 ts->error = td->first_error;
1555                                 ts->verror[sizeof(ts->verror) - 1] = '\0';
1556                                 strncpy(ts->verror, td->verror, sizeof(ts->verror) - 1);
1557                         } else  if (td->error) {
1558                                 ts->error = td->error;
1559                                 ts->verror[sizeof(ts->verror) - 1] = '\0';
1560                                 strncpy(ts->verror, td->verror, sizeof(ts->verror) - 1);
1561                         }
1562                 }
1563
1564                 ts->latency_depth = td->latency_qd;
1565                 ts->latency_target = td->o.latency_target;
1566                 ts->latency_percentile = td->o.latency_percentile;
1567                 ts->latency_window = td->o.latency_window;
1568
1569                 ts->nr_block_infos = td->ts.nr_block_infos;
1570                 for (k = 0; k < ts->nr_block_infos; k++)
1571                         ts->block_infos[k] = td->ts.block_infos[k];
1572
1573                 sum_thread_stats(ts, &td->ts, idx == 1);
1574         }
1575
1576         for (i = 0; i < nr_ts; i++) {
1577                 unsigned long long bw;
1578
1579                 ts = &threadstats[i];
1580                 rs = &runstats[ts->groupid];
1581                 rs->kb_base = ts->kb_base;
1582                 rs->unit_base = ts->unit_base;
1583                 rs->unified_rw_rep += ts->unified_rw_rep;
1584
1585                 for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1586                         if (!ts->runtime[j])
1587                                 continue;
1588                         if (ts->runtime[j] < rs->min_run[j] || !rs->min_run[j])
1589                                 rs->min_run[j] = ts->runtime[j];
1590                         if (ts->runtime[j] > rs->max_run[j])
1591                                 rs->max_run[j] = ts->runtime[j];
1592
1593                         bw = 0;
1594                         if (ts->runtime[j]) {
1595                                 unsigned long runt = ts->runtime[j];
1596                                 unsigned long long kb;
1597
1598                                 kb = ts->io_bytes[j] / rs->kb_base;
1599                                 bw = kb * 1000 / runt;
1600                         }
1601                         if (bw < rs->min_bw[j])
1602                                 rs->min_bw[j] = bw;
1603                         if (bw > rs->max_bw[j])
1604                                 rs->max_bw[j] = bw;
1605
1606                         rs->io_kb[j] += ts->io_bytes[j] / rs->kb_base;
1607                 }
1608         }
1609
1610         for (i = 0; i < groupid + 1; i++) {
1611                 int ddir;
1612
1613                 rs = &runstats[i];
1614
1615                 for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
1616                         if (rs->max_run[ddir])
1617                                 rs->agg[ddir] = (rs->io_kb[ddir] * 1000) /
1618                                                 rs->max_run[ddir];
1619                 }
1620         }
1621
1622         for (i = 0; i < FIO_OUTPUT_NR; i++)
1623                 buf_output_init(&output[i]);
1624
1625         /*
1626          * don't overwrite last signal output
1627          */
1628         if (output_format & FIO_OUTPUT_NORMAL)
1629                 log_buf(&output[__FIO_OUTPUT_NORMAL], "\n");
1630         if (output_format & FIO_OUTPUT_JSON) {
1631                 struct thread_data *global;
1632                 char time_buf[32];
1633                 time_t time_p;
1634
1635                 time(&time_p);
1636                 os_ctime_r((const time_t *) &time_p, time_buf,
1637                                 sizeof(time_buf));
1638                 time_buf[strlen(time_buf) - 1] = '\0';
1639
1640                 root = json_create_object();
1641                 json_object_add_value_string(root, "fio version", fio_version_string);
1642                 json_object_add_value_int(root, "timestamp", time_p);
1643                 json_object_add_value_string(root, "time", time_buf);
1644                 global = get_global_options();
1645                 json_add_job_opts(root, "global options", &global->opt_list);
1646                 array = json_create_array();
1647                 json_object_add_value_array(root, "jobs", array);
1648         }
1649
1650         for (i = 0; i < nr_ts; i++) {
1651                 ts = &threadstats[i];
1652                 rs = &runstats[ts->groupid];
1653
1654                 if (is_backend)
1655                         fio_server_send_ts(ts, rs);
1656                 else {
1657                         if (output_format & FIO_OUTPUT_TERSE)
1658                                 show_thread_status_terse(ts, rs, &output[__FIO_OUTPUT_TERSE]);
1659                         if (output_format & FIO_OUTPUT_JSON) {
1660                                 struct json_object *tmp = show_thread_status_json(ts, rs, opt_lists[i]);
1661                                 json_array_add_value_object(array, tmp);
1662                         }
1663                         if (output_format & FIO_OUTPUT_NORMAL)
1664                                 show_thread_status_normal(ts, rs, &output[__FIO_OUTPUT_NORMAL]);
1665                 }
1666         }
1667         if (!is_backend && (output_format & FIO_OUTPUT_JSON)) {
1668                 /* disk util stats, if any */
1669                 show_disk_util(1, root, &output[__FIO_OUTPUT_JSON]);
1670
1671                 show_idle_prof_stats(FIO_OUTPUT_JSON, root, &output[__FIO_OUTPUT_JSON]);
1672
1673                 json_print_object(root, &output[__FIO_OUTPUT_JSON]);
1674                 log_buf(&output[__FIO_OUTPUT_JSON], "\n");
1675                 json_free_object(root);
1676         }
1677
1678         for (i = 0; i < groupid + 1; i++) {
1679                 rs = &runstats[i];
1680
1681                 rs->groupid = i;
1682                 if (is_backend)
1683                         fio_server_send_gs(rs);
1684                 else if (output_format & FIO_OUTPUT_NORMAL)
1685                         show_group_stats(rs, &output[__FIO_OUTPUT_NORMAL]);
1686         }
1687
1688         if (is_backend)
1689                 fio_server_send_du();
1690         else if (output_format & FIO_OUTPUT_NORMAL) {
1691                 show_disk_util(0, NULL, &output[__FIO_OUTPUT_NORMAL]);
1692                 show_idle_prof_stats(FIO_OUTPUT_NORMAL, NULL, &output[__FIO_OUTPUT_NORMAL]);
1693         }
1694
1695         for (i = 0; i < FIO_OUTPUT_NR; i++) {
1696                 buf_output_flush(&output[i]);
1697                 buf_output_free(&output[i]);
1698         }
1699
1700         log_info_flush();
1701         free(runstats);
1702         free(threadstats);
1703         free(opt_lists);
1704 }
1705
1706 void show_run_stats(void)
1707 {
1708         fio_mutex_down(stat_mutex);
1709         __show_run_stats();
1710         fio_mutex_up(stat_mutex);
1711 }
1712
1713 void __show_running_run_stats(void)
1714 {
1715         struct thread_data *td;
1716         unsigned long long *rt;
1717         struct timeval tv;
1718         int i;
1719
1720         fio_mutex_down(stat_mutex);
1721
1722         rt = malloc(thread_number * sizeof(unsigned long long));
1723         fio_gettime(&tv, NULL);
1724
1725         for_each_td(td, i) {
1726                 rt[i] = mtime_since(&td->start, &tv);
1727                 if (td_read(td) && td->io_bytes[DDIR_READ])
1728                         td->ts.runtime[DDIR_READ] += rt[i];
1729                 if (td_write(td) && td->io_bytes[DDIR_WRITE])
1730                         td->ts.runtime[DDIR_WRITE] += rt[i];
1731                 if (td_trim(td) && td->io_bytes[DDIR_TRIM])
1732                         td->ts.runtime[DDIR_TRIM] += rt[i];
1733
1734                 td->update_rusage = 1;
1735                 td->ts.io_bytes[DDIR_READ] = td->io_bytes[DDIR_READ];
1736                 td->ts.io_bytes[DDIR_WRITE] = td->io_bytes[DDIR_WRITE];
1737                 td->ts.io_bytes[DDIR_TRIM] = td->io_bytes[DDIR_TRIM];
1738                 td->ts.total_run_time = mtime_since(&td->epoch, &tv);
1739         }
1740
1741         for_each_td(td, i) {
1742                 if (td->runstate >= TD_EXITED)
1743                         continue;
1744                 if (td->rusage_sem) {
1745                         td->update_rusage = 1;
1746                         fio_mutex_down(td->rusage_sem);
1747                 }
1748                 td->update_rusage = 0;
1749         }
1750
1751         __show_run_stats();
1752
1753         for_each_td(td, i) {
1754                 if (td_read(td) && td->io_bytes[DDIR_READ])
1755                         td->ts.runtime[DDIR_READ] -= rt[i];
1756                 if (td_write(td) && td->io_bytes[DDIR_WRITE])
1757                         td->ts.runtime[DDIR_WRITE] -= rt[i];
1758                 if (td_trim(td) && td->io_bytes[DDIR_TRIM])
1759                         td->ts.runtime[DDIR_TRIM] -= rt[i];
1760         }
1761
1762         free(rt);
1763         fio_mutex_up(stat_mutex);
1764 }
1765
1766 static int status_interval_init;
1767 static struct timeval status_time;
1768 static int status_file_disabled;
1769
1770 #define FIO_STATUS_FILE         "fio-dump-status"
1771
1772 static int check_status_file(void)
1773 {
1774         struct stat sb;
1775         const char *temp_dir;
1776         char fio_status_file_path[PATH_MAX];
1777
1778         if (status_file_disabled)
1779                 return 0;
1780
1781         temp_dir = getenv("TMPDIR");
1782         if (temp_dir == NULL) {
1783                 temp_dir = getenv("TEMP");
1784                 if (temp_dir && strlen(temp_dir) >= PATH_MAX)
1785                         temp_dir = NULL;
1786         }
1787         if (temp_dir == NULL)
1788                 temp_dir = "/tmp";
1789
1790         snprintf(fio_status_file_path, sizeof(fio_status_file_path), "%s/%s", temp_dir, FIO_STATUS_FILE);
1791
1792         if (stat(fio_status_file_path, &sb))
1793                 return 0;
1794
1795         if (unlink(fio_status_file_path) < 0) {
1796                 log_err("fio: failed to unlink %s: %s\n", fio_status_file_path,
1797                                                         strerror(errno));
1798                 log_err("fio: disabling status file updates\n");
1799                 status_file_disabled = 1;
1800         }
1801
1802         return 1;
1803 }
1804
1805 void check_for_running_stats(void)
1806 {
1807         if (status_interval) {
1808                 if (!status_interval_init) {
1809                         fio_gettime(&status_time, NULL);
1810                         status_interval_init = 1;
1811                 } else if (mtime_since_now(&status_time) >= status_interval) {
1812                         show_running_run_stats();
1813                         fio_gettime(&status_time, NULL);
1814                         return;
1815                 }
1816         }
1817         if (check_status_file()) {
1818                 show_running_run_stats();
1819                 return;
1820         }
1821 }
1822
1823 static inline void add_stat_sample(struct io_stat *is, unsigned long data)
1824 {
1825         double val = data;
1826         double delta;
1827
1828         if (data > is->max_val)
1829                 is->max_val = data;
1830         if (data < is->min_val)
1831                 is->min_val = data;
1832
1833         delta = val - is->mean.u.f;
1834         if (delta) {
1835                 is->mean.u.f += delta / (is->samples + 1.0);
1836                 is->S.u.f += delta * (val - is->mean.u.f);
1837         }
1838
1839         is->samples++;
1840 }
1841
1842 static void __add_log_sample(struct io_log *iolog, unsigned long val,
1843                              enum fio_ddir ddir, unsigned int bs,
1844                              unsigned long t, uint64_t offset)
1845 {
1846         uint64_t nr_samples = iolog->nr_samples;
1847         struct io_sample *s;
1848
1849         if (iolog->disabled)
1850                 return;
1851
1852         if (!iolog->nr_samples)
1853                 iolog->avg_last = t;
1854
1855         if (iolog->nr_samples == iolog->max_samples) {
1856                 size_t new_size;
1857                 void *new_log;
1858
1859                 new_size = 2 * iolog->max_samples * log_entry_sz(iolog);
1860
1861                 if (iolog->log_gz && (new_size > iolog->log_gz)) {
1862                         if (iolog_flush(iolog, 0)) {
1863                                 log_err("fio: failed flushing iolog! Will stop logging.\n");
1864                                 iolog->disabled = 1;
1865                                 return;
1866                         }
1867                         nr_samples = iolog->nr_samples;
1868                 } else {
1869                         new_log = realloc(iolog->log, new_size);
1870                         if (!new_log) {
1871                                 log_err("fio: failed extending iolog! Will stop logging.\n");
1872                                 iolog->disabled = 1;
1873                                 return;
1874                         }
1875                         iolog->log = new_log;
1876                         iolog->max_samples <<= 1;
1877                 }
1878         }
1879
1880         s = get_sample(iolog, nr_samples);
1881
1882         s->val = val;
1883         s->time = t;
1884         io_sample_set_ddir(iolog, s, ddir);
1885         s->bs = bs;
1886
1887         if (iolog->log_offset) {
1888                 struct io_sample_offset *so = (void *) s;
1889
1890                 so->offset = offset;
1891         }
1892
1893         iolog->nr_samples++;
1894 }
1895
1896 static inline void reset_io_stat(struct io_stat *ios)
1897 {
1898         ios->max_val = ios->min_val = ios->samples = 0;
1899         ios->mean.u.f = ios->S.u.f = 0;
1900 }
1901
1902 void reset_io_stats(struct thread_data *td)
1903 {
1904         struct thread_stat *ts = &td->ts;
1905         int i, j;
1906
1907         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1908                 reset_io_stat(&ts->clat_stat[i]);
1909                 reset_io_stat(&ts->slat_stat[i]);
1910                 reset_io_stat(&ts->lat_stat[i]);
1911                 reset_io_stat(&ts->bw_stat[i]);
1912                 reset_io_stat(&ts->iops_stat[i]);
1913
1914                 ts->io_bytes[i] = 0;
1915                 ts->runtime[i] = 0;
1916
1917                 for (j = 0; j < FIO_IO_U_PLAT_NR; j++)
1918                         ts->io_u_plat[i][j] = 0;
1919         }
1920
1921         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
1922                 ts->io_u_map[i] = 0;
1923                 ts->io_u_submit[i] = 0;
1924                 ts->io_u_complete[i] = 0;
1925                 ts->io_u_lat_u[i] = 0;
1926                 ts->io_u_lat_m[i] = 0;
1927                 ts->total_submit = 0;
1928                 ts->total_complete = 0;
1929         }
1930
1931         for (i = 0; i < 3; i++) {
1932                 ts->total_io_u[i] = 0;
1933                 ts->short_io_u[i] = 0;
1934                 ts->drop_io_u[i] = 0;
1935         }
1936 }
1937
1938 static void _add_stat_to_log(struct io_log *iolog, unsigned long elapsed)
1939 {
1940         /*
1941          * Note an entry in the log. Use the mean from the logged samples,
1942          * making sure to properly round up. Only write a log entry if we
1943          * had actual samples done.
1944          */
1945         if (iolog->avg_window[DDIR_READ].samples) {
1946                 unsigned long mr;
1947
1948                 mr = iolog->avg_window[DDIR_READ].mean.u.f + 0.50;
1949                 __add_log_sample(iolog, mr, DDIR_READ, 0, elapsed, 0);
1950         }
1951         if (iolog->avg_window[DDIR_WRITE].samples) {
1952                 unsigned long mw;
1953
1954                 mw = iolog->avg_window[DDIR_WRITE].mean.u.f + 0.50;
1955                 __add_log_sample(iolog, mw, DDIR_WRITE, 0, elapsed, 0);
1956         }
1957         if (iolog->avg_window[DDIR_TRIM].samples) {
1958                 unsigned long mw;
1959
1960                 mw = iolog->avg_window[DDIR_TRIM].mean.u.f + 0.50;
1961                 __add_log_sample(iolog, mw, DDIR_TRIM, 0, elapsed, 0);
1962         }
1963
1964         reset_io_stat(&iolog->avg_window[DDIR_READ]);
1965         reset_io_stat(&iolog->avg_window[DDIR_WRITE]);
1966         reset_io_stat(&iolog->avg_window[DDIR_TRIM]);
1967 }
1968
1969 static void add_log_sample(struct thread_data *td, struct io_log *iolog,
1970                            unsigned long val, enum fio_ddir ddir,
1971                            unsigned int bs, uint64_t offset)
1972 {
1973         unsigned long elapsed, this_window;
1974
1975         if (!ddir_rw(ddir))
1976                 return;
1977
1978         elapsed = mtime_since_now(&td->epoch);
1979
1980         /*
1981          * If no time averaging, just add the log sample.
1982          */
1983         if (!iolog->avg_msec) {
1984                 __add_log_sample(iolog, val, ddir, bs, elapsed, offset);
1985                 return;
1986         }
1987
1988         /*
1989          * Add the sample. If the time period has passed, then
1990          * add that entry to the log and clear.
1991          */
1992         add_stat_sample(&iolog->avg_window[ddir], val);
1993
1994         /*
1995          * If period hasn't passed, adding the above sample is all we
1996          * need to do.
1997          */
1998         this_window = elapsed - iolog->avg_last;
1999         if (this_window < iolog->avg_msec)
2000                 return;
2001
2002         _add_stat_to_log(iolog, elapsed);
2003
2004         iolog->avg_last = elapsed;
2005 }
2006
2007 void finalize_logs(struct thread_data *td)
2008 {
2009         unsigned long elapsed;
2010
2011         elapsed = mtime_since_now(&td->epoch);
2012
2013         if (td->clat_log)
2014                 _add_stat_to_log(td->clat_log, elapsed);
2015         if (td->slat_log)
2016                 _add_stat_to_log(td->slat_log, elapsed);
2017         if (td->lat_log)
2018                 _add_stat_to_log(td->lat_log, elapsed);
2019         if (td->bw_log)
2020                 _add_stat_to_log(td->bw_log, elapsed);
2021         if (td->iops_log)
2022                 _add_stat_to_log(td->iops_log, elapsed);
2023 }
2024
2025 void add_agg_sample(unsigned long val, enum fio_ddir ddir, unsigned int bs)
2026 {
2027         struct io_log *iolog;
2028
2029         if (!ddir_rw(ddir))
2030                 return;
2031
2032         iolog = agg_io_log[ddir];
2033         __add_log_sample(iolog, val, ddir, bs, mtime_since_genesis(), 0);
2034 }
2035
2036 static void add_clat_percentile_sample(struct thread_stat *ts,
2037                                 unsigned long usec, enum fio_ddir ddir)
2038 {
2039         unsigned int idx = plat_val_to_idx(usec);
2040         assert(idx < FIO_IO_U_PLAT_NR);
2041
2042         ts->io_u_plat[ddir][idx]++;
2043 }
2044
2045 void add_clat_sample(struct thread_data *td, enum fio_ddir ddir,
2046                      unsigned long usec, unsigned int bs, uint64_t offset)
2047 {
2048         struct thread_stat *ts = &td->ts;
2049
2050         if (!ddir_rw(ddir))
2051                 return;
2052
2053         td_io_u_lock(td);
2054
2055         add_stat_sample(&ts->clat_stat[ddir], usec);
2056
2057         if (td->clat_log)
2058                 add_log_sample(td, td->clat_log, usec, ddir, bs, offset);
2059
2060         if (ts->clat_percentiles)
2061                 add_clat_percentile_sample(ts, usec, ddir);
2062
2063         td_io_u_unlock(td);
2064 }
2065
2066 void add_slat_sample(struct thread_data *td, enum fio_ddir ddir,
2067                      unsigned long usec, unsigned int bs, uint64_t offset)
2068 {
2069         struct thread_stat *ts = &td->ts;
2070
2071         if (!ddir_rw(ddir))
2072                 return;
2073
2074         td_io_u_lock(td);
2075
2076         add_stat_sample(&ts->slat_stat[ddir], usec);
2077
2078         if (td->slat_log)
2079                 add_log_sample(td, td->slat_log, usec, ddir, bs, offset);
2080
2081         td_io_u_unlock(td);
2082 }
2083
2084 void add_lat_sample(struct thread_data *td, enum fio_ddir ddir,
2085                     unsigned long usec, unsigned int bs, uint64_t offset)
2086 {
2087         struct thread_stat *ts = &td->ts;
2088
2089         if (!ddir_rw(ddir))
2090                 return;
2091
2092         td_io_u_lock(td);
2093
2094         add_stat_sample(&ts->lat_stat[ddir], usec);
2095
2096         if (td->lat_log)
2097                 add_log_sample(td, td->lat_log, usec, ddir, bs, offset);
2098
2099         td_io_u_unlock(td);
2100 }
2101
2102 void add_bw_sample(struct thread_data *td, enum fio_ddir ddir, unsigned int bs,
2103                    struct timeval *t)
2104 {
2105         struct thread_stat *ts = &td->ts;
2106         unsigned long spent, rate;
2107
2108         if (!ddir_rw(ddir))
2109                 return;
2110
2111         spent = mtime_since(&td->bw_sample_time, t);
2112         if (spent < td->o.bw_avg_time)
2113                 return;
2114
2115         td_io_u_lock(td);
2116
2117         /*
2118          * Compute both read and write rates for the interval.
2119          */
2120         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++) {
2121                 uint64_t delta;
2122
2123                 delta = td->this_io_bytes[ddir] - td->stat_io_bytes[ddir];
2124                 if (!delta)
2125                         continue; /* No entries for interval */
2126
2127                 if (spent)
2128                         rate = delta * 1000 / spent / 1024;
2129                 else
2130                         rate = 0;
2131
2132                 add_stat_sample(&ts->bw_stat[ddir], rate);
2133
2134                 if (td->bw_log)
2135                         add_log_sample(td, td->bw_log, rate, ddir, bs, 0);
2136
2137                 td->stat_io_bytes[ddir] = td->this_io_bytes[ddir];
2138         }
2139
2140         fio_gettime(&td->bw_sample_time, NULL);
2141         td_io_u_unlock(td);
2142 }
2143
2144 void add_iops_sample(struct thread_data *td, enum fio_ddir ddir, unsigned int bs,
2145                      struct timeval *t)
2146 {
2147         struct thread_stat *ts = &td->ts;
2148         unsigned long spent, iops;
2149
2150         if (!ddir_rw(ddir))
2151                 return;
2152
2153         spent = mtime_since(&td->iops_sample_time, t);
2154         if (spent < td->o.iops_avg_time)
2155                 return;
2156
2157         td_io_u_lock(td);
2158
2159         /*
2160          * Compute both read and write rates for the interval.
2161          */
2162         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++) {
2163                 uint64_t delta;
2164
2165                 delta = td->this_io_blocks[ddir] - td->stat_io_blocks[ddir];
2166                 if (!delta)
2167                         continue; /* No entries for interval */
2168
2169                 if (spent)
2170                         iops = (delta * 1000) / spent;
2171                 else
2172                         iops = 0;
2173
2174                 add_stat_sample(&ts->iops_stat[ddir], iops);
2175
2176                 if (td->iops_log)
2177                         add_log_sample(td, td->iops_log, iops, ddir, bs, 0);
2178
2179                 td->stat_io_blocks[ddir] = td->this_io_blocks[ddir];
2180         }
2181
2182         fio_gettime(&td->iops_sample_time, NULL);
2183         td_io_u_unlock(td);
2184 }
2185
2186 void stat_init(void)
2187 {
2188         stat_mutex = fio_mutex_init(FIO_MUTEX_UNLOCKED);
2189 }
2190
2191 void stat_exit(void)
2192 {
2193         /*
2194          * When we have the mutex, we know out-of-band access to it
2195          * have ended.
2196          */
2197         fio_mutex_down(stat_mutex);
2198         fio_mutex_remove(stat_mutex);
2199 }
2200
2201 /*
2202  * Called from signal handler. Wake up status thread.
2203  */
2204 void show_running_run_stats(void)
2205 {
2206         helper_do_stat = 1;
2207         pthread_cond_signal(&helper_cond);
2208 }
2209
2210 uint32_t *io_u_block_info(struct thread_data *td, struct io_u *io_u)
2211 {
2212         /* Ignore io_u's which span multiple blocks--they will just get
2213          * inaccurate counts. */
2214         int idx = (io_u->offset - io_u->file->file_offset)
2215                         / td->o.bs[DDIR_TRIM];
2216         uint32_t *info = &td->ts.block_infos[idx];
2217         assert(idx < td->ts.nr_block_infos);
2218         return info;
2219 }