core: Removing duplicated code
[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
17 static struct fio_mutex *stat_mutex;
18
19 void update_rusage_stat(struct thread_data *td)
20 {
21         struct thread_stat *ts = &td->ts;
22
23         fio_getrusage(&td->ru_end);
24         ts->usr_time += mtime_since(&td->ru_start.ru_utime,
25                                         &td->ru_end.ru_utime);
26         ts->sys_time += mtime_since(&td->ru_start.ru_stime,
27                                         &td->ru_end.ru_stime);
28         ts->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw
29                         - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
30         ts->minf += td->ru_end.ru_minflt - td->ru_start.ru_minflt;
31         ts->majf += td->ru_end.ru_majflt - td->ru_start.ru_majflt;
32
33         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
34 }
35
36 /*
37  * Given a latency, return the index of the corresponding bucket in
38  * the structure tracking percentiles.
39  *
40  * (1) find the group (and error bits) that the value (latency)
41  * belongs to by looking at its MSB. (2) find the bucket number in the
42  * group by looking at the index bits.
43  *
44  */
45 static unsigned int plat_val_to_idx(unsigned int val)
46 {
47         unsigned int msb, error_bits, base, offset, idx;
48
49         /* Find MSB starting from bit 0 */
50         if (val == 0)
51                 msb = 0;
52         else
53                 msb = (sizeof(val)*8) - __builtin_clz(val) - 1;
54
55         /*
56          * MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
57          * all bits of the sample as index
58          */
59         if (msb <= FIO_IO_U_PLAT_BITS)
60                 return val;
61
62         /* Compute the number of error bits to discard*/
63         error_bits = msb - FIO_IO_U_PLAT_BITS;
64
65         /* Compute the number of buckets before the group */
66         base = (error_bits + 1) << FIO_IO_U_PLAT_BITS;
67
68         /*
69          * Discard the error bits and apply the mask to find the
70          * index for the buckets in the group
71          */
72         offset = (FIO_IO_U_PLAT_VAL - 1) & (val >> error_bits);
73
74         /* Make sure the index does not exceed (array size - 1) */
75         idx = (base + offset) < (FIO_IO_U_PLAT_NR - 1) ?
76                 (base + offset) : (FIO_IO_U_PLAT_NR - 1);
77
78         return idx;
79 }
80
81 /*
82  * Convert the given index of the bucket array to the value
83  * represented by the bucket
84  */
85 static unsigned int plat_idx_to_val(unsigned int idx)
86 {
87         unsigned int error_bits, k, base;
88
89         assert(idx < FIO_IO_U_PLAT_NR);
90
91         /* MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
92          * all bits of the sample as index */
93         if (idx < (FIO_IO_U_PLAT_VAL << 1))
94                 return idx;
95
96         /* Find the group and compute the minimum value of that group */
97         error_bits = (idx >> FIO_IO_U_PLAT_BITS) - 1;
98         base = 1 << (error_bits + FIO_IO_U_PLAT_BITS);
99
100         /* Find its bucket number of the group */
101         k = idx % FIO_IO_U_PLAT_VAL;
102
103         /* Return the mean of the range of the bucket */
104         return base + ((k + 0.5) * (1 << error_bits));
105 }
106
107 static int double_cmp(const void *a, const void *b)
108 {
109         const fio_fp64_t fa = *(const fio_fp64_t *) a;
110         const fio_fp64_t fb = *(const fio_fp64_t *) b;
111         int cmp = 0;
112
113         if (fa.u.f > fb.u.f)
114                 cmp = 1;
115         else if (fa.u.f < fb.u.f)
116                 cmp = -1;
117
118         return cmp;
119 }
120
121 unsigned int calc_clat_percentiles(unsigned int *io_u_plat, unsigned long nr,
122                                    fio_fp64_t *plist, unsigned int **output,
123                                    unsigned int *maxv, unsigned int *minv)
124 {
125         unsigned long sum = 0;
126         unsigned int len, i, j = 0;
127         unsigned int oval_len = 0;
128         unsigned int *ovals = NULL;
129         int is_last;
130
131         *minv = -1U;
132         *maxv = 0;
133
134         len = 0;
135         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
136                 len++;
137
138         if (!len)
139                 return 0;
140
141         /*
142          * Sort the percentile list. Note that it may already be sorted if
143          * we are using the default values, but since it's a short list this
144          * isn't a worry. Also note that this does not work for NaN values.
145          */
146         if (len > 1)
147                 qsort((void *)plist, len, sizeof(plist[0]), double_cmp);
148
149         /*
150          * Calculate bucket values, note down max and min values
151          */
152         is_last = 0;
153         for (i = 0; i < FIO_IO_U_PLAT_NR && !is_last; i++) {
154                 sum += io_u_plat[i];
155                 while (sum >= (plist[j].u.f / 100.0 * nr)) {
156                         assert(plist[j].u.f <= 100.0);
157
158                         if (j == oval_len) {
159                                 oval_len += 100;
160                                 ovals = realloc(ovals, oval_len * sizeof(unsigned int));
161                         }
162
163                         ovals[j] = plat_idx_to_val(i);
164                         if (ovals[j] < *minv)
165                                 *minv = ovals[j];
166                         if (ovals[j] > *maxv)
167                                 *maxv = ovals[j];
168
169                         is_last = (j == len - 1);
170                         if (is_last)
171                                 break;
172
173                         j++;
174                 }
175         }
176
177         *output = ovals;
178         return len;
179 }
180
181 /*
182  * Find and display the p-th percentile of clat
183  */
184 static void show_clat_percentiles(unsigned int *io_u_plat, unsigned long nr,
185                                   fio_fp64_t *plist, unsigned int precision)
186 {
187         unsigned int len, j = 0, minv, maxv;
188         unsigned int *ovals;
189         int is_last, per_line, scale_down;
190         char fmt[32];
191
192         len = calc_clat_percentiles(io_u_plat, nr, plist, &ovals, &maxv, &minv);
193         if (!len)
194                 goto out;
195
196         /*
197          * We default to usecs, but if the value range is such that we
198          * should scale down to msecs, do that.
199          */
200         if (minv > 2000 && maxv > 99999) {
201                 scale_down = 1;
202                 log_info("    clat percentiles (msec):\n     |");
203         } else {
204                 scale_down = 0;
205                 log_info("    clat percentiles (usec):\n     |");
206         }
207
208         snprintf(fmt, sizeof(fmt), "%%1.%uf", precision);
209         per_line = (80 - 7) / (precision + 14);
210
211         for (j = 0; j < len; j++) {
212                 char fbuf[16], *ptr = fbuf;
213
214                 /* for formatting */
215                 if (j != 0 && (j % per_line) == 0)
216                         log_info("     |");
217
218                 /* end of the list */
219                 is_last = (j == len - 1);
220
221                 if (plist[j].u.f < 10.0)
222                         ptr += sprintf(fbuf, " ");
223
224                 snprintf(ptr, sizeof(fbuf), fmt, plist[j].u.f);
225
226                 if (scale_down)
227                         ovals[j] = (ovals[j] + 999) / 1000;
228
229                 log_info(" %sth=[%5u]%c", fbuf, ovals[j], is_last ? '\n' : ',');
230
231                 if (is_last)
232                         break;
233
234                 if ((j % per_line) == per_line - 1)     /* for formatting */
235                         log_info("\n");
236         }
237
238 out:
239         if (ovals)
240                 free(ovals);
241 }
242
243 int calc_lat(struct io_stat *is, unsigned long *min, unsigned long *max,
244              double *mean, double *dev)
245 {
246         double n = (double) is->samples;
247
248         if (n == 0)
249                 return 0;
250
251         *min = is->min_val;
252         *max = is->max_val;
253         *mean = is->mean.u.f;
254
255         if (n > 1.0)
256                 *dev = sqrt(is->S.u.f / (n - 1.0));
257         else
258                 *dev = 0;
259
260         return 1;
261 }
262
263 void show_group_stats(struct group_run_stats *rs)
264 {
265         char *p1, *p2, *p3, *p4;
266         const char *ddir_str[] = { "   READ", "  WRITE" , "   TRIM"};
267         int i;
268
269         log_info("\nRun status group %d (all jobs):\n", rs->groupid);
270
271         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
272                 const int i2p = is_power_of_2(rs->kb_base);
273
274                 if (!rs->max_run[i])
275                         continue;
276
277                 p1 = num2str(rs->io_kb[i], 6, rs->kb_base, i2p, 8);
278                 p2 = num2str(rs->agg[i], 6, rs->kb_base, i2p, rs->unit_base);
279                 p3 = num2str(rs->min_bw[i], 6, rs->kb_base, i2p, rs->unit_base);
280                 p4 = num2str(rs->max_bw[i], 6, rs->kb_base, i2p, rs->unit_base);
281
282                 log_info("%s: io=%s, aggrb=%s/s, minb=%s/s, maxb=%s/s,"
283                          " mint=%llumsec, maxt=%llumsec\n",
284                                 rs->unified_rw_rep ? "  MIXED" : ddir_str[i],
285                                 p1, p2, p3, p4,
286                                 (unsigned long long) rs->min_run[i],
287                                 (unsigned long long) rs->max_run[i]);
288
289                 free(p1);
290                 free(p2);
291                 free(p3);
292                 free(p4);
293         }
294 }
295
296 void stat_calc_dist(unsigned int *map, unsigned long total, double *io_u_dist)
297 {
298         int i;
299
300         /*
301          * Do depth distribution calculations
302          */
303         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
304                 if (total) {
305                         io_u_dist[i] = (double) map[i] / (double) total;
306                         io_u_dist[i] *= 100.0;
307                         if (io_u_dist[i] < 0.1 && map[i])
308                                 io_u_dist[i] = 0.1;
309                 } else
310                         io_u_dist[i] = 0.0;
311         }
312 }
313
314 static void stat_calc_lat(struct thread_stat *ts, double *dst,
315                           unsigned int *src, int nr)
316 {
317         unsigned long total = ddir_rw_sum(ts->total_io_u);
318         int i;
319
320         /*
321          * Do latency distribution calculations
322          */
323         for (i = 0; i < nr; i++) {
324                 if (total) {
325                         dst[i] = (double) src[i] / (double) total;
326                         dst[i] *= 100.0;
327                         if (dst[i] < 0.01 && src[i])
328                                 dst[i] = 0.01;
329                 } else
330                         dst[i] = 0.0;
331         }
332 }
333
334 void stat_calc_lat_u(struct thread_stat *ts, double *io_u_lat)
335 {
336         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
337 }
338
339 void stat_calc_lat_m(struct thread_stat *ts, double *io_u_lat)
340 {
341         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_m, FIO_IO_U_LAT_M_NR);
342 }
343
344 static void display_lat(const char *name, unsigned long min, unsigned long max,
345                         double mean, double dev)
346 {
347         const char *base = "(usec)";
348         char *minp, *maxp;
349
350         if (!usec_to_msec(&min, &max, &mean, &dev))
351                 base = "(msec)";
352
353         minp = num2str(min, 6, 1, 0, 0);
354         maxp = num2str(max, 6, 1, 0, 0);
355
356         log_info("    %s %s: min=%s, max=%s, avg=%5.02f,"
357                  " stdev=%5.02f\n", name, base, minp, maxp, mean, dev);
358
359         free(minp);
360         free(maxp);
361 }
362
363 static void show_ddir_status(struct group_run_stats *rs, struct thread_stat *ts,
364                              int ddir)
365 {
366         const char *ddir_str[] = { "read ", "write", "trim" };
367         unsigned long min, max, runt;
368         unsigned long long bw, iops;
369         double mean, dev;
370         char *io_p, *bw_p, *iops_p;
371         int i2p;
372
373         assert(ddir_rw(ddir));
374
375         if (!ts->runtime[ddir])
376                 return;
377
378         i2p = is_power_of_2(rs->kb_base);
379         runt = ts->runtime[ddir];
380
381         bw = (1000 * ts->io_bytes[ddir]) / runt;
382         io_p = num2str(ts->io_bytes[ddir], 6, 1, i2p, 8);
383         bw_p = num2str(bw, 6, 1, i2p, ts->unit_base);
384
385         iops = (1000 * (uint64_t)ts->total_io_u[ddir]) / runt;
386         iops_p = num2str(iops, 6, 1, 0, 0);
387
388         log_info("  %s: io=%s, bw=%s/s, iops=%s, runt=%6llumsec\n",
389                                 rs->unified_rw_rep ? "mixed" : ddir_str[ddir],
390                                 io_p, bw_p, iops_p,
391                                 (unsigned long long) ts->runtime[ddir]);
392
393         free(io_p);
394         free(bw_p);
395         free(iops_p);
396
397         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
398                 display_lat("slat", min, max, mean, dev);
399         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
400                 display_lat("clat", min, max, mean, dev);
401         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
402                 display_lat(" lat", min, max, mean, dev);
403
404         if (ts->clat_percentiles) {
405                 show_clat_percentiles(ts->io_u_plat[ddir],
406                                         ts->clat_stat[ddir].samples,
407                                         ts->percentile_list,
408                                         ts->percentile_precision);
409         }
410         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
411                 double p_of_agg = 100.0, fkb_base = (double)rs->kb_base;
412                 const char *bw_str = (rs->unit_base == 1 ? "Kbit" : "KB");
413
414                 if (rs->unit_base == 1) {
415                         min *= 8.0;
416                         max *= 8.0;
417                         mean *= 8.0;
418                         dev *= 8.0;
419                 }
420
421                 if (rs->agg[ddir]) {
422                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
423                         if (p_of_agg > 100.0)
424                                 p_of_agg = 100.0;
425                 }
426
427                 if (mean > fkb_base * fkb_base) {
428                         min /= fkb_base;
429                         max /= fkb_base;
430                         mean /= fkb_base;
431                         dev /= fkb_base;
432                         bw_str = (rs->unit_base == 1 ? "Mbit" : "MB");
433                 }
434
435                 log_info("    bw (%-4s/s): min=%5lu, max=%5lu, per=%3.2f%%,"
436                          " avg=%5.02f, stdev=%5.02f\n", bw_str, min, max,
437                                                         p_of_agg, mean, dev);
438         }
439 }
440
441 static int show_lat(double *io_u_lat, int nr, const char **ranges,
442                     const char *msg)
443 {
444         int new_line = 1, i, line = 0, shown = 0;
445
446         for (i = 0; i < nr; i++) {
447                 if (io_u_lat[i] <= 0.0)
448                         continue;
449                 shown = 1;
450                 if (new_line) {
451                         if (line)
452                                 log_info("\n");
453                         log_info("    lat (%s) : ", msg);
454                         new_line = 0;
455                         line = 0;
456                 }
457                 if (line)
458                         log_info(", ");
459                 log_info("%s%3.2f%%", ranges[i], io_u_lat[i]);
460                 line++;
461                 if (line == 5)
462                         new_line = 1;
463         }
464
465         if (shown)
466                 log_info("\n");
467
468         return shown;
469 }
470
471 static void show_lat_u(double *io_u_lat_u)
472 {
473         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
474                                  "250=", "500=", "750=", "1000=", };
475
476         show_lat(io_u_lat_u, FIO_IO_U_LAT_U_NR, ranges, "usec");
477 }
478
479 static void show_lat_m(double *io_u_lat_m)
480 {
481         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
482                                  "250=", "500=", "750=", "1000=", "2000=",
483                                  ">=2000=", };
484
485         show_lat(io_u_lat_m, FIO_IO_U_LAT_M_NR, ranges, "msec");
486 }
487
488 static void show_latencies(struct thread_stat *ts)
489 {
490         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
491         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
492
493         stat_calc_lat_u(ts, io_u_lat_u);
494         stat_calc_lat_m(ts, io_u_lat_m);
495
496         show_lat_u(io_u_lat_u);
497         show_lat_m(io_u_lat_m);
498 }
499
500 void show_thread_status(struct thread_stat *ts, struct group_run_stats *rs)
501 {
502         double usr_cpu, sys_cpu;
503         unsigned long runtime;
504         double io_u_dist[FIO_IO_U_MAP_NR];
505         time_t time_p;
506         char time_buf[64];
507
508         if (!(ts->io_bytes[DDIR_READ] + ts->io_bytes[DDIR_WRITE] +
509             ts->io_bytes[DDIR_TRIM]) && !(ts->total_io_u[DDIR_READ] +
510             ts->total_io_u[DDIR_WRITE] + ts->total_io_u[DDIR_TRIM]))
511                 return;
512
513         time(&time_p);
514         os_ctime_r((const time_t *) &time_p, time_buf, sizeof(time_buf));
515
516         if (!ts->error) {
517                 log_info("%s: (groupid=%d, jobs=%d): err=%2d: pid=%d: %s",
518                                         ts->name, ts->groupid, ts->members,
519                                         ts->error, (int) ts->pid, time_buf);
520         } else {
521                 log_info("%s: (groupid=%d, jobs=%d): err=%2d (%s): pid=%d: %s",
522                                         ts->name, ts->groupid, ts->members,
523                                         ts->error, ts->verror, (int) ts->pid,
524                                         time_buf);
525         }
526
527         if (strlen(ts->description))
528                 log_info("  Description  : [%s]\n", ts->description);
529
530         if (ts->io_bytes[DDIR_READ])
531                 show_ddir_status(rs, ts, DDIR_READ);
532         if (ts->io_bytes[DDIR_WRITE])
533                 show_ddir_status(rs, ts, DDIR_WRITE);
534         if (ts->io_bytes[DDIR_TRIM])
535                 show_ddir_status(rs, ts, DDIR_TRIM);
536
537         show_latencies(ts);
538
539         runtime = ts->total_run_time;
540         if (runtime) {
541                 double runt = (double) runtime;
542
543                 usr_cpu = (double) ts->usr_time * 100 / runt;
544                 sys_cpu = (double) ts->sys_time * 100 / runt;
545         } else {
546                 usr_cpu = 0;
547                 sys_cpu = 0;
548         }
549
550         log_info("  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%llu,"
551                  " majf=%llu, minf=%llu\n", usr_cpu, sys_cpu,
552                         (unsigned long long) ts->ctx,
553                         (unsigned long long) ts->majf,
554                         (unsigned long long) ts->minf);
555
556         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
557         log_info("  IO depths    : 1=%3.1f%%, 2=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%,"
558                  " 16=%3.1f%%, 32=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
559                                         io_u_dist[1], io_u_dist[2],
560                                         io_u_dist[3], io_u_dist[4],
561                                         io_u_dist[5], io_u_dist[6]);
562
563         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
564         log_info("     submit    : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
565                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
566                                         io_u_dist[1], io_u_dist[2],
567                                         io_u_dist[3], io_u_dist[4],
568                                         io_u_dist[5], io_u_dist[6]);
569         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
570         log_info("     complete  : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
571                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
572                                         io_u_dist[1], io_u_dist[2],
573                                         io_u_dist[3], io_u_dist[4],
574                                         io_u_dist[5], io_u_dist[6]);
575         log_info("     issued    : total=r=%llu/w=%llu/d=%llu,"
576                                  " short=r=%llu/w=%llu/d=%llu\n",
577                                         (unsigned long long) ts->total_io_u[0],
578                                         (unsigned long long) ts->total_io_u[1],
579                                         (unsigned long long) ts->total_io_u[2],
580                                         (unsigned long long) ts->short_io_u[0],
581                                         (unsigned long long) ts->short_io_u[1],
582                                         (unsigned long long) ts->short_io_u[2]);
583         if (ts->continue_on_error) {
584                 log_info("     errors    : total=%llu, first_error=%d/<%s>\n",
585                                         (unsigned long long)ts->total_err_count,
586                                         ts->first_error,
587                                         strerror(ts->first_error));
588         }
589 }
590
591 static void show_ddir_status_terse(struct thread_stat *ts,
592                                    struct group_run_stats *rs, int ddir)
593 {
594         unsigned long min, max;
595         unsigned long long bw, iops;
596         unsigned int *ovals = NULL;
597         double mean, dev;
598         unsigned int len, minv, maxv;
599         int i;
600
601         assert(ddir_rw(ddir));
602
603         iops = bw = 0;
604         if (ts->runtime[ddir]) {
605                 uint64_t runt = ts->runtime[ddir];
606
607                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024;
608                 iops = (1000 * (uint64_t) ts->total_io_u[ddir]) / runt;
609         }
610
611         log_info(";%llu;%llu;%llu;%llu",
612                 (unsigned long long) ts->io_bytes[ddir] >> 10, bw, iops,
613                                         (unsigned long long) ts->runtime[ddir]);
614
615         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
616                 log_info(";%lu;%lu;%f;%f", min, max, mean, dev);
617         else
618                 log_info(";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
619
620         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
621                 log_info(";%lu;%lu;%f;%f", min, max, mean, dev);
622         else
623                 log_info(";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
624
625         if (ts->clat_percentiles) {
626                 len = calc_clat_percentiles(ts->io_u_plat[ddir],
627                                         ts->clat_stat[ddir].samples,
628                                         ts->percentile_list, &ovals, &maxv,
629                                         &minv);
630         } else
631                 len = 0;
632
633         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
634                 if (i >= len) {
635                         log_info(";0%%=0");
636                         continue;
637                 }
638                 log_info(";%f%%=%u", ts->percentile_list[i].u.f, ovals[i]);
639         }
640
641         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
642                 log_info(";%lu;%lu;%f;%f", min, max, mean, dev);
643         else
644                 log_info(";%lu;%lu;%f;%f", 0UL, 0UL, 0.0, 0.0);
645
646         if (ovals)
647                 free(ovals);
648
649         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
650                 double p_of_agg = 100.0;
651
652                 if (rs->agg[ddir]) {
653                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
654                         if (p_of_agg > 100.0)
655                                 p_of_agg = 100.0;
656                 }
657
658                 log_info(";%lu;%lu;%f%%;%f;%f", min, max, p_of_agg, mean, dev);
659         } else
660                 log_info(";%lu;%lu;%f%%;%f;%f", 0UL, 0UL, 0.0, 0.0, 0.0);
661 }
662
663 static void add_ddir_status_json(struct thread_stat *ts,
664                 struct group_run_stats *rs, int ddir, struct json_object *parent)
665 {
666         unsigned long min, max;
667         unsigned long long bw, iops;
668         unsigned int *ovals = NULL;
669         double mean, dev;
670         unsigned int len, minv, maxv;
671         int i;
672         const char *ddirname[] = {"read", "write", "trim"};
673         struct json_object *dir_object, *tmp_object, *percentile_object;
674         char buf[120];
675         double p_of_agg = 100.0;
676
677         assert(ddir_rw(ddir));
678
679         if (ts->unified_rw_rep && ddir != DDIR_READ)
680                 return;
681
682         dir_object = json_create_object();
683         json_object_add_value_object(parent,
684                 ts->unified_rw_rep ? "mixed" : ddirname[ddir], dir_object);
685
686         iops = bw = 0;
687         if (ts->runtime[ddir]) {
688                 uint64_t runt = ts->runtime[ddir];
689
690                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024;
691                 iops = (1000 * (uint64_t) ts->total_io_u[ddir]) / runt;
692         }
693
694         json_object_add_value_int(dir_object, "io_bytes", ts->io_bytes[ddir] >> 10);
695         json_object_add_value_int(dir_object, "bw", bw);
696         json_object_add_value_int(dir_object, "iops", iops);
697         json_object_add_value_int(dir_object, "runtime", ts->runtime[ddir]);
698
699         if (!calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev)) {
700                 min = max = 0;
701                 mean = dev = 0.0;
702         }
703         tmp_object = json_create_object();
704         json_object_add_value_object(dir_object, "slat", tmp_object);
705         json_object_add_value_int(tmp_object, "min", min);
706         json_object_add_value_int(tmp_object, "max", max);
707         json_object_add_value_float(tmp_object, "mean", mean);
708         json_object_add_value_float(tmp_object, "stddev", dev);
709
710         if (!calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev)) {
711                 min = max = 0;
712                 mean = dev = 0.0;
713         }
714         tmp_object = json_create_object();
715         json_object_add_value_object(dir_object, "clat", tmp_object);
716         json_object_add_value_int(tmp_object, "min", min);
717         json_object_add_value_int(tmp_object, "max", max);
718         json_object_add_value_float(tmp_object, "mean", mean);
719         json_object_add_value_float(tmp_object, "stddev", dev);
720
721         if (ts->clat_percentiles) {
722                 len = calc_clat_percentiles(ts->io_u_plat[ddir],
723                                         ts->clat_stat[ddir].samples,
724                                         ts->percentile_list, &ovals, &maxv,
725                                         &minv);
726         } else
727                 len = 0;
728
729         percentile_object = json_create_object();
730         json_object_add_value_object(tmp_object, "percentile", percentile_object);
731         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
732                 if (i >= len) {
733                         json_object_add_value_int(percentile_object, "0.00", 0);
734                         continue;
735                 }
736                 snprintf(buf, sizeof(buf), "%f", ts->percentile_list[i].u.f);
737                 json_object_add_value_int(percentile_object, (const char *)buf, ovals[i]);
738         }
739
740         if (!calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev)) {
741                 min = max = 0;
742                 mean = dev = 0.0;
743         }
744         tmp_object = json_create_object();
745         json_object_add_value_object(dir_object, "lat", tmp_object);
746         json_object_add_value_int(tmp_object, "min", min);
747         json_object_add_value_int(tmp_object, "max", max);
748         json_object_add_value_float(tmp_object, "mean", mean);
749         json_object_add_value_float(tmp_object, "stddev", dev);
750         if (ovals)
751                 free(ovals);
752
753         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
754                 if (rs->agg[ddir]) {
755                         p_of_agg = mean * 100 / (double) rs->agg[ddir];
756                         if (p_of_agg > 100.0)
757                                 p_of_agg = 100.0;
758                 }
759         } else {
760                 min = max = 0;
761                 p_of_agg = mean = dev = 0.0;
762         }
763         json_object_add_value_int(dir_object, "bw_min", min);
764         json_object_add_value_int(dir_object, "bw_max", max);
765         json_object_add_value_float(dir_object, "bw_agg", mean);
766         json_object_add_value_float(dir_object, "bw_mean", mean);
767         json_object_add_value_float(dir_object, "bw_dev", dev);
768 }
769
770 static void show_thread_status_terse_v2(struct thread_stat *ts,
771                                         struct group_run_stats *rs)
772 {
773         double io_u_dist[FIO_IO_U_MAP_NR];
774         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
775         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
776         double usr_cpu, sys_cpu;
777         int i;
778
779         /* General Info */
780         log_info("2;%s;%d;%d", ts->name, ts->groupid, ts->error);
781         /* Log Read Status */
782         show_ddir_status_terse(ts, rs, DDIR_READ);
783         /* Log Write Status */
784         show_ddir_status_terse(ts, rs, DDIR_WRITE);
785         /* Log Trim Status */
786         show_ddir_status_terse(ts, rs, DDIR_TRIM);
787
788         /* CPU Usage */
789         if (ts->total_run_time) {
790                 double runt = (double) ts->total_run_time;
791
792                 usr_cpu = (double) ts->usr_time * 100 / runt;
793                 sys_cpu = (double) ts->sys_time * 100 / runt;
794         } else {
795                 usr_cpu = 0;
796                 sys_cpu = 0;
797         }
798
799         log_info(";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
800                                                 (unsigned long long) ts->ctx,
801                                                 (unsigned long long) ts->majf,
802                                                 (unsigned long long) ts->minf);
803
804         /* Calc % distribution of IO depths, usecond, msecond latency */
805         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
806         stat_calc_lat_u(ts, io_u_lat_u);
807         stat_calc_lat_m(ts, io_u_lat_m);
808
809         /* Only show fixed 7 I/O depth levels*/
810         log_info(";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
811                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
812                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
813
814         /* Microsecond latency */
815         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
816                 log_info(";%3.2f%%", io_u_lat_u[i]);
817         /* Millisecond latency */
818         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
819                 log_info(";%3.2f%%", io_u_lat_m[i]);
820         /* Additional output if continue_on_error set - default off*/
821         if (ts->continue_on_error)
822                 log_info(";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
823         log_info("\n");
824
825         /* Additional output if description is set */
826         if (ts->description)
827                 log_info(";%s", ts->description);
828
829         log_info("\n");
830 }
831
832 static void show_thread_status_terse_v3_v4(struct thread_stat *ts,
833                                            struct group_run_stats *rs, int ver)
834 {
835         double io_u_dist[FIO_IO_U_MAP_NR];
836         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
837         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
838         double usr_cpu, sys_cpu;
839         int i;
840
841         /* General Info */
842         log_info("%d;%s;%s;%d;%d", ver, fio_version_string,
843                                         ts->name, ts->groupid, ts->error);
844         /* Log Read Status */
845         show_ddir_status_terse(ts, rs, DDIR_READ);
846         /* Log Write Status */
847         show_ddir_status_terse(ts, rs, DDIR_WRITE);
848         /* Log Trim Status */
849         if (ver == 4)
850                 show_ddir_status_terse(ts, rs, DDIR_TRIM);
851
852         /* CPU Usage */
853         if (ts->total_run_time) {
854                 double runt = (double) ts->total_run_time;
855
856                 usr_cpu = (double) ts->usr_time * 100 / runt;
857                 sys_cpu = (double) ts->sys_time * 100 / runt;
858         } else {
859                 usr_cpu = 0;
860                 sys_cpu = 0;
861         }
862
863         log_info(";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
864                                                 (unsigned long long) ts->ctx,
865                                                 (unsigned long long) ts->majf,
866                                                 (unsigned long long) ts->minf);
867
868         /* Calc % distribution of IO depths, usecond, msecond latency */
869         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
870         stat_calc_lat_u(ts, io_u_lat_u);
871         stat_calc_lat_m(ts, io_u_lat_m);
872
873         /* Only show fixed 7 I/O depth levels*/
874         log_info(";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
875                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
876                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
877
878         /* Microsecond latency */
879         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
880                 log_info(";%3.2f%%", io_u_lat_u[i]);
881         /* Millisecond latency */
882         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
883                 log_info(";%3.2f%%", io_u_lat_m[i]);
884
885         /* disk util stats, if any */
886         show_disk_util(1, NULL);
887
888         /* Additional output if continue_on_error set - default off*/
889         if (ts->continue_on_error)
890                 log_info(";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
891
892         /* Additional output if description is set */
893         if (strlen(ts->description))
894                 log_info(";%s", ts->description);
895
896         log_info("\n");
897 }
898
899 static struct json_object *show_thread_status_json(struct thread_stat *ts,
900                                     struct group_run_stats *rs)
901 {
902         struct json_object *root, *tmp;
903         double io_u_dist[FIO_IO_U_MAP_NR];
904         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
905         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
906         double usr_cpu, sys_cpu;
907         int i;
908
909         root = json_create_object();
910         json_object_add_value_string(root, "jobname", ts->name);
911         json_object_add_value_int(root, "groupid", ts->groupid);
912         json_object_add_value_int(root, "error", ts->error);
913
914         add_ddir_status_json(ts, rs, DDIR_READ, root);
915         add_ddir_status_json(ts, rs, DDIR_WRITE, root);
916         add_ddir_status_json(ts, rs, DDIR_TRIM, root);
917
918         /* CPU Usage */
919         if (ts->total_run_time) {
920                 double runt = (double) ts->total_run_time;
921
922                 usr_cpu = (double) ts->usr_time * 100 / runt;
923                 sys_cpu = (double) ts->sys_time * 100 / runt;
924         } else {
925                 usr_cpu = 0;
926                 sys_cpu = 0;
927         }
928         json_object_add_value_float(root, "usr_cpu", usr_cpu);
929         json_object_add_value_float(root, "sys_cpu", sys_cpu);
930         json_object_add_value_int(root, "ctx", ts->ctx);
931         json_object_add_value_int(root, "majf", ts->majf);
932         json_object_add_value_int(root, "minf", ts->minf);
933
934
935         /* Calc % distribution of IO depths, usecond, msecond latency */
936         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
937         stat_calc_lat_u(ts, io_u_lat_u);
938         stat_calc_lat_m(ts, io_u_lat_m);
939
940         tmp = json_create_object();
941         json_object_add_value_object(root, "iodepth_level", tmp);
942         /* Only show fixed 7 I/O depth levels*/
943         for (i = 0; i < 7; i++) {
944                 char name[20];
945                 if (i < 6)
946                         snprintf(name, 20, "%d", 1 << i);
947                 else
948                         snprintf(name, 20, ">=%d", 1 << i);
949                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
950         }
951
952         tmp = json_create_object();
953         json_object_add_value_object(root, "latency_us", tmp);
954         /* Microsecond latency */
955         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++) {
956                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
957                                  "250", "500", "750", "1000", };
958                 json_object_add_value_float(tmp, ranges[i], io_u_lat_u[i]);
959         }
960         /* Millisecond latency */
961         tmp = json_create_object();
962         json_object_add_value_object(root, "latency_ms", tmp);
963         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++) {
964                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
965                                  "250", "500", "750", "1000", "2000",
966                                  ">=2000", };
967                 json_object_add_value_float(tmp, ranges[i], io_u_lat_m[i]);
968         }
969
970         /* Additional output if continue_on_error set - default off*/
971         if (ts->continue_on_error) {
972                 json_object_add_value_int(root, "total_err", ts->total_err_count);
973                 json_object_add_value_int(root, "total_err", ts->first_error);
974         }
975
976         /* Additional output if description is set */
977         if (strlen(ts->description))
978                 json_object_add_value_string(root, "desc", ts->description);
979
980         return root;
981 }
982
983 static void show_thread_status_terse(struct thread_stat *ts,
984                                      struct group_run_stats *rs)
985 {
986         if (terse_version == 2)
987                 show_thread_status_terse_v2(ts, rs);
988         else if (terse_version == 3 || terse_version == 4)
989                 show_thread_status_terse_v3_v4(ts, rs, terse_version);
990         else
991                 log_err("fio: bad terse version!? %d\n", terse_version);
992 }
993
994 static void sum_stat(struct io_stat *dst, struct io_stat *src, int nr)
995 {
996         double mean, S;
997
998         if (src->samples == 0)
999                 return;
1000
1001         dst->min_val = min(dst->min_val, src->min_val);
1002         dst->max_val = max(dst->max_val, src->max_val);
1003
1004         /*
1005          * Compute new mean and S after the merge
1006          * <http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
1007          *  #Parallel_algorithm>
1008          */
1009         if (nr == 1) {
1010                 mean = src->mean.u.f;
1011                 S = src->S.u.f;
1012         } else {
1013                 double delta = src->mean.u.f - dst->mean.u.f;
1014
1015                 mean = ((src->mean.u.f * src->samples) +
1016                         (dst->mean.u.f * dst->samples)) /
1017                         (dst->samples + src->samples);
1018
1019                 S =  src->S.u.f + dst->S.u.f + pow(delta, 2.0) *
1020                         (dst->samples * src->samples) /
1021                         (dst->samples + src->samples);
1022         }
1023
1024         dst->samples += src->samples;
1025         dst->mean.u.f = mean;
1026         dst->S.u.f = S;
1027 }
1028
1029 void sum_group_stats(struct group_run_stats *dst, struct group_run_stats *src)
1030 {
1031         int i;
1032
1033         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1034                 if (dst->max_run[i] < src->max_run[i])
1035                         dst->max_run[i] = src->max_run[i];
1036                 if (dst->min_run[i] && dst->min_run[i] > src->min_run[i])
1037                         dst->min_run[i] = src->min_run[i];
1038                 if (dst->max_bw[i] < src->max_bw[i])
1039                         dst->max_bw[i] = src->max_bw[i];
1040                 if (dst->min_bw[i] && dst->min_bw[i] > src->min_bw[i])
1041                         dst->min_bw[i] = src->min_bw[i];
1042
1043                 dst->io_kb[i] += src->io_kb[i];
1044                 dst->agg[i] += src->agg[i];
1045         }
1046
1047 }
1048
1049 void sum_thread_stats(struct thread_stat *dst, struct thread_stat *src, int nr)
1050 {
1051         int l, k;
1052
1053         for (l = 0; l < DDIR_RWDIR_CNT; l++) {
1054                 if (!dst->unified_rw_rep) {
1055                         sum_stat(&dst->clat_stat[l], &src->clat_stat[l], nr);
1056                         sum_stat(&dst->slat_stat[l], &src->slat_stat[l], nr);
1057                         sum_stat(&dst->lat_stat[l], &src->lat_stat[l], nr);
1058                         sum_stat(&dst->bw_stat[l], &src->bw_stat[l], nr);
1059
1060                         dst->io_bytes[l] += src->io_bytes[l];
1061
1062                         if (dst->runtime[l] < src->runtime[l])
1063                                 dst->runtime[l] = src->runtime[l];
1064                 } else {
1065                         sum_stat(&dst->clat_stat[0], &src->clat_stat[l], nr);
1066                         sum_stat(&dst->slat_stat[0], &src->slat_stat[l], nr);
1067                         sum_stat(&dst->lat_stat[0], &src->lat_stat[l], nr);
1068                         sum_stat(&dst->bw_stat[0], &src->bw_stat[l], nr);
1069
1070                         dst->io_bytes[0] += src->io_bytes[l];
1071
1072                         if (dst->runtime[0] < src->runtime[l])
1073                                 dst->runtime[0] = src->runtime[l];
1074                 }
1075         }
1076
1077         dst->usr_time += src->usr_time;
1078         dst->sys_time += src->sys_time;
1079         dst->ctx += src->ctx;
1080         dst->majf += src->majf;
1081         dst->minf += src->minf;
1082
1083         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1084                 dst->io_u_map[k] += src->io_u_map[k];
1085         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1086                 dst->io_u_submit[k] += src->io_u_submit[k];
1087         for (k = 0; k < FIO_IO_U_MAP_NR; k++)
1088                 dst->io_u_complete[k] += src->io_u_complete[k];
1089         for (k = 0; k < FIO_IO_U_LAT_U_NR; k++)
1090                 dst->io_u_lat_u[k] += src->io_u_lat_u[k];
1091         for (k = 0; k < FIO_IO_U_LAT_M_NR; k++)
1092                 dst->io_u_lat_m[k] += src->io_u_lat_m[k];
1093
1094         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1095                 if (!dst->unified_rw_rep) {
1096                         dst->total_io_u[k] += src->total_io_u[k];
1097                         dst->short_io_u[k] += src->short_io_u[k];
1098                 } else {
1099                         dst->total_io_u[0] += src->total_io_u[k];
1100                         dst->short_io_u[0] += src->short_io_u[k];
1101                 }
1102         }
1103
1104         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1105                 int m;
1106
1107                 for (m = 0; m < FIO_IO_U_PLAT_NR; m++) {
1108                         if (!dst->unified_rw_rep)
1109                                 dst->io_u_plat[k][m] += src->io_u_plat[k][m];
1110                         else
1111                                 dst->io_u_plat[0][m] += src->io_u_plat[k][m];
1112                 }
1113         }
1114
1115         dst->total_run_time += src->total_run_time;
1116         dst->total_submit += src->total_submit;
1117         dst->total_complete += src->total_complete;
1118 }
1119
1120 void init_group_run_stat(struct group_run_stats *gs)
1121 {
1122         int i;
1123         memset(gs, 0, sizeof(*gs));
1124
1125         for (i = 0; i < DDIR_RWDIR_CNT; i++)
1126                 gs->min_bw[i] = gs->min_run[i] = ~0UL;
1127 }
1128
1129 void init_thread_stat(struct thread_stat *ts)
1130 {
1131         int j;
1132
1133         memset(ts, 0, sizeof(*ts));
1134
1135         for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1136                 ts->lat_stat[j].min_val = -1UL;
1137                 ts->clat_stat[j].min_val = -1UL;
1138                 ts->slat_stat[j].min_val = -1UL;
1139                 ts->bw_stat[j].min_val = -1UL;
1140         }
1141         ts->groupid = -1;
1142 }
1143
1144 static void __show_run_stats(void)
1145 {
1146         struct group_run_stats *runstats, *rs;
1147         struct thread_data *td;
1148         struct thread_stat *threadstats, *ts;
1149         int i, j, nr_ts, last_ts, idx;
1150         int kb_base_warned = 0;
1151         int unit_base_warned = 0;
1152         struct json_object *root = NULL;
1153         struct json_array *array = NULL;
1154
1155         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
1156
1157         for (i = 0; i < groupid + 1; i++)
1158                 init_group_run_stat(&runstats[i]);
1159
1160         /*
1161          * find out how many threads stats we need. if group reporting isn't
1162          * enabled, it's one-per-td.
1163          */
1164         nr_ts = 0;
1165         last_ts = -1;
1166         for_each_td(td, i) {
1167                 if (!td->o.group_reporting) {
1168                         nr_ts++;
1169                         continue;
1170                 }
1171                 if (last_ts == td->groupid)
1172                         continue;
1173
1174                 last_ts = td->groupid;
1175                 nr_ts++;
1176         }
1177
1178         threadstats = malloc(nr_ts * sizeof(struct thread_stat));
1179
1180         for (i = 0; i < nr_ts; i++)
1181                 init_thread_stat(&threadstats[i]);
1182
1183         j = 0;
1184         last_ts = -1;
1185         idx = 0;
1186         for_each_td(td, i) {
1187                 if (idx && (!td->o.group_reporting ||
1188                     (td->o.group_reporting && last_ts != td->groupid))) {
1189                         idx = 0;
1190                         j++;
1191                 }
1192
1193                 last_ts = td->groupid;
1194
1195                 ts = &threadstats[j];
1196
1197                 ts->clat_percentiles = td->o.clat_percentiles;
1198                 ts->percentile_precision = td->o.percentile_precision;
1199                 memcpy(ts->percentile_list, td->o.percentile_list, sizeof(td->o.percentile_list));
1200
1201                 idx++;
1202                 ts->members++;
1203
1204                 if (ts->groupid == -1) {
1205                         /*
1206                          * These are per-group shared already
1207                          */
1208                         strncpy(ts->name, td->o.name, FIO_JOBNAME_SIZE);
1209                         if (td->o.description)
1210                                 strncpy(ts->description, td->o.description,
1211                                                 FIO_JOBNAME_SIZE);
1212                         else
1213                                 memset(ts->description, 0, FIO_JOBNAME_SIZE);
1214
1215                         /*
1216                          * If multiple entries in this group, this is
1217                          * the first member.
1218                          */
1219                         ts->thread_number = td->thread_number;
1220                         ts->groupid = td->groupid;
1221
1222                         /*
1223                          * first pid in group, not very useful...
1224                          */
1225                         ts->pid = td->pid;
1226
1227                         ts->kb_base = td->o.kb_base;
1228                         ts->unit_base = td->o.unit_base;
1229                         ts->unified_rw_rep = td->o.unified_rw_rep;
1230                 } else if (ts->kb_base != td->o.kb_base && !kb_base_warned) {
1231                         log_info("fio: kb_base differs for jobs in group, using"
1232                                  " %u as the base\n", ts->kb_base);
1233                         kb_base_warned = 1;
1234                 } else if (ts->unit_base != td->o.unit_base && !unit_base_warned) {
1235                         log_info("fio: unit_base differs for jobs in group, using"
1236                                  " %u as the base\n", ts->unit_base);
1237                         unit_base_warned = 1;
1238                 }
1239
1240                 ts->continue_on_error = td->o.continue_on_error;
1241                 ts->total_err_count += td->total_err_count;
1242                 ts->first_error = td->first_error;
1243                 if (!ts->error) {
1244                         if (!td->error && td->o.continue_on_error &&
1245                             td->first_error) {
1246                                 ts->error = td->first_error;
1247                                 strcpy(ts->verror, td->verror);
1248                         } else  if (td->error) {
1249                                 ts->error = td->error;
1250                                 strcpy(ts->verror, td->verror);
1251                         }
1252                 }
1253
1254                 sum_thread_stats(ts, &td->ts, idx);
1255         }
1256
1257         for (i = 0; i < nr_ts; i++) {
1258                 unsigned long long bw;
1259
1260                 ts = &threadstats[i];
1261                 rs = &runstats[ts->groupid];
1262                 rs->kb_base = ts->kb_base;
1263                 rs->unit_base = ts->unit_base;
1264                 rs->unified_rw_rep += ts->unified_rw_rep;
1265
1266                 for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1267                         if (!ts->runtime[j])
1268                                 continue;
1269                         if (ts->runtime[j] < rs->min_run[j] || !rs->min_run[j])
1270                                 rs->min_run[j] = ts->runtime[j];
1271                         if (ts->runtime[j] > rs->max_run[j])
1272                                 rs->max_run[j] = ts->runtime[j];
1273
1274                         bw = 0;
1275                         if (ts->runtime[j]) {
1276                                 unsigned long runt = ts->runtime[j];
1277                                 unsigned long long kb;
1278
1279                                 kb = ts->io_bytes[j] / rs->kb_base;
1280                                 bw = kb * 1000 / runt;
1281                         }
1282                         if (bw < rs->min_bw[j])
1283                                 rs->min_bw[j] = bw;
1284                         if (bw > rs->max_bw[j])
1285                                 rs->max_bw[j] = bw;
1286
1287                         rs->io_kb[j] += ts->io_bytes[j] / rs->kb_base;
1288                 }
1289         }
1290
1291         for (i = 0; i < groupid + 1; i++) {
1292                 int ddir;
1293
1294                 rs = &runstats[i];
1295
1296                 for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
1297                         if (rs->max_run[ddir])
1298                                 rs->agg[ddir] = (rs->io_kb[ddir] * 1000) /
1299                                                 rs->max_run[ddir];
1300                 }
1301         }
1302
1303         /*
1304          * don't overwrite last signal output
1305          */
1306         if (output_format == FIO_OUTPUT_NORMAL)
1307                 log_info("\n");
1308         else if (output_format == FIO_OUTPUT_JSON) {
1309                 root = json_create_object();
1310                 json_object_add_value_string(root, "fio version", fio_version_string);
1311                 array = json_create_array();
1312                 json_object_add_value_array(root, "jobs", array);
1313         }
1314
1315         for (i = 0; i < nr_ts; i++) {
1316                 ts = &threadstats[i];
1317                 rs = &runstats[ts->groupid];
1318
1319                 if (is_backend)
1320                         fio_server_send_ts(ts, rs);
1321                 else if (output_format == FIO_OUTPUT_TERSE)
1322                         show_thread_status_terse(ts, rs);
1323                 else if (output_format == FIO_OUTPUT_JSON) {
1324                         struct json_object *tmp = show_thread_status_json(ts, rs);
1325                         json_array_add_value_object(array, tmp);
1326                 } else
1327                         show_thread_status(ts, rs);
1328         }
1329         if (output_format == FIO_OUTPUT_JSON) {
1330                 /* disk util stats, if any */
1331                 show_disk_util(1, root);
1332
1333                 show_idle_prof_stats(FIO_OUTPUT_JSON, root);
1334
1335                 json_print_object(root);
1336                 log_info("\n");
1337                 json_free_object(root);
1338         }
1339
1340         for (i = 0; i < groupid + 1; i++) {
1341                 rs = &runstats[i];
1342
1343                 rs->groupid = i;
1344                 if (is_backend)
1345                         fio_server_send_gs(rs);
1346                 else if (output_format == FIO_OUTPUT_NORMAL)
1347                         show_group_stats(rs);
1348         }
1349
1350         if (is_backend)
1351                 fio_server_send_du();
1352         else if (output_format == FIO_OUTPUT_NORMAL) {
1353                 show_disk_util(0, NULL);
1354                 show_idle_prof_stats(FIO_OUTPUT_NORMAL, NULL);
1355         }
1356
1357         log_info_flush();
1358         free(runstats);
1359         free(threadstats);
1360 }
1361
1362 void show_run_stats(void)
1363 {
1364         fio_mutex_down(stat_mutex);
1365         __show_run_stats();
1366         fio_mutex_up(stat_mutex);
1367 }
1368
1369 static void *__show_running_run_stats(void fio_unused *arg)
1370 {
1371         struct thread_data *td;
1372         unsigned long long *rt;
1373         struct timeval tv;
1374         int i;
1375
1376         rt = malloc(thread_number * sizeof(unsigned long long));
1377         fio_gettime(&tv, NULL);
1378
1379         for_each_td(td, i) {
1380                 rt[i] = mtime_since(&td->start, &tv);
1381                 if (td_read(td) && td->io_bytes[DDIR_READ])
1382                         td->ts.runtime[DDIR_READ] += rt[i];
1383                 if (td_write(td) && td->io_bytes[DDIR_WRITE])
1384                         td->ts.runtime[DDIR_WRITE] += rt[i];
1385                 if (td_trim(td) && td->io_bytes[DDIR_TRIM])
1386                         td->ts.runtime[DDIR_TRIM] += rt[i];
1387
1388                 td->update_rusage = 1;
1389                 td->ts.io_bytes[DDIR_READ] = td->io_bytes[DDIR_READ];
1390                 td->ts.io_bytes[DDIR_WRITE] = td->io_bytes[DDIR_WRITE];
1391                 td->ts.io_bytes[DDIR_TRIM] = td->io_bytes[DDIR_TRIM];
1392                 td->ts.total_run_time = mtime_since(&td->epoch, &tv);
1393         }
1394
1395         for_each_td(td, i) {
1396                 if (td->rusage_sem) {
1397                         td->update_rusage = 1;
1398                         fio_mutex_down(td->rusage_sem);
1399                 }
1400                 td->update_rusage = 0;
1401         }
1402
1403         __show_run_stats();
1404
1405         for_each_td(td, i) {
1406                 if (td_read(td) && td->io_bytes[DDIR_READ])
1407                         td->ts.runtime[DDIR_READ] -= rt[i];
1408                 if (td_write(td) && td->io_bytes[DDIR_WRITE])
1409                         td->ts.runtime[DDIR_WRITE] -= rt[i];
1410                 if (td_trim(td) && td->io_bytes[DDIR_TRIM])
1411                         td->ts.runtime[DDIR_TRIM] -= rt[i];
1412         }
1413
1414         free(rt);
1415         fio_mutex_up(stat_mutex);
1416         return NULL;
1417 }
1418
1419 /*
1420  * Called from signal handler. It _should_ be safe to just run this inline
1421  * in the sig handler, but we should be disturbing the system less by just
1422  * creating a thread to do it.
1423  */
1424 void show_running_run_stats(void)
1425 {
1426         pthread_t thread;
1427
1428         fio_mutex_down(stat_mutex);
1429
1430         if (!pthread_create(&thread, NULL, __show_running_run_stats, NULL)) {
1431                 pthread_detach(thread);
1432                 return;
1433         }
1434
1435         fio_mutex_up(stat_mutex);
1436 }
1437
1438 static int status_interval_init;
1439 static struct timeval status_time;
1440
1441 #define FIO_STATUS_FILE         "/tmp/fio-dump-status"
1442
1443 static int check_status_file(void)
1444 {
1445         struct stat sb;
1446         const char *temp_dir;
1447         char fio_status_file_path[PATH_MAX];
1448
1449         temp_dir = getenv("TMPDIR");
1450         if (temp_dir == NULL)
1451                 temp_dir = getenv("TEMP");
1452         if (temp_dir == NULL)
1453                 temp_dir = "/tmp";
1454
1455         snprintf(fio_status_file_path, sizeof(fio_status_file_path), "%s/%s", temp_dir, FIO_STATUS_FILE);
1456
1457         if (stat(fio_status_file_path, &sb))
1458                 return 0;
1459
1460         unlink(fio_status_file_path);
1461         return 1;
1462 }
1463
1464 void check_for_running_stats(void)
1465 {
1466         if (status_interval) {
1467                 if (!status_interval_init) {
1468                         fio_gettime(&status_time, NULL);
1469                         status_interval_init = 1;
1470                 } else if (mtime_since_now(&status_time) >= status_interval) {
1471                         show_running_run_stats();
1472                         fio_gettime(&status_time, NULL);
1473                         return;
1474                 }
1475         }
1476         if (check_status_file()) {
1477                 show_running_run_stats();
1478                 return;
1479         }
1480 }
1481
1482 static inline void add_stat_sample(struct io_stat *is, unsigned long data)
1483 {
1484         double val = data;
1485         double delta;
1486
1487         if (data > is->max_val)
1488                 is->max_val = data;
1489         if (data < is->min_val)
1490                 is->min_val = data;
1491
1492         delta = val - is->mean.u.f;
1493         if (delta) {
1494                 is->mean.u.f += delta / (is->samples + 1.0);
1495                 is->S.u.f += delta * (val - is->mean.u.f);
1496         }
1497
1498         is->samples++;
1499 }
1500
1501 static void __add_log_sample(struct io_log *iolog, unsigned long val,
1502                              enum fio_ddir ddir, unsigned int bs,
1503                              unsigned long t)
1504 {
1505         const int nr_samples = iolog->nr_samples;
1506
1507         if (!iolog->nr_samples)
1508                 iolog->avg_last = t;
1509
1510         if (iolog->nr_samples == iolog->max_samples) {
1511                 int new_size = sizeof(struct io_sample) * iolog->max_samples*2;
1512
1513                 iolog->log = realloc(iolog->log, new_size);
1514                 iolog->max_samples <<= 1;
1515         }
1516
1517         iolog->log[nr_samples].val = val;
1518         iolog->log[nr_samples].time = t;
1519         iolog->log[nr_samples].ddir = ddir;
1520         iolog->log[nr_samples].bs = bs;
1521         iolog->nr_samples++;
1522 }
1523
1524 static inline void reset_io_stat(struct io_stat *ios)
1525 {
1526         ios->max_val = ios->min_val = ios->samples = 0;
1527         ios->mean.u.f = ios->S.u.f = 0;
1528 }
1529
1530 static void add_log_sample(struct thread_data *td, struct io_log *iolog,
1531                            unsigned long val, enum fio_ddir ddir,
1532                            unsigned int bs)
1533 {
1534         unsigned long elapsed, this_window;
1535
1536         if (!ddir_rw(ddir))
1537                 return;
1538
1539         elapsed = mtime_since_now(&td->epoch);
1540
1541         /*
1542          * If no time averaging, just add the log sample.
1543          */
1544         if (!iolog->avg_msec) {
1545                 __add_log_sample(iolog, val, ddir, bs, elapsed);
1546                 return;
1547         }
1548
1549         /*
1550          * Add the sample. If the time period has passed, then
1551          * add that entry to the log and clear.
1552          */
1553         add_stat_sample(&iolog->avg_window[ddir], val);
1554
1555         /*
1556          * If period hasn't passed, adding the above sample is all we
1557          * need to do.
1558          */
1559         this_window = elapsed - iolog->avg_last;
1560         if (this_window < iolog->avg_msec)
1561                 return;
1562
1563         /*
1564          * Note an entry in the log. Use the mean from the logged samples,
1565          * making sure to properly round up. Only write a log entry if we
1566          * had actual samples done.
1567          */
1568         if (iolog->avg_window[DDIR_READ].samples) {
1569                 unsigned long mr;
1570
1571                 mr = iolog->avg_window[DDIR_READ].mean.u.f + 0.50;
1572                 __add_log_sample(iolog, mr, DDIR_READ, 0, elapsed);
1573         }
1574         if (iolog->avg_window[DDIR_WRITE].samples) {
1575                 unsigned long mw;
1576
1577                 mw = iolog->avg_window[DDIR_WRITE].mean.u.f + 0.50;
1578                 __add_log_sample(iolog, mw, DDIR_WRITE, 0, elapsed);
1579         }
1580         if (iolog->avg_window[DDIR_TRIM].samples) {
1581                 unsigned long mw;
1582
1583                 mw = iolog->avg_window[DDIR_TRIM].mean.u.f + 0.50;
1584                 __add_log_sample(iolog, mw, DDIR_TRIM, 0, elapsed);
1585         }
1586
1587
1588         reset_io_stat(&iolog->avg_window[DDIR_READ]);
1589         reset_io_stat(&iolog->avg_window[DDIR_WRITE]);
1590         reset_io_stat(&iolog->avg_window[DDIR_TRIM]);
1591         iolog->avg_last = elapsed;
1592 }
1593
1594 void add_agg_sample(unsigned long val, enum fio_ddir ddir, unsigned int bs)
1595 {
1596         struct io_log *iolog;
1597
1598         if (!ddir_rw(ddir))
1599                 return;
1600
1601         iolog = agg_io_log[ddir];
1602         __add_log_sample(iolog, val, ddir, bs, mtime_since_genesis());
1603 }
1604
1605 static void add_clat_percentile_sample(struct thread_stat *ts,
1606                                 unsigned long usec, enum fio_ddir ddir)
1607 {
1608         unsigned int idx = plat_val_to_idx(usec);
1609         assert(idx < FIO_IO_U_PLAT_NR);
1610
1611         ts->io_u_plat[ddir][idx]++;
1612 }
1613
1614 void add_clat_sample(struct thread_data *td, enum fio_ddir ddir,
1615                      unsigned long usec, unsigned int bs)
1616 {
1617         struct thread_stat *ts = &td->ts;
1618
1619         if (!ddir_rw(ddir))
1620                 return;
1621
1622         add_stat_sample(&ts->clat_stat[ddir], usec);
1623
1624         if (td->clat_log)
1625                 add_log_sample(td, td->clat_log, usec, ddir, bs);
1626
1627         if (ts->clat_percentiles)
1628                 add_clat_percentile_sample(ts, usec, ddir);
1629 }
1630
1631 void add_slat_sample(struct thread_data *td, enum fio_ddir ddir,
1632                      unsigned long usec, unsigned int bs)
1633 {
1634         struct thread_stat *ts = &td->ts;
1635
1636         if (!ddir_rw(ddir))
1637                 return;
1638
1639         add_stat_sample(&ts->slat_stat[ddir], usec);
1640
1641         if (td->slat_log)
1642                 add_log_sample(td, td->slat_log, usec, ddir, bs);
1643 }
1644
1645 void add_lat_sample(struct thread_data *td, enum fio_ddir ddir,
1646                     unsigned long usec, unsigned int bs)
1647 {
1648         struct thread_stat *ts = &td->ts;
1649
1650         if (!ddir_rw(ddir))
1651                 return;
1652
1653         add_stat_sample(&ts->lat_stat[ddir], usec);
1654
1655         if (td->lat_log)
1656                 add_log_sample(td, td->lat_log, usec, ddir, bs);
1657 }
1658
1659 void add_bw_sample(struct thread_data *td, enum fio_ddir ddir, unsigned int bs,
1660                    struct timeval *t)
1661 {
1662         struct thread_stat *ts = &td->ts;
1663         unsigned long spent, rate;
1664
1665         if (!ddir_rw(ddir))
1666                 return;
1667
1668         spent = mtime_since(&td->bw_sample_time, t);
1669         if (spent < td->o.bw_avg_time)
1670                 return;
1671
1672         /*
1673          * Compute both read and write rates for the interval.
1674          */
1675         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++) {
1676                 uint64_t delta;
1677
1678                 delta = td->this_io_bytes[ddir] - td->stat_io_bytes[ddir];
1679                 if (!delta)
1680                         continue; /* No entries for interval */
1681
1682                 rate = delta * 1000 / spent / 1024;
1683                 add_stat_sample(&ts->bw_stat[ddir], rate);
1684
1685                 if (td->bw_log)
1686                         add_log_sample(td, td->bw_log, rate, ddir, bs);
1687
1688                 td->stat_io_bytes[ddir] = td->this_io_bytes[ddir];
1689         }
1690
1691         fio_gettime(&td->bw_sample_time, NULL);
1692 }
1693
1694 void add_iops_sample(struct thread_data *td, enum fio_ddir ddir,
1695                      struct timeval *t)
1696 {
1697         struct thread_stat *ts = &td->ts;
1698         unsigned long spent, iops;
1699
1700         if (!ddir_rw(ddir))
1701                 return;
1702
1703         spent = mtime_since(&td->iops_sample_time, t);
1704         if (spent < td->o.iops_avg_time)
1705                 return;
1706
1707         /*
1708          * Compute both read and write rates for the interval.
1709          */
1710         for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++) {
1711                 uint64_t delta;
1712
1713                 delta = td->this_io_blocks[ddir] - td->stat_io_blocks[ddir];
1714                 if (!delta)
1715                         continue; /* No entries for interval */
1716
1717                 iops = (delta * 1000) / spent;
1718                 add_stat_sample(&ts->iops_stat[ddir], iops);
1719
1720                 if (td->iops_log)
1721                         add_log_sample(td, td->iops_log, iops, ddir, 0);
1722
1723                 td->stat_io_blocks[ddir] = td->this_io_blocks[ddir];
1724         }
1725
1726         fio_gettime(&td->iops_sample_time, NULL);
1727 }
1728
1729 void stat_init(void)
1730 {
1731         stat_mutex = fio_mutex_init(FIO_MUTEX_UNLOCKED);
1732 }
1733
1734 void stat_exit(void)
1735 {
1736         /*
1737          * When we have the mutex, we know out-of-band access to it
1738          * have ended.
1739          */
1740         fio_mutex_down(stat_mutex);
1741         fio_mutex_remove(stat_mutex);
1742 }