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