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