engines/sg: kill dead function
[fio.git] / stat.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <sys/time.h>
4 #include <sys/stat.h>
5 #include <math.h>
6
7 #include "fio.h"
8 #include "diskutil.h"
9 #include "lib/ieee754.h"
10 #include "json.h"
11 #include "lib/getrusage.h"
12 #include "idletime.h"
13 #include "lib/pow2.h"
14 #include "lib/output_buffer.h"
15 #include "helper_thread.h"
16 #include "smalloc.h"
17 #include "zbd.h"
18
19 #define LOG_MSEC_SLACK  1
20
21 struct fio_sem *stat_sem;
22
23 void clear_rusage_stat(struct thread_data *td)
24 {
25         struct thread_stat *ts = &td->ts;
26
27         fio_getrusage(&td->ru_start);
28         ts->usr_time = ts->sys_time = 0;
29         ts->ctx = 0;
30         ts->minf = ts->majf = 0;
31 }
32
33 void update_rusage_stat(struct thread_data *td)
34 {
35         struct thread_stat *ts = &td->ts;
36
37         fio_getrusage(&td->ru_end);
38         ts->usr_time += mtime_since_tv(&td->ru_start.ru_utime,
39                                         &td->ru_end.ru_utime);
40         ts->sys_time += mtime_since_tv(&td->ru_start.ru_stime,
41                                         &td->ru_end.ru_stime);
42         ts->ctx += td->ru_end.ru_nvcsw + td->ru_end.ru_nivcsw
43                         - (td->ru_start.ru_nvcsw + td->ru_start.ru_nivcsw);
44         ts->minf += td->ru_end.ru_minflt - td->ru_start.ru_minflt;
45         ts->majf += td->ru_end.ru_majflt - td->ru_start.ru_majflt;
46
47         memcpy(&td->ru_start, &td->ru_end, sizeof(td->ru_end));
48 }
49
50 /*
51  * Given a latency, return the index of the corresponding bucket in
52  * the structure tracking percentiles.
53  *
54  * (1) find the group (and error bits) that the value (latency)
55  * belongs to by looking at its MSB. (2) find the bucket number in the
56  * group by looking at the index bits.
57  *
58  */
59 static unsigned int plat_val_to_idx(unsigned long long val)
60 {
61         unsigned int msb, error_bits, base, offset, idx;
62
63         /* Find MSB starting from bit 0 */
64         if (val == 0)
65                 msb = 0;
66         else
67                 msb = (sizeof(val)*8) - __builtin_clzll(val) - 1;
68
69         /*
70          * MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
71          * all bits of the sample as index
72          */
73         if (msb <= FIO_IO_U_PLAT_BITS)
74                 return val;
75
76         /* Compute the number of error bits to discard*/
77         error_bits = msb - FIO_IO_U_PLAT_BITS;
78
79         /* Compute the number of buckets before the group */
80         base = (error_bits + 1) << FIO_IO_U_PLAT_BITS;
81
82         /*
83          * Discard the error bits and apply the mask to find the
84          * index for the buckets in the group
85          */
86         offset = (FIO_IO_U_PLAT_VAL - 1) & (val >> error_bits);
87
88         /* Make sure the index does not exceed (array size - 1) */
89         idx = (base + offset) < (FIO_IO_U_PLAT_NR - 1) ?
90                 (base + offset) : (FIO_IO_U_PLAT_NR - 1);
91
92         return idx;
93 }
94
95 /*
96  * Convert the given index of the bucket array to the value
97  * represented by the bucket
98  */
99 static unsigned long long plat_idx_to_val(unsigned int idx)
100 {
101         unsigned int error_bits;
102         unsigned long long k, base;
103
104         assert(idx < FIO_IO_U_PLAT_NR);
105
106         /* MSB <= (FIO_IO_U_PLAT_BITS-1), cannot be rounded off. Use
107          * all bits of the sample as index */
108         if (idx < (FIO_IO_U_PLAT_VAL << 1))
109                 return idx;
110
111         /* Find the group and compute the minimum value of that group */
112         error_bits = (idx >> FIO_IO_U_PLAT_BITS) - 1;
113         base = ((unsigned long long) 1) << (error_bits + FIO_IO_U_PLAT_BITS);
114
115         /* Find its bucket number of the group */
116         k = idx % FIO_IO_U_PLAT_VAL;
117
118         /* Return the mean of the range of the bucket */
119         return base + ((k + 0.5) * (1 << error_bits));
120 }
121
122 static int double_cmp(const void *a, const void *b)
123 {
124         const fio_fp64_t fa = *(const fio_fp64_t *) a;
125         const fio_fp64_t fb = *(const fio_fp64_t *) b;
126         int cmp = 0;
127
128         if (fa.u.f > fb.u.f)
129                 cmp = 1;
130         else if (fa.u.f < fb.u.f)
131                 cmp = -1;
132
133         return cmp;
134 }
135
136 unsigned int calc_clat_percentiles(uint64_t *io_u_plat, unsigned long long nr,
137                                    fio_fp64_t *plist, unsigned long long **output,
138                                    unsigned long long *maxv, unsigned long long *minv)
139 {
140         unsigned long long sum = 0;
141         unsigned int len, i, j = 0;
142         unsigned long long *ovals = NULL;
143         bool is_last;
144
145         *minv = -1ULL;
146         *maxv = 0;
147
148         len = 0;
149         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
150                 len++;
151
152         if (!len)
153                 return 0;
154
155         /*
156          * Sort the percentile list. Note that it may already be sorted if
157          * we are using the default values, but since it's a short list this
158          * isn't a worry. Also note that this does not work for NaN values.
159          */
160         if (len > 1)
161                 qsort((void *)plist, len, sizeof(plist[0]), double_cmp);
162
163         ovals = malloc(len * sizeof(*ovals));
164         if (!ovals)
165                 return 0;
166
167         /*
168          * Calculate bucket values, note down max and min values
169          */
170         is_last = false;
171         for (i = 0; i < FIO_IO_U_PLAT_NR && !is_last; i++) {
172                 sum += io_u_plat[i];
173                 while (sum >= ((long double) plist[j].u.f / 100.0 * nr)) {
174                         assert(plist[j].u.f <= 100.0);
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) != 0;
183                         if (is_last)
184                                 break;
185
186                         j++;
187                 }
188         }
189
190         if (!is_last)
191                 log_err("fio: error calculating latency percentiles\n");
192
193         *output = ovals;
194         return len;
195 }
196
197 /*
198  * Find and display the p-th percentile of clat
199  */
200 static void show_clat_percentiles(uint64_t *io_u_plat, unsigned long long nr,
201                                   fio_fp64_t *plist, unsigned int precision,
202                                   const char *pre, struct buf_output *out)
203 {
204         unsigned int divisor, len, i, j = 0;
205         unsigned long long minv, maxv;
206         unsigned long long *ovals;
207         int per_line, scale_down, time_width;
208         bool is_last;
209         char fmt[32];
210
211         len = calc_clat_percentiles(io_u_plat, nr, plist, &ovals, &maxv, &minv);
212         if (!len || !ovals)
213                 goto out;
214
215         /*
216          * We default to nsecs, but if the value range is such that we
217          * should scale down to usecs or msecs, do that.
218          */
219         if (minv > 2000000 && maxv > 99999999ULL) {
220                 scale_down = 2;
221                 divisor = 1000000;
222                 log_buf(out, "    %s percentiles (msec):\n     |", pre);
223         } else if (minv > 2000 && maxv > 99999) {
224                 scale_down = 1;
225                 divisor = 1000;
226                 log_buf(out, "    %s percentiles (usec):\n     |", pre);
227         } else {
228                 scale_down = 0;
229                 divisor = 1;
230                 log_buf(out, "    %s percentiles (nsec):\n     |", pre);
231         }
232
233
234         time_width = max(5, (int) (log10(maxv / divisor) + 1));
235         snprintf(fmt, sizeof(fmt), " %%%u.%ufth=[%%%dllu]%%c", precision + 3,
236                         precision, time_width);
237         /* fmt will be something like " %5.2fth=[%4llu]%c" */
238         per_line = (80 - 7) / (precision + 10 + time_width);
239
240         for (j = 0; j < len; j++) {
241                 /* for formatting */
242                 if (j != 0 && (j % per_line) == 0)
243                         log_buf(out, "     |");
244
245                 /* end of the list */
246                 is_last = (j == len - 1) != 0;
247
248                 for (i = 0; i < scale_down; i++)
249                         ovals[j] = (ovals[j] + 999) / 1000;
250
251                 log_buf(out, fmt, plist[j].u.f, ovals[j], is_last ? '\n' : ',');
252
253                 if (is_last)
254                         break;
255
256                 if ((j % per_line) == per_line - 1)     /* for formatting */
257                         log_buf(out, "\n");
258         }
259
260 out:
261         if (ovals)
262                 free(ovals);
263 }
264
265 bool calc_lat(struct io_stat *is, unsigned long long *min,
266               unsigned long long *max, double *mean, double *dev)
267 {
268         double n = (double) is->samples;
269
270         if (n == 0)
271                 return false;
272
273         *min = is->min_val;
274         *max = is->max_val;
275         *mean = is->mean.u.f;
276
277         if (n > 1.0)
278                 *dev = sqrt(is->S.u.f / (n - 1.0));
279         else
280                 *dev = 0;
281
282         return true;
283 }
284
285 void show_group_stats(struct group_run_stats *rs, struct buf_output *out)
286 {
287         char *io, *agg, *min, *max;
288         char *ioalt, *aggalt, *minalt, *maxalt;
289         const char *str[] = { "   READ", "  WRITE" , "   TRIM"};
290         int i;
291
292         log_buf(out, "\nRun status group %d (all jobs):\n", rs->groupid);
293
294         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
295                 const int i2p = is_power_of_2(rs->kb_base);
296
297                 if (!rs->max_run[i])
298                         continue;
299
300                 io = num2str(rs->iobytes[i], rs->sig_figs, 1, i2p, N2S_BYTE);
301                 ioalt = num2str(rs->iobytes[i], rs->sig_figs, 1, !i2p, N2S_BYTE);
302                 agg = num2str(rs->agg[i], rs->sig_figs, 1, i2p, rs->unit_base);
303                 aggalt = num2str(rs->agg[i], rs->sig_figs, 1, !i2p, rs->unit_base);
304                 min = num2str(rs->min_bw[i], rs->sig_figs, 1, i2p, rs->unit_base);
305                 minalt = num2str(rs->min_bw[i], rs->sig_figs, 1, !i2p, rs->unit_base);
306                 max = num2str(rs->max_bw[i], rs->sig_figs, 1, i2p, rs->unit_base);
307                 maxalt = num2str(rs->max_bw[i], rs->sig_figs, 1, !i2p, rs->unit_base);
308                 log_buf(out, "%s: bw=%s (%s), %s-%s (%s-%s), io=%s (%s), run=%llu-%llumsec\n",
309                                 rs->unified_rw_rep ? "  MIXED" : str[i],
310                                 agg, aggalt, min, max, minalt, maxalt, io, ioalt,
311                                 (unsigned long long) rs->min_run[i],
312                                 (unsigned long long) rs->max_run[i]);
313
314                 free(io);
315                 free(agg);
316                 free(min);
317                 free(max);
318                 free(ioalt);
319                 free(aggalt);
320                 free(minalt);
321                 free(maxalt);
322         }
323 }
324
325 void stat_calc_dist(uint64_t *map, unsigned long total, double *io_u_dist)
326 {
327         int i;
328
329         /*
330          * Do depth distribution calculations
331          */
332         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
333                 if (total) {
334                         io_u_dist[i] = (double) map[i] / (double) total;
335                         io_u_dist[i] *= 100.0;
336                         if (io_u_dist[i] < 0.1 && map[i])
337                                 io_u_dist[i] = 0.1;
338                 } else
339                         io_u_dist[i] = 0.0;
340         }
341 }
342
343 static void stat_calc_lat(struct thread_stat *ts, double *dst,
344                           uint64_t *src, int nr)
345 {
346         unsigned long total = ddir_rw_sum(ts->total_io_u);
347         int i;
348
349         /*
350          * Do latency distribution calculations
351          */
352         for (i = 0; i < nr; i++) {
353                 if (total) {
354                         dst[i] = (double) src[i] / (double) total;
355                         dst[i] *= 100.0;
356                         if (dst[i] < 0.01 && src[i])
357                                 dst[i] = 0.01;
358                 } else
359                         dst[i] = 0.0;
360         }
361 }
362
363 /*
364  * To keep the terse format unaltered, add all of the ns latency
365  * buckets to the first us latency bucket
366  */
367 static void stat_calc_lat_nu(struct thread_stat *ts, double *io_u_lat_u)
368 {
369         unsigned long ntotal = 0, total = ddir_rw_sum(ts->total_io_u);
370         int i;
371
372         stat_calc_lat(ts, io_u_lat_u, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
373
374         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
375                 ntotal += ts->io_u_lat_n[i];
376
377         io_u_lat_u[0] += 100.0 * (double) ntotal / (double) total;
378 }
379
380 void stat_calc_lat_n(struct thread_stat *ts, double *io_u_lat)
381 {
382         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_n, FIO_IO_U_LAT_N_NR);
383 }
384
385 void stat_calc_lat_u(struct thread_stat *ts, double *io_u_lat)
386 {
387         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_u, FIO_IO_U_LAT_U_NR);
388 }
389
390 void stat_calc_lat_m(struct thread_stat *ts, double *io_u_lat)
391 {
392         stat_calc_lat(ts, io_u_lat, ts->io_u_lat_m, FIO_IO_U_LAT_M_NR);
393 }
394
395 static void display_lat(const char *name, unsigned long long min,
396                         unsigned long long max, double mean, double dev,
397                         struct buf_output *out)
398 {
399         const char *base = "(nsec)";
400         char *minp, *maxp;
401
402         if (nsec_to_msec(&min, &max, &mean, &dev))
403                 base = "(msec)";
404         else if (nsec_to_usec(&min, &max, &mean, &dev))
405                 base = "(usec)";
406
407         minp = num2str(min, 6, 1, 0, N2S_NONE);
408         maxp = num2str(max, 6, 1, 0, N2S_NONE);
409
410         log_buf(out, "    %s %s: min=%s, max=%s, avg=%5.02f,"
411                  " stdev=%5.02f\n", name, base, minp, maxp, mean, dev);
412
413         free(minp);
414         free(maxp);
415 }
416
417 static void show_ddir_status(struct group_run_stats *rs, struct thread_stat *ts,
418                              int ddir, struct buf_output *out)
419 {
420         unsigned long runt;
421         unsigned long long min, max, bw, iops;
422         double mean, dev;
423         char *io_p, *bw_p, *bw_p_alt, *iops_p, *post_st = NULL;
424         int i2p;
425
426         if (ddir_sync(ddir)) {
427                 if (calc_lat(&ts->sync_stat, &min, &max, &mean, &dev)) {
428                         log_buf(out, "  %s:\n", "fsync/fdatasync/sync_file_range");
429                         display_lat(io_ddir_name(ddir), min, max, mean, dev, out);
430                         show_clat_percentiles(ts->io_u_sync_plat,
431                                                 ts->sync_stat.samples,
432                                                 ts->percentile_list,
433                                                 ts->percentile_precision,
434                                                 io_ddir_name(ddir), out);
435                 }
436                 return;
437         }
438
439         assert(ddir_rw(ddir));
440
441         if (!ts->runtime[ddir])
442                 return;
443
444         i2p = is_power_of_2(rs->kb_base);
445         runt = ts->runtime[ddir];
446
447         bw = (1000 * ts->io_bytes[ddir]) / runt;
448         io_p = num2str(ts->io_bytes[ddir], ts->sig_figs, 1, i2p, N2S_BYTE);
449         bw_p = num2str(bw, ts->sig_figs, 1, i2p, ts->unit_base);
450         bw_p_alt = num2str(bw, ts->sig_figs, 1, !i2p, ts->unit_base);
451
452         iops = (1000 * (uint64_t)ts->total_io_u[ddir]) / runt;
453         iops_p = num2str(iops, ts->sig_figs, 1, 0, N2S_NONE);
454         if (ddir == DDIR_WRITE)
455                 post_st = zbd_write_status(ts);
456         else if (ddir == DDIR_READ && ts->cachehit && ts->cachemiss) {
457                 uint64_t total;
458                 double hit;
459
460                 total = ts->cachehit + ts->cachemiss;
461                 hit = (double) ts->cachehit / (double) total;
462                 hit *= 100.0;
463                 if (asprintf(&post_st, "; Cachehit=%0.2f%%", hit) < 0)
464                         post_st = NULL;
465         }
466
467         log_buf(out, "  %s: IOPS=%s, BW=%s (%s)(%s/%llumsec)%s\n",
468                         rs->unified_rw_rep ? "mixed" : io_ddir_name(ddir),
469                         iops_p, bw_p, bw_p_alt, io_p,
470                         (unsigned long long) ts->runtime[ddir],
471                         post_st ? : "");
472
473         free(post_st);
474         free(io_p);
475         free(bw_p);
476         free(bw_p_alt);
477         free(iops_p);
478
479         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
480                 display_lat("slat", min, max, mean, dev, out);
481         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
482                 display_lat("clat", min, max, mean, dev, out);
483         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
484                 display_lat(" lat", min, max, mean, dev, out);
485
486         if (ts->clat_percentiles || ts->lat_percentiles) {
487                 const char *name = ts->clat_percentiles ? "clat" : " lat";
488                 uint64_t samples;
489
490                 if (ts->clat_percentiles)
491                         samples = ts->clat_stat[ddir].samples;
492                 else
493                         samples = ts->lat_stat[ddir].samples;
494
495                 show_clat_percentiles(ts->io_u_plat[ddir],
496                                         samples,
497                                         ts->percentile_list,
498                                         ts->percentile_precision, name, out);
499         }
500         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
501                 double p_of_agg = 100.0, fkb_base = (double)rs->kb_base;
502                 const char *bw_str;
503
504                 if ((rs->unit_base == 1) && i2p)
505                         bw_str = "Kibit";
506                 else if (rs->unit_base == 1)
507                         bw_str = "kbit";
508                 else if (i2p)
509                         bw_str = "KiB";
510                 else
511                         bw_str = "kB";
512
513                 if (rs->agg[ddir]) {
514                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
515                         if (p_of_agg > 100.0)
516                                 p_of_agg = 100.0;
517                 }
518
519                 if (rs->unit_base == 1) {
520                         min *= 8.0;
521                         max *= 8.0;
522                         mean *= 8.0;
523                         dev *= 8.0;
524                 }
525
526                 if (mean > fkb_base * fkb_base) {
527                         min /= fkb_base;
528                         max /= fkb_base;
529                         mean /= fkb_base;
530                         dev /= fkb_base;
531                         bw_str = (rs->unit_base == 1 ? "Mibit" : "MiB");
532                 }
533
534                 log_buf(out, "   bw (%5s/s): min=%5llu, max=%5llu, per=%3.2f%%, "
535                         "avg=%5.02f, stdev=%5.02f, samples=%" PRIu64 "\n",
536                         bw_str, min, max, p_of_agg, mean, dev,
537                         (&ts->bw_stat[ddir])->samples);
538         }
539         if (calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev)) {
540                 log_buf(out, "   iops        : min=%5llu, max=%5llu, "
541                         "avg=%5.02f, stdev=%5.02f, samples=%" PRIu64 "\n",
542                         min, max, mean, dev, (&ts->iops_stat[ddir])->samples);
543         }
544 }
545
546 static bool show_lat(double *io_u_lat, int nr, const char **ranges,
547                      const char *msg, struct buf_output *out)
548 {
549         bool new_line = true, shown = false;
550         int i, line = 0;
551
552         for (i = 0; i < nr; i++) {
553                 if (io_u_lat[i] <= 0.0)
554                         continue;
555                 shown = true;
556                 if (new_line) {
557                         if (line)
558                                 log_buf(out, "\n");
559                         log_buf(out, "  lat (%s)   : ", msg);
560                         new_line = false;
561                         line = 0;
562                 }
563                 if (line)
564                         log_buf(out, ", ");
565                 log_buf(out, "%s%3.2f%%", ranges[i], io_u_lat[i]);
566                 line++;
567                 if (line == 5)
568                         new_line = true;
569         }
570
571         if (shown)
572                 log_buf(out, "\n");
573
574         return true;
575 }
576
577 static void show_lat_n(double *io_u_lat_n, struct buf_output *out)
578 {
579         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
580                                  "250=", "500=", "750=", "1000=", };
581
582         show_lat(io_u_lat_n, FIO_IO_U_LAT_N_NR, ranges, "nsec", out);
583 }
584
585 static void show_lat_u(double *io_u_lat_u, struct buf_output *out)
586 {
587         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
588                                  "250=", "500=", "750=", "1000=", };
589
590         show_lat(io_u_lat_u, FIO_IO_U_LAT_U_NR, ranges, "usec", out);
591 }
592
593 static void show_lat_m(double *io_u_lat_m, struct buf_output *out)
594 {
595         const char *ranges[] = { "2=", "4=", "10=", "20=", "50=", "100=",
596                                  "250=", "500=", "750=", "1000=", "2000=",
597                                  ">=2000=", };
598
599         show_lat(io_u_lat_m, FIO_IO_U_LAT_M_NR, ranges, "msec", out);
600 }
601
602 static void show_latencies(struct thread_stat *ts, struct buf_output *out)
603 {
604         double io_u_lat_n[FIO_IO_U_LAT_N_NR];
605         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
606         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
607
608         stat_calc_lat_n(ts, io_u_lat_n);
609         stat_calc_lat_u(ts, io_u_lat_u);
610         stat_calc_lat_m(ts, io_u_lat_m);
611
612         show_lat_n(io_u_lat_n, out);
613         show_lat_u(io_u_lat_u, out);
614         show_lat_m(io_u_lat_m, out);
615 }
616
617 static int block_state_category(int block_state)
618 {
619         switch (block_state) {
620         case BLOCK_STATE_UNINIT:
621                 return 0;
622         case BLOCK_STATE_TRIMMED:
623         case BLOCK_STATE_WRITTEN:
624                 return 1;
625         case BLOCK_STATE_WRITE_FAILURE:
626         case BLOCK_STATE_TRIM_FAILURE:
627                 return 2;
628         default:
629                 /* Silence compile warning on some BSDs and have a return */
630                 assert(0);
631                 return -1;
632         }
633 }
634
635 static int compare_block_infos(const void *bs1, const void *bs2)
636 {
637         uint64_t block1 = *(uint64_t *)bs1;
638         uint64_t block2 = *(uint64_t *)bs2;
639         int state1 = BLOCK_INFO_STATE(block1);
640         int state2 = BLOCK_INFO_STATE(block2);
641         int bscat1 = block_state_category(state1);
642         int bscat2 = block_state_category(state2);
643         int cycles1 = BLOCK_INFO_TRIMS(block1);
644         int cycles2 = BLOCK_INFO_TRIMS(block2);
645
646         if (bscat1 < bscat2)
647                 return -1;
648         if (bscat1 > bscat2)
649                 return 1;
650
651         if (cycles1 < cycles2)
652                 return -1;
653         if (cycles1 > cycles2)
654                 return 1;
655
656         if (state1 < state2)
657                 return -1;
658         if (state1 > state2)
659                 return 1;
660
661         assert(block1 == block2);
662         return 0;
663 }
664
665 static int calc_block_percentiles(int nr_block_infos, uint32_t *block_infos,
666                                   fio_fp64_t *plist, unsigned int **percentiles,
667                                   unsigned int *types)
668 {
669         int len = 0;
670         int i, nr_uninit;
671
672         qsort(block_infos, nr_block_infos, sizeof(uint32_t), compare_block_infos);
673
674         while (len < FIO_IO_U_LIST_MAX_LEN && plist[len].u.f != 0.0)
675                 len++;
676
677         if (!len)
678                 return 0;
679
680         /*
681          * Sort the percentile list. Note that it may already be sorted if
682          * we are using the default values, but since it's a short list this
683          * isn't a worry. Also note that this does not work for NaN values.
684          */
685         if (len > 1)
686                 qsort((void *)plist, len, sizeof(plist[0]), double_cmp);
687
688         /* Start only after the uninit entries end */
689         for (nr_uninit = 0;
690              nr_uninit < nr_block_infos
691                 && BLOCK_INFO_STATE(block_infos[nr_uninit]) == BLOCK_STATE_UNINIT;
692              nr_uninit ++)
693                 ;
694
695         if (nr_uninit == nr_block_infos)
696                 return 0;
697
698         *percentiles = calloc(len, sizeof(**percentiles));
699
700         for (i = 0; i < len; i++) {
701                 int idx = (plist[i].u.f * (nr_block_infos - nr_uninit) / 100)
702                                 + nr_uninit;
703                 (*percentiles)[i] = BLOCK_INFO_TRIMS(block_infos[idx]);
704         }
705
706         memset(types, 0, sizeof(*types) * BLOCK_STATE_COUNT);
707         for (i = 0; i < nr_block_infos; i++)
708                 types[BLOCK_INFO_STATE(block_infos[i])]++;
709
710         return len;
711 }
712
713 static const char *block_state_names[] = {
714         [BLOCK_STATE_UNINIT] = "unwritten",
715         [BLOCK_STATE_TRIMMED] = "trimmed",
716         [BLOCK_STATE_WRITTEN] = "written",
717         [BLOCK_STATE_TRIM_FAILURE] = "trim failure",
718         [BLOCK_STATE_WRITE_FAILURE] = "write failure",
719 };
720
721 static void show_block_infos(int nr_block_infos, uint32_t *block_infos,
722                              fio_fp64_t *plist, struct buf_output *out)
723 {
724         int len, pos, i;
725         unsigned int *percentiles = NULL;
726         unsigned int block_state_counts[BLOCK_STATE_COUNT];
727
728         len = calc_block_percentiles(nr_block_infos, block_infos, plist,
729                                      &percentiles, block_state_counts);
730
731         log_buf(out, "  block lifetime percentiles :\n   |");
732         pos = 0;
733         for (i = 0; i < len; i++) {
734                 uint32_t block_info = percentiles[i];
735 #define LINE_LENGTH     75
736                 char str[LINE_LENGTH];
737                 int strln = snprintf(str, LINE_LENGTH, " %3.2fth=%u%c",
738                                      plist[i].u.f, block_info,
739                                      i == len - 1 ? '\n' : ',');
740                 assert(strln < LINE_LENGTH);
741                 if (pos + strln > LINE_LENGTH) {
742                         pos = 0;
743                         log_buf(out, "\n   |");
744                 }
745                 log_buf(out, "%s", str);
746                 pos += strln;
747 #undef LINE_LENGTH
748         }
749         if (percentiles)
750                 free(percentiles);
751
752         log_buf(out, "        states               :");
753         for (i = 0; i < BLOCK_STATE_COUNT; i++)
754                 log_buf(out, " %s=%u%c",
755                          block_state_names[i], block_state_counts[i],
756                          i == BLOCK_STATE_COUNT - 1 ? '\n' : ',');
757 }
758
759 static void show_ss_normal(struct thread_stat *ts, struct buf_output *out)
760 {
761         char *p1, *p1alt, *p2;
762         unsigned long long bw_mean, iops_mean;
763         const int i2p = is_power_of_2(ts->kb_base);
764
765         if (!ts->ss_dur)
766                 return;
767
768         bw_mean = steadystate_bw_mean(ts);
769         iops_mean = steadystate_iops_mean(ts);
770
771         p1 = num2str(bw_mean / ts->kb_base, ts->sig_figs, ts->kb_base, i2p, ts->unit_base);
772         p1alt = num2str(bw_mean / ts->kb_base, ts->sig_figs, ts->kb_base, !i2p, ts->unit_base);
773         p2 = num2str(iops_mean, ts->sig_figs, 1, 0, N2S_NONE);
774
775         log_buf(out, "  steadystate  : attained=%s, bw=%s (%s), iops=%s, %s%s=%.3f%s\n",
776                 ts->ss_state & FIO_SS_ATTAINED ? "yes" : "no",
777                 p1, p1alt, p2,
778                 ts->ss_state & FIO_SS_IOPS ? "iops" : "bw",
779                 ts->ss_state & FIO_SS_SLOPE ? " slope": " mean dev",
780                 ts->ss_criterion.u.f,
781                 ts->ss_state & FIO_SS_PCT ? "%" : "");
782
783         free(p1);
784         free(p1alt);
785         free(p2);
786 }
787
788 static void show_thread_status_normal(struct thread_stat *ts,
789                                       struct group_run_stats *rs,
790                                       struct buf_output *out)
791 {
792         double usr_cpu, sys_cpu;
793         unsigned long runtime;
794         double io_u_dist[FIO_IO_U_MAP_NR];
795         time_t time_p;
796         char time_buf[32];
797
798         if (!ddir_rw_sum(ts->io_bytes) && !ddir_rw_sum(ts->total_io_u))
799                 return;
800                 
801         memset(time_buf, 0, sizeof(time_buf));
802
803         time(&time_p);
804         os_ctime_r((const time_t *) &time_p, time_buf, sizeof(time_buf));
805
806         if (!ts->error) {
807                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d: pid=%d: %s",
808                                         ts->name, ts->groupid, ts->members,
809                                         ts->error, (int) ts->pid, time_buf);
810         } else {
811                 log_buf(out, "%s: (groupid=%d, jobs=%d): err=%2d (%s): pid=%d: %s",
812                                         ts->name, ts->groupid, ts->members,
813                                         ts->error, ts->verror, (int) ts->pid,
814                                         time_buf);
815         }
816
817         if (strlen(ts->description))
818                 log_buf(out, "  Description  : [%s]\n", ts->description);
819
820         if (ts->io_bytes[DDIR_READ])
821                 show_ddir_status(rs, ts, DDIR_READ, out);
822         if (ts->io_bytes[DDIR_WRITE])
823                 show_ddir_status(rs, ts, DDIR_WRITE, out);
824         if (ts->io_bytes[DDIR_TRIM])
825                 show_ddir_status(rs, ts, DDIR_TRIM, out);
826
827         show_latencies(ts, out);
828
829         if (ts->sync_stat.samples)
830                 show_ddir_status(rs, ts, DDIR_SYNC, out);
831
832         runtime = ts->total_run_time;
833         if (runtime) {
834                 double runt = (double) runtime;
835
836                 usr_cpu = (double) ts->usr_time * 100 / runt;
837                 sys_cpu = (double) ts->sys_time * 100 / runt;
838         } else {
839                 usr_cpu = 0;
840                 sys_cpu = 0;
841         }
842
843         log_buf(out, "  cpu          : usr=%3.2f%%, sys=%3.2f%%, ctx=%llu,"
844                  " majf=%llu, minf=%llu\n", usr_cpu, sys_cpu,
845                         (unsigned long long) ts->ctx,
846                         (unsigned long long) ts->majf,
847                         (unsigned long long) ts->minf);
848
849         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
850         log_buf(out, "  IO depths    : 1=%3.1f%%, 2=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%,"
851                  " 16=%3.1f%%, 32=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
852                                         io_u_dist[1], io_u_dist[2],
853                                         io_u_dist[3], io_u_dist[4],
854                                         io_u_dist[5], io_u_dist[6]);
855
856         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
857         log_buf(out, "     submit    : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
858                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
859                                         io_u_dist[1], io_u_dist[2],
860                                         io_u_dist[3], io_u_dist[4],
861                                         io_u_dist[5], io_u_dist[6]);
862         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
863         log_buf(out, "     complete  : 0=%3.1f%%, 4=%3.1f%%, 8=%3.1f%%, 16=%3.1f%%,"
864                  " 32=%3.1f%%, 64=%3.1f%%, >=64=%3.1f%%\n", io_u_dist[0],
865                                         io_u_dist[1], io_u_dist[2],
866                                         io_u_dist[3], io_u_dist[4],
867                                         io_u_dist[5], io_u_dist[6]);
868         log_buf(out, "     issued rwts: total=%llu,%llu,%llu,%llu"
869                                  " short=%llu,%llu,%llu,0"
870                                  " dropped=%llu,%llu,%llu,0\n",
871                                         (unsigned long long) ts->total_io_u[0],
872                                         (unsigned long long) ts->total_io_u[1],
873                                         (unsigned long long) ts->total_io_u[2],
874                                         (unsigned long long) ts->total_io_u[3],
875                                         (unsigned long long) ts->short_io_u[0],
876                                         (unsigned long long) ts->short_io_u[1],
877                                         (unsigned long long) ts->short_io_u[2],
878                                         (unsigned long long) ts->drop_io_u[0],
879                                         (unsigned long long) ts->drop_io_u[1],
880                                         (unsigned long long) ts->drop_io_u[2]);
881         if (ts->continue_on_error) {
882                 log_buf(out, "     errors    : total=%llu, first_error=%d/<%s>\n",
883                                         (unsigned long long)ts->total_err_count,
884                                         ts->first_error,
885                                         strerror(ts->first_error));
886         }
887         if (ts->latency_depth) {
888                 log_buf(out, "     latency   : target=%llu, window=%llu, percentile=%.2f%%, depth=%u\n",
889                                         (unsigned long long)ts->latency_target,
890                                         (unsigned long long)ts->latency_window,
891                                         ts->latency_percentile.u.f,
892                                         ts->latency_depth);
893         }
894
895         if (ts->nr_block_infos)
896                 show_block_infos(ts->nr_block_infos, ts->block_infos,
897                                   ts->percentile_list, out);
898
899         if (ts->ss_dur)
900                 show_ss_normal(ts, out);
901 }
902
903 static void show_ddir_status_terse(struct thread_stat *ts,
904                                    struct group_run_stats *rs, int ddir,
905                                    int ver, struct buf_output *out)
906 {
907         unsigned long long min, max, minv, maxv, bw, iops;
908         unsigned long long *ovals = NULL;
909         double mean, dev;
910         unsigned int len;
911         int i, bw_stat;
912
913         assert(ddir_rw(ddir));
914
915         iops = bw = 0;
916         if (ts->runtime[ddir]) {
917                 uint64_t runt = ts->runtime[ddir];
918
919                 bw = ((1000 * ts->io_bytes[ddir]) / runt) / 1024; /* KiB/s */
920                 iops = (1000 * (uint64_t) ts->total_io_u[ddir]) / runt;
921         }
922
923         log_buf(out, ";%llu;%llu;%llu;%llu",
924                 (unsigned long long) ts->io_bytes[ddir] >> 10, bw, iops,
925                                         (unsigned long long) ts->runtime[ddir]);
926
927         if (calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev))
928                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
929         else
930                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
931
932         if (calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev))
933                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
934         else
935                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
936
937         if (ts->clat_percentiles || ts->lat_percentiles) {
938                 len = calc_clat_percentiles(ts->io_u_plat[ddir],
939                                         ts->clat_stat[ddir].samples,
940                                         ts->percentile_list, &ovals, &maxv,
941                                         &minv);
942         } else
943                 len = 0;
944
945         for (i = 0; i < FIO_IO_U_LIST_MAX_LEN; i++) {
946                 if (i >= len) {
947                         log_buf(out, ";0%%=0");
948                         continue;
949                 }
950                 log_buf(out, ";%f%%=%llu", ts->percentile_list[i].u.f, ovals[i]/1000);
951         }
952
953         if (calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev))
954                 log_buf(out, ";%llu;%llu;%f;%f", min/1000, max/1000, mean/1000, dev/1000);
955         else
956                 log_buf(out, ";%llu;%llu;%f;%f", 0ULL, 0ULL, 0.0, 0.0);
957
958         if (ovals)
959                 free(ovals);
960
961         bw_stat = calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev);
962         if (bw_stat) {
963                 double p_of_agg = 100.0;
964
965                 if (rs->agg[ddir]) {
966                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
967                         if (p_of_agg > 100.0)
968                                 p_of_agg = 100.0;
969                 }
970
971                 log_buf(out, ";%llu;%llu;%f%%;%f;%f", min, max, p_of_agg, mean, dev);
972         } else
973                 log_buf(out, ";%llu;%llu;%f%%;%f;%f", 0ULL, 0ULL, 0.0, 0.0, 0.0);
974
975         if (ver == 5) {
976                 if (bw_stat)
977                         log_buf(out, ";%" PRIu64, (&ts->bw_stat[ddir])->samples);
978                 else
979                         log_buf(out, ";%lu", 0UL);
980
981                 if (calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev))
982                         log_buf(out, ";%llu;%llu;%f;%f;%" PRIu64, min, max,
983                                 mean, dev, (&ts->iops_stat[ddir])->samples);
984                 else
985                         log_buf(out, ";%llu;%llu;%f;%f;%lu", 0ULL, 0ULL, 0.0, 0.0, 0UL);
986         }
987 }
988
989 static void add_ddir_status_json(struct thread_stat *ts,
990                 struct group_run_stats *rs, int ddir, struct json_object *parent)
991 {
992         unsigned long long min, max, minv, maxv;
993         unsigned long long bw_bytes, bw;
994         unsigned long long *ovals = NULL;
995         double mean, dev, iops;
996         unsigned int len;
997         int i;
998         struct json_object *dir_object, *tmp_object, *percentile_object, *clat_bins_object = NULL;
999         char buf[120];
1000         double p_of_agg = 100.0;
1001
1002         assert(ddir_rw(ddir) || ddir_sync(ddir));
1003
1004         if (ts->unified_rw_rep && ddir != DDIR_READ)
1005                 return;
1006
1007         dir_object = json_create_object();
1008         json_object_add_value_object(parent,
1009                 ts->unified_rw_rep ? "mixed" : io_ddir_name(ddir), dir_object);
1010
1011         if (ddir_rw(ddir)) {
1012                 bw_bytes = 0;
1013                 bw = 0;
1014                 iops = 0.0;
1015                 if (ts->runtime[ddir]) {
1016                         uint64_t runt = ts->runtime[ddir];
1017
1018                         bw_bytes = ((1000 * ts->io_bytes[ddir]) / runt); /* Bytes/s */
1019                         bw = bw_bytes / 1024; /* KiB/s */
1020                         iops = (1000.0 * (uint64_t) ts->total_io_u[ddir]) / runt;
1021                 }
1022
1023                 json_object_add_value_int(dir_object, "io_bytes", ts->io_bytes[ddir]);
1024                 json_object_add_value_int(dir_object, "io_kbytes", ts->io_bytes[ddir] >> 10);
1025                 json_object_add_value_int(dir_object, "bw_bytes", bw_bytes);
1026                 json_object_add_value_int(dir_object, "bw", bw);
1027                 json_object_add_value_float(dir_object, "iops", iops);
1028                 json_object_add_value_int(dir_object, "runtime", ts->runtime[ddir]);
1029                 json_object_add_value_int(dir_object, "total_ios", ts->total_io_u[ddir]);
1030                 json_object_add_value_int(dir_object, "short_ios", ts->short_io_u[ddir]);
1031                 json_object_add_value_int(dir_object, "drop_ios", ts->drop_io_u[ddir]);
1032
1033                 if (!calc_lat(&ts->slat_stat[ddir], &min, &max, &mean, &dev)) {
1034                         min = max = 0;
1035                         mean = dev = 0.0;
1036                 }
1037                 tmp_object = json_create_object();
1038                 json_object_add_value_object(dir_object, "slat_ns", tmp_object);
1039                 json_object_add_value_int(tmp_object, "min", min);
1040                 json_object_add_value_int(tmp_object, "max", max);
1041                 json_object_add_value_float(tmp_object, "mean", mean);
1042                 json_object_add_value_float(tmp_object, "stddev", dev);
1043
1044                 if (!calc_lat(&ts->clat_stat[ddir], &min, &max, &mean, &dev)) {
1045                         min = max = 0;
1046                         mean = dev = 0.0;
1047                 }
1048                 tmp_object = json_create_object();
1049                 json_object_add_value_object(dir_object, "clat_ns", tmp_object);
1050                 json_object_add_value_int(tmp_object, "min", min);
1051                 json_object_add_value_int(tmp_object, "max", max);
1052                 json_object_add_value_float(tmp_object, "mean", mean);
1053                 json_object_add_value_float(tmp_object, "stddev", dev);
1054         } else {
1055                 if (!calc_lat(&ts->sync_stat, &min, &max, &mean, &dev)) {
1056                         min = max = 0;
1057                         mean = dev = 0.0;
1058                 }
1059
1060                 tmp_object = json_create_object();
1061                 json_object_add_value_object(dir_object, "lat_ns", tmp_object);
1062                 json_object_add_value_int(dir_object, "total_ios", ts->total_io_u[DDIR_SYNC]);
1063                 json_object_add_value_int(tmp_object, "min", min);
1064                 json_object_add_value_int(tmp_object, "max", max);
1065                 json_object_add_value_float(tmp_object, "mean", mean);
1066                 json_object_add_value_float(tmp_object, "stddev", dev);
1067         }
1068
1069         if (ts->clat_percentiles || ts->lat_percentiles) {
1070                 if (ddir_rw(ddir)) {
1071                         uint64_t samples;
1072
1073                         if (ts->clat_percentiles)
1074                                 samples = ts->clat_stat[ddir].samples;
1075                         else
1076                                 samples = ts->lat_stat[ddir].samples;
1077
1078                         len = calc_clat_percentiles(ts->io_u_plat[ddir],
1079                                         samples, ts->percentile_list, &ovals,
1080                                         &maxv, &minv);
1081                 } else {
1082                         len = calc_clat_percentiles(ts->io_u_sync_plat,
1083                                         ts->sync_stat.samples,
1084                                         ts->percentile_list, &ovals, &maxv,
1085                                         &minv);
1086                 }
1087
1088                 if (len > FIO_IO_U_LIST_MAX_LEN)
1089                         len = FIO_IO_U_LIST_MAX_LEN;
1090         } else
1091                 len = 0;
1092
1093         percentile_object = json_create_object();
1094         if (ts->clat_percentiles)
1095                 json_object_add_value_object(tmp_object, "percentile", percentile_object);
1096         for (i = 0; i < len; i++) {
1097                 snprintf(buf, sizeof(buf), "%f", ts->percentile_list[i].u.f);
1098                 json_object_add_value_int(percentile_object, (const char *)buf, ovals[i]);
1099         }
1100
1101         if (output_format & FIO_OUTPUT_JSON_PLUS) {
1102                 clat_bins_object = json_create_object();
1103                 if (ts->clat_percentiles)
1104                         json_object_add_value_object(tmp_object, "bins", clat_bins_object);
1105
1106                 for(i = 0; i < FIO_IO_U_PLAT_NR; i++) {
1107                         if (ddir_rw(ddir)) {
1108                                 if (ts->io_u_plat[ddir][i]) {
1109                                         snprintf(buf, sizeof(buf), "%llu", plat_idx_to_val(i));
1110                                         json_object_add_value_int(clat_bins_object, (const char *)buf, ts->io_u_plat[ddir][i]);
1111                                 }
1112                         } else {
1113                                 if (ts->io_u_sync_plat[i]) {
1114                                         snprintf(buf, sizeof(buf), "%llu", plat_idx_to_val(i));
1115                                         json_object_add_value_int(clat_bins_object, (const char *)buf, ts->io_u_sync_plat[i]);
1116                                 }
1117                         }
1118                 }
1119         }
1120
1121         if (!ddir_rw(ddir))
1122                 return;
1123
1124         if (!calc_lat(&ts->lat_stat[ddir], &min, &max, &mean, &dev)) {
1125                 min = max = 0;
1126                 mean = dev = 0.0;
1127         }
1128         tmp_object = json_create_object();
1129         json_object_add_value_object(dir_object, "lat_ns", tmp_object);
1130         json_object_add_value_int(tmp_object, "min", min);
1131         json_object_add_value_int(tmp_object, "max", max);
1132         json_object_add_value_float(tmp_object, "mean", mean);
1133         json_object_add_value_float(tmp_object, "stddev", dev);
1134         if (ts->lat_percentiles)
1135                 json_object_add_value_object(tmp_object, "percentile", percentile_object);
1136         if (output_format & FIO_OUTPUT_JSON_PLUS && ts->lat_percentiles)
1137                 json_object_add_value_object(tmp_object, "bins", clat_bins_object);
1138
1139         if (ovals)
1140                 free(ovals);
1141
1142         if (calc_lat(&ts->bw_stat[ddir], &min, &max, &mean, &dev)) {
1143                 if (rs->agg[ddir]) {
1144                         p_of_agg = mean * 100 / (double) (rs->agg[ddir] / 1024);
1145                         if (p_of_agg > 100.0)
1146                                 p_of_agg = 100.0;
1147                 }
1148         } else {
1149                 min = max = 0;
1150                 p_of_agg = mean = dev = 0.0;
1151         }
1152         json_object_add_value_int(dir_object, "bw_min", min);
1153         json_object_add_value_int(dir_object, "bw_max", max);
1154         json_object_add_value_float(dir_object, "bw_agg", p_of_agg);
1155         json_object_add_value_float(dir_object, "bw_mean", mean);
1156         json_object_add_value_float(dir_object, "bw_dev", dev);
1157         json_object_add_value_int(dir_object, "bw_samples",
1158                                 (&ts->bw_stat[ddir])->samples);
1159
1160         if (!calc_lat(&ts->iops_stat[ddir], &min, &max, &mean, &dev)) {
1161                 min = max = 0;
1162                 mean = dev = 0.0;
1163         }
1164         json_object_add_value_int(dir_object, "iops_min", min);
1165         json_object_add_value_int(dir_object, "iops_max", max);
1166         json_object_add_value_float(dir_object, "iops_mean", mean);
1167         json_object_add_value_float(dir_object, "iops_stddev", dev);
1168         json_object_add_value_int(dir_object, "iops_samples",
1169                                 (&ts->iops_stat[ddir])->samples);
1170
1171         if (ts->cachehit + ts->cachemiss) {
1172                 uint64_t total;
1173                 double hit;
1174
1175                 total = ts->cachehit + ts->cachemiss;
1176                 hit = (double) ts->cachehit / (double) total;
1177                 hit *= 100.0;
1178                 json_object_add_value_float(dir_object, "cachehit", hit);
1179         }
1180 }
1181
1182 static void show_thread_status_terse_all(struct thread_stat *ts,
1183                                          struct group_run_stats *rs, int ver,
1184                                          struct buf_output *out)
1185 {
1186         double io_u_dist[FIO_IO_U_MAP_NR];
1187         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1188         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1189         double usr_cpu, sys_cpu;
1190         int i;
1191
1192         /* General Info */
1193         if (ver == 2)
1194                 log_buf(out, "2;%s;%d;%d", ts->name, ts->groupid, ts->error);
1195         else
1196                 log_buf(out, "%d;%s;%s;%d;%d", ver, fio_version_string,
1197                         ts->name, ts->groupid, ts->error);
1198
1199         /* Log Read Status */
1200         show_ddir_status_terse(ts, rs, DDIR_READ, ver, out);
1201         /* Log Write Status */
1202         show_ddir_status_terse(ts, rs, DDIR_WRITE, ver, out);
1203         /* Log Trim Status */
1204         if (ver == 2 || ver == 4 || ver == 5)
1205                 show_ddir_status_terse(ts, rs, DDIR_TRIM, ver, out);
1206
1207         /* CPU Usage */
1208         if (ts->total_run_time) {
1209                 double runt = (double) ts->total_run_time;
1210
1211                 usr_cpu = (double) ts->usr_time * 100 / runt;
1212                 sys_cpu = (double) ts->sys_time * 100 / runt;
1213         } else {
1214                 usr_cpu = 0;
1215                 sys_cpu = 0;
1216         }
1217
1218         log_buf(out, ";%f%%;%f%%;%llu;%llu;%llu", usr_cpu, sys_cpu,
1219                                                 (unsigned long long) ts->ctx,
1220                                                 (unsigned long long) ts->majf,
1221                                                 (unsigned long long) ts->minf);
1222
1223         /* Calc % distribution of IO depths, usecond, msecond latency */
1224         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1225         stat_calc_lat_nu(ts, io_u_lat_u);
1226         stat_calc_lat_m(ts, io_u_lat_m);
1227
1228         /* Only show fixed 7 I/O depth levels*/
1229         log_buf(out, ";%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%;%3.1f%%",
1230                         io_u_dist[0], io_u_dist[1], io_u_dist[2], io_u_dist[3],
1231                         io_u_dist[4], io_u_dist[5], io_u_dist[6]);
1232
1233         /* Microsecond latency */
1234         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
1235                 log_buf(out, ";%3.2f%%", io_u_lat_u[i]);
1236         /* Millisecond latency */
1237         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
1238                 log_buf(out, ";%3.2f%%", io_u_lat_m[i]);
1239
1240         /* disk util stats, if any */
1241         if (ver >= 3 && is_running_backend())
1242                 show_disk_util(1, NULL, out);
1243
1244         /* Additional output if continue_on_error set - default off*/
1245         if (ts->continue_on_error)
1246                 log_buf(out, ";%llu;%d", (unsigned long long) ts->total_err_count, ts->first_error);
1247         if (ver == 2)
1248                 log_buf(out, "\n");
1249
1250         /* Additional output if description is set */
1251         if (strlen(ts->description))
1252                 log_buf(out, ";%s", ts->description);
1253
1254         log_buf(out, "\n");
1255 }
1256
1257 static void json_add_job_opts(struct json_object *root, const char *name,
1258                               struct flist_head *opt_list)
1259 {
1260         struct json_object *dir_object;
1261         struct flist_head *entry;
1262         struct print_option *p;
1263
1264         if (flist_empty(opt_list))
1265                 return;
1266
1267         dir_object = json_create_object();
1268         json_object_add_value_object(root, name, dir_object);
1269
1270         flist_for_each(entry, opt_list) {
1271                 const char *pos = "";
1272
1273                 p = flist_entry(entry, struct print_option, list);
1274                 if (p->value)
1275                         pos = p->value;
1276                 json_object_add_value_string(dir_object, p->name, pos);
1277         }
1278 }
1279
1280 static struct json_object *show_thread_status_json(struct thread_stat *ts,
1281                                                    struct group_run_stats *rs,
1282                                                    struct flist_head *opt_list)
1283 {
1284         struct json_object *root, *tmp;
1285         struct jobs_eta *je;
1286         double io_u_dist[FIO_IO_U_MAP_NR];
1287         double io_u_lat_n[FIO_IO_U_LAT_N_NR];
1288         double io_u_lat_u[FIO_IO_U_LAT_U_NR];
1289         double io_u_lat_m[FIO_IO_U_LAT_M_NR];
1290         double usr_cpu, sys_cpu;
1291         int i;
1292         size_t size;
1293
1294         root = json_create_object();
1295         json_object_add_value_string(root, "jobname", ts->name);
1296         json_object_add_value_int(root, "groupid", ts->groupid);
1297         json_object_add_value_int(root, "error", ts->error);
1298
1299         /* ETA Info */
1300         je = get_jobs_eta(true, &size);
1301         if (je) {
1302                 json_object_add_value_int(root, "eta", je->eta_sec);
1303                 json_object_add_value_int(root, "elapsed", je->elapsed_sec);
1304         }
1305
1306         if (opt_list)
1307                 json_add_job_opts(root, "job options", opt_list);
1308
1309         add_ddir_status_json(ts, rs, DDIR_READ, root);
1310         add_ddir_status_json(ts, rs, DDIR_WRITE, root);
1311         add_ddir_status_json(ts, rs, DDIR_TRIM, root);
1312         add_ddir_status_json(ts, rs, DDIR_SYNC, root);
1313
1314         /* CPU Usage */
1315         if (ts->total_run_time) {
1316                 double runt = (double) ts->total_run_time;
1317
1318                 usr_cpu = (double) ts->usr_time * 100 / runt;
1319                 sys_cpu = (double) ts->sys_time * 100 / runt;
1320         } else {
1321                 usr_cpu = 0;
1322                 sys_cpu = 0;
1323         }
1324         json_object_add_value_int(root, "job_runtime", ts->total_run_time);
1325         json_object_add_value_float(root, "usr_cpu", usr_cpu);
1326         json_object_add_value_float(root, "sys_cpu", sys_cpu);
1327         json_object_add_value_int(root, "ctx", ts->ctx);
1328         json_object_add_value_int(root, "majf", ts->majf);
1329         json_object_add_value_int(root, "minf", ts->minf);
1330
1331         /* Calc % distribution of IO depths */
1332         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1333         tmp = json_create_object();
1334         json_object_add_value_object(root, "iodepth_level", tmp);
1335         /* Only show fixed 7 I/O depth levels*/
1336         for (i = 0; i < 7; i++) {
1337                 char name[20];
1338                 if (i < 6)
1339                         snprintf(name, 20, "%d", 1 << i);
1340                 else
1341                         snprintf(name, 20, ">=%d", 1 << i);
1342                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1343         }
1344
1345         /* Calc % distribution of submit IO depths */
1346         stat_calc_dist(ts->io_u_submit, ts->total_submit, io_u_dist);
1347         tmp = json_create_object();
1348         json_object_add_value_object(root, "iodepth_submit", tmp);
1349         /* Only show fixed 7 I/O depth levels*/
1350         for (i = 0; i < 7; i++) {
1351                 char name[20];
1352                 if (i == 0)
1353                         snprintf(name, 20, "0");
1354                 else if (i < 6)
1355                         snprintf(name, 20, "%d", 1 << (i+1));
1356                 else
1357                         snprintf(name, 20, ">=%d", 1 << i);
1358                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1359         }
1360
1361         /* Calc % distribution of completion IO depths */
1362         stat_calc_dist(ts->io_u_complete, ts->total_complete, io_u_dist);
1363         tmp = json_create_object();
1364         json_object_add_value_object(root, "iodepth_complete", tmp);
1365         /* Only show fixed 7 I/O depth levels*/
1366         for (i = 0; i < 7; i++) {
1367                 char name[20];
1368                 if (i == 0)
1369                         snprintf(name, 20, "0");
1370                 else if (i < 6)
1371                         snprintf(name, 20, "%d", 1 << (i+1));
1372                 else
1373                         snprintf(name, 20, ">=%d", 1 << i);
1374                 json_object_add_value_float(tmp, (const char *)name, io_u_dist[i]);
1375         }
1376
1377         /* Calc % distribution of nsecond, usecond, msecond latency */
1378         stat_calc_dist(ts->io_u_map, ddir_rw_sum(ts->total_io_u), io_u_dist);
1379         stat_calc_lat_n(ts, io_u_lat_n);
1380         stat_calc_lat_u(ts, io_u_lat_u);
1381         stat_calc_lat_m(ts, io_u_lat_m);
1382
1383         /* Nanosecond latency */
1384         tmp = json_create_object();
1385         json_object_add_value_object(root, "latency_ns", tmp);
1386         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++) {
1387                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1388                                  "250", "500", "750", "1000", };
1389                 json_object_add_value_float(tmp, ranges[i], io_u_lat_n[i]);
1390         }
1391         /* Microsecond latency */
1392         tmp = json_create_object();
1393         json_object_add_value_object(root, "latency_us", tmp);
1394         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++) {
1395                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1396                                  "250", "500", "750", "1000", };
1397                 json_object_add_value_float(tmp, ranges[i], io_u_lat_u[i]);
1398         }
1399         /* Millisecond latency */
1400         tmp = json_create_object();
1401         json_object_add_value_object(root, "latency_ms", tmp);
1402         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++) {
1403                 const char *ranges[] = { "2", "4", "10", "20", "50", "100",
1404                                  "250", "500", "750", "1000", "2000",
1405                                  ">=2000", };
1406                 json_object_add_value_float(tmp, ranges[i], io_u_lat_m[i]);
1407         }
1408
1409         /* Additional output if continue_on_error set - default off*/
1410         if (ts->continue_on_error) {
1411                 json_object_add_value_int(root, "total_err", ts->total_err_count);
1412                 json_object_add_value_int(root, "first_error", ts->first_error);
1413         }
1414
1415         if (ts->latency_depth) {
1416                 json_object_add_value_int(root, "latency_depth", ts->latency_depth);
1417                 json_object_add_value_int(root, "latency_target", ts->latency_target);
1418                 json_object_add_value_float(root, "latency_percentile", ts->latency_percentile.u.f);
1419                 json_object_add_value_int(root, "latency_window", ts->latency_window);
1420         }
1421
1422         /* Additional output if description is set */
1423         if (strlen(ts->description))
1424                 json_object_add_value_string(root, "desc", ts->description);
1425
1426         if (ts->nr_block_infos) {
1427                 /* Block error histogram and types */
1428                 int len;
1429                 unsigned int *percentiles = NULL;
1430                 unsigned int block_state_counts[BLOCK_STATE_COUNT];
1431
1432                 len = calc_block_percentiles(ts->nr_block_infos, ts->block_infos,
1433                                              ts->percentile_list,
1434                                              &percentiles, block_state_counts);
1435
1436                 if (len) {
1437                         struct json_object *block, *percentile_object, *states;
1438                         int state;
1439                         block = json_create_object();
1440                         json_object_add_value_object(root, "block", block);
1441
1442                         percentile_object = json_create_object();
1443                         json_object_add_value_object(block, "percentiles",
1444                                                      percentile_object);
1445                         for (i = 0; i < len; i++) {
1446                                 char buf[20];
1447                                 snprintf(buf, sizeof(buf), "%f",
1448                                          ts->percentile_list[i].u.f);
1449                                 json_object_add_value_int(percentile_object,
1450                                                           (const char *)buf,
1451                                                           percentiles[i]);
1452                         }
1453
1454                         states = json_create_object();
1455                         json_object_add_value_object(block, "states", states);
1456                         for (state = 0; state < BLOCK_STATE_COUNT; state++) {
1457                                 json_object_add_value_int(states,
1458                                         block_state_names[state],
1459                                         block_state_counts[state]);
1460                         }
1461                         free(percentiles);
1462                 }
1463         }
1464
1465         if (ts->ss_dur) {
1466                 struct json_object *data;
1467                 struct json_array *iops, *bw;
1468                 int j, k, l;
1469                 char ss_buf[64];
1470
1471                 snprintf(ss_buf, sizeof(ss_buf), "%s%s:%f%s",
1472                         ts->ss_state & FIO_SS_IOPS ? "iops" : "bw",
1473                         ts->ss_state & FIO_SS_SLOPE ? "_slope" : "",
1474                         (float) ts->ss_limit.u.f,
1475                         ts->ss_state & FIO_SS_PCT ? "%" : "");
1476
1477                 tmp = json_create_object();
1478                 json_object_add_value_object(root, "steadystate", tmp);
1479                 json_object_add_value_string(tmp, "ss", ss_buf);
1480                 json_object_add_value_int(tmp, "duration", (int)ts->ss_dur);
1481                 json_object_add_value_int(tmp, "attained", (ts->ss_state & FIO_SS_ATTAINED) > 0);
1482
1483                 snprintf(ss_buf, sizeof(ss_buf), "%f%s", (float) ts->ss_criterion.u.f,
1484                         ts->ss_state & FIO_SS_PCT ? "%" : "");
1485                 json_object_add_value_string(tmp, "criterion", ss_buf);
1486                 json_object_add_value_float(tmp, "max_deviation", ts->ss_deviation.u.f);
1487                 json_object_add_value_float(tmp, "slope", ts->ss_slope.u.f);
1488
1489                 data = json_create_object();
1490                 json_object_add_value_object(tmp, "data", data);
1491                 bw = json_create_array();
1492                 iops = json_create_array();
1493
1494                 /*
1495                 ** if ss was attained or the buffer is not full,
1496                 ** ss->head points to the first element in the list.
1497                 ** otherwise it actually points to the second element
1498                 ** in the list
1499                 */
1500                 if ((ts->ss_state & FIO_SS_ATTAINED) || !(ts->ss_state & FIO_SS_BUFFER_FULL))
1501                         j = ts->ss_head;
1502                 else
1503                         j = ts->ss_head == 0 ? ts->ss_dur - 1 : ts->ss_head - 1;
1504                 for (l = 0; l < ts->ss_dur; l++) {
1505                         k = (j + l) % ts->ss_dur;
1506                         json_array_add_value_int(bw, ts->ss_bw_data[k]);
1507                         json_array_add_value_int(iops, ts->ss_iops_data[k]);
1508                 }
1509                 json_object_add_value_int(data, "bw_mean", steadystate_bw_mean(ts));
1510                 json_object_add_value_int(data, "iops_mean", steadystate_iops_mean(ts));
1511                 json_object_add_value_array(data, "iops", iops);
1512                 json_object_add_value_array(data, "bw", bw);
1513         }
1514
1515         return root;
1516 }
1517
1518 static void show_thread_status_terse(struct thread_stat *ts,
1519                                      struct group_run_stats *rs,
1520                                      struct buf_output *out)
1521 {
1522         if (terse_version >= 2 && terse_version <= 5)
1523                 show_thread_status_terse_all(ts, rs, terse_version, out);
1524         else
1525                 log_err("fio: bad terse version!? %d\n", terse_version);
1526 }
1527
1528 struct json_object *show_thread_status(struct thread_stat *ts,
1529                                        struct group_run_stats *rs,
1530                                        struct flist_head *opt_list,
1531                                        struct buf_output *out)
1532 {
1533         struct json_object *ret = NULL;
1534
1535         if (output_format & FIO_OUTPUT_TERSE)
1536                 show_thread_status_terse(ts, rs,  out);
1537         if (output_format & FIO_OUTPUT_JSON)
1538                 ret = show_thread_status_json(ts, rs, opt_list);
1539         if (output_format & FIO_OUTPUT_NORMAL)
1540                 show_thread_status_normal(ts, rs,  out);
1541
1542         return ret;
1543 }
1544
1545 static void __sum_stat(struct io_stat *dst, struct io_stat *src, bool first)
1546 {
1547         double mean, S;
1548
1549         dst->min_val = min(dst->min_val, src->min_val);
1550         dst->max_val = max(dst->max_val, src->max_val);
1551
1552         /*
1553          * Compute new mean and S after the merge
1554          * <http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
1555          *  #Parallel_algorithm>
1556          */
1557         if (first) {
1558                 mean = src->mean.u.f;
1559                 S = src->S.u.f;
1560         } else {
1561                 double delta = src->mean.u.f - dst->mean.u.f;
1562
1563                 mean = ((src->mean.u.f * src->samples) +
1564                         (dst->mean.u.f * dst->samples)) /
1565                         (dst->samples + src->samples);
1566
1567                 S =  src->S.u.f + dst->S.u.f + pow(delta, 2.0) *
1568                         (dst->samples * src->samples) /
1569                         (dst->samples + src->samples);
1570         }
1571
1572         dst->samples += src->samples;
1573         dst->mean.u.f = mean;
1574         dst->S.u.f = S;
1575
1576 }
1577
1578 /*
1579  * We sum two kinds of stats - one that is time based, in which case we
1580  * apply the proper summing technique, and then one that is iops/bw
1581  * numbers. For group_reporting, we should just add those up, not make
1582  * them the mean of everything.
1583  */
1584 static void sum_stat(struct io_stat *dst, struct io_stat *src, bool first,
1585                      bool pure_sum)
1586 {
1587         if (src->samples == 0)
1588                 return;
1589
1590         if (!pure_sum) {
1591                 __sum_stat(dst, src, first);
1592                 return;
1593         }
1594
1595         if (first) {
1596                 dst->min_val = src->min_val;
1597                 dst->max_val = src->max_val;
1598                 dst->samples = src->samples;
1599                 dst->mean.u.f = src->mean.u.f;
1600                 dst->S.u.f = src->S.u.f;
1601         } else {
1602                 dst->min_val += src->min_val;
1603                 dst->max_val += src->max_val;
1604                 dst->samples += src->samples;
1605                 dst->mean.u.f += src->mean.u.f;
1606                 dst->S.u.f += src->S.u.f;
1607         }
1608 }
1609
1610 void sum_group_stats(struct group_run_stats *dst, struct group_run_stats *src)
1611 {
1612         int i;
1613
1614         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
1615                 if (dst->max_run[i] < src->max_run[i])
1616                         dst->max_run[i] = src->max_run[i];
1617                 if (dst->min_run[i] && dst->min_run[i] > src->min_run[i])
1618                         dst->min_run[i] = src->min_run[i];
1619                 if (dst->max_bw[i] < src->max_bw[i])
1620                         dst->max_bw[i] = src->max_bw[i];
1621                 if (dst->min_bw[i] && dst->min_bw[i] > src->min_bw[i])
1622                         dst->min_bw[i] = src->min_bw[i];
1623
1624                 dst->iobytes[i] += src->iobytes[i];
1625                 dst->agg[i] += src->agg[i];
1626         }
1627
1628         if (!dst->kb_base)
1629                 dst->kb_base = src->kb_base;
1630         if (!dst->unit_base)
1631                 dst->unit_base = src->unit_base;
1632         if (!dst->sig_figs)
1633                 dst->sig_figs = src->sig_figs;
1634 }
1635
1636 void sum_thread_stats(struct thread_stat *dst, struct thread_stat *src,
1637                       bool first)
1638 {
1639         int l, k;
1640
1641         for (l = 0; l < DDIR_RWDIR_CNT; l++) {
1642                 if (!dst->unified_rw_rep) {
1643                         sum_stat(&dst->clat_stat[l], &src->clat_stat[l], first, false);
1644                         sum_stat(&dst->slat_stat[l], &src->slat_stat[l], first, false);
1645                         sum_stat(&dst->lat_stat[l], &src->lat_stat[l], first, false);
1646                         sum_stat(&dst->bw_stat[l], &src->bw_stat[l], first, true);
1647                         sum_stat(&dst->iops_stat[l], &src->iops_stat[l], first, true);
1648
1649                         dst->io_bytes[l] += src->io_bytes[l];
1650
1651                         if (dst->runtime[l] < src->runtime[l])
1652                                 dst->runtime[l] = src->runtime[l];
1653                 } else {
1654                         sum_stat(&dst->clat_stat[0], &src->clat_stat[l], first, false);
1655                         sum_stat(&dst->slat_stat[0], &src->slat_stat[l], first, false);
1656                         sum_stat(&dst->lat_stat[0], &src->lat_stat[l], first, false);
1657                         sum_stat(&dst->bw_stat[0], &src->bw_stat[l], first, true);
1658                         sum_stat(&dst->iops_stat[0], &src->iops_stat[l], first, true);
1659
1660                         dst->io_bytes[0] += src->io_bytes[l];
1661
1662                         if (dst->runtime[0] < src->runtime[l])
1663                                 dst->runtime[0] = src->runtime[l];
1664
1665                         /*
1666                          * We're summing to the same destination, so override
1667                          * 'first' after the first iteration of the loop
1668                          */
1669                         first = false;
1670                 }
1671         }
1672
1673         sum_stat(&dst->sync_stat, &src->sync_stat, first, false);
1674         dst->usr_time += src->usr_time;
1675         dst->sys_time += src->sys_time;
1676         dst->ctx += src->ctx;
1677         dst->majf += src->majf;
1678         dst->minf += src->minf;
1679
1680         for (k = 0; k < FIO_IO_U_MAP_NR; k++) {
1681                 dst->io_u_map[k] += src->io_u_map[k];
1682                 dst->io_u_submit[k] += src->io_u_submit[k];
1683                 dst->io_u_complete[k] += src->io_u_complete[k];
1684         }
1685         for (k = 0; k < FIO_IO_U_LAT_N_NR; k++) {
1686                 dst->io_u_lat_n[k] += src->io_u_lat_n[k];
1687                 dst->io_u_lat_u[k] += src->io_u_lat_u[k];
1688                 dst->io_u_lat_m[k] += src->io_u_lat_m[k];
1689         }
1690         for (k = 0; k < FIO_IO_U_PLAT_NR; k++)
1691                 dst->io_u_sync_plat[k] += src->io_u_sync_plat[k];
1692
1693         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1694                 if (!dst->unified_rw_rep) {
1695                         dst->total_io_u[k] += src->total_io_u[k];
1696                         dst->short_io_u[k] += src->short_io_u[k];
1697                         dst->drop_io_u[k] += src->drop_io_u[k];
1698                 } else {
1699                         dst->total_io_u[0] += src->total_io_u[k];
1700                         dst->short_io_u[0] += src->short_io_u[k];
1701                         dst->drop_io_u[0] += src->drop_io_u[k];
1702                 }
1703         }
1704
1705         dst->total_io_u[DDIR_SYNC] += src->total_io_u[DDIR_SYNC];
1706
1707         for (k = 0; k < DDIR_RWDIR_CNT; k++) {
1708                 int m;
1709
1710                 for (m = 0; m < FIO_IO_U_PLAT_NR; m++) {
1711                         if (!dst->unified_rw_rep)
1712                                 dst->io_u_plat[k][m] += src->io_u_plat[k][m];
1713                         else
1714                                 dst->io_u_plat[0][m] += src->io_u_plat[k][m];
1715                 }
1716         }
1717
1718         dst->total_run_time += src->total_run_time;
1719         dst->total_submit += src->total_submit;
1720         dst->total_complete += src->total_complete;
1721         dst->nr_zone_resets += src->nr_zone_resets;
1722         dst->cachehit += src->cachehit;
1723         dst->cachemiss += src->cachemiss;
1724 }
1725
1726 void init_group_run_stat(struct group_run_stats *gs)
1727 {
1728         int i;
1729         memset(gs, 0, sizeof(*gs));
1730
1731         for (i = 0; i < DDIR_RWDIR_CNT; i++)
1732                 gs->min_bw[i] = gs->min_run[i] = ~0UL;
1733 }
1734
1735 void init_thread_stat(struct thread_stat *ts)
1736 {
1737         int j;
1738
1739         memset(ts, 0, sizeof(*ts));
1740
1741         for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1742                 ts->lat_stat[j].min_val = -1UL;
1743                 ts->clat_stat[j].min_val = -1UL;
1744                 ts->slat_stat[j].min_val = -1UL;
1745                 ts->bw_stat[j].min_val = -1UL;
1746                 ts->iops_stat[j].min_val = -1UL;
1747         }
1748         ts->sync_stat.min_val = -1UL;
1749         ts->groupid = -1;
1750 }
1751
1752 void __show_run_stats(void)
1753 {
1754         struct group_run_stats *runstats, *rs;
1755         struct thread_data *td;
1756         struct thread_stat *threadstats, *ts;
1757         int i, j, k, nr_ts, last_ts, idx;
1758         bool kb_base_warned = false;
1759         bool unit_base_warned = false;
1760         struct json_object *root = NULL;
1761         struct json_array *array = NULL;
1762         struct buf_output output[FIO_OUTPUT_NR];
1763         struct flist_head **opt_lists;
1764
1765         runstats = malloc(sizeof(struct group_run_stats) * (groupid + 1));
1766
1767         for (i = 0; i < groupid + 1; i++)
1768                 init_group_run_stat(&runstats[i]);
1769
1770         /*
1771          * find out how many threads stats we need. if group reporting isn't
1772          * enabled, it's one-per-td.
1773          */
1774         nr_ts = 0;
1775         last_ts = -1;
1776         for_each_td(td, i) {
1777                 if (!td->o.group_reporting) {
1778                         nr_ts++;
1779                         continue;
1780                 }
1781                 if (last_ts == td->groupid)
1782                         continue;
1783                 if (!td->o.stats)
1784                         continue;
1785
1786                 last_ts = td->groupid;
1787                 nr_ts++;
1788         }
1789
1790         threadstats = malloc(nr_ts * sizeof(struct thread_stat));
1791         opt_lists = malloc(nr_ts * sizeof(struct flist_head *));
1792
1793         for (i = 0; i < nr_ts; i++) {
1794                 init_thread_stat(&threadstats[i]);
1795                 opt_lists[i] = NULL;
1796         }
1797
1798         j = 0;
1799         last_ts = -1;
1800         idx = 0;
1801         for_each_td(td, i) {
1802                 if (!td->o.stats)
1803                         continue;
1804                 if (idx && (!td->o.group_reporting ||
1805                     (td->o.group_reporting && last_ts != td->groupid))) {
1806                         idx = 0;
1807                         j++;
1808                 }
1809
1810                 last_ts = td->groupid;
1811
1812                 ts = &threadstats[j];
1813
1814                 ts->clat_percentiles = td->o.clat_percentiles;
1815                 ts->lat_percentiles = td->o.lat_percentiles;
1816                 ts->percentile_precision = td->o.percentile_precision;
1817                 memcpy(ts->percentile_list, td->o.percentile_list, sizeof(td->o.percentile_list));
1818                 opt_lists[j] = &td->opt_list;
1819
1820                 idx++;
1821                 ts->members++;
1822
1823                 if (ts->groupid == -1) {
1824                         /*
1825                          * These are per-group shared already
1826                          */
1827                         strncpy(ts->name, td->o.name, FIO_JOBNAME_SIZE - 1);
1828                         if (td->o.description)
1829                                 strncpy(ts->description, td->o.description,
1830                                                 FIO_JOBDESC_SIZE - 1);
1831                         else
1832                                 memset(ts->description, 0, FIO_JOBDESC_SIZE);
1833
1834                         /*
1835                          * If multiple entries in this group, this is
1836                          * the first member.
1837                          */
1838                         ts->thread_number = td->thread_number;
1839                         ts->groupid = td->groupid;
1840
1841                         /*
1842                          * first pid in group, not very useful...
1843                          */
1844                         ts->pid = td->pid;
1845
1846                         ts->kb_base = td->o.kb_base;
1847                         ts->unit_base = td->o.unit_base;
1848                         ts->sig_figs = td->o.sig_figs;
1849                         ts->unified_rw_rep = td->o.unified_rw_rep;
1850                 } else if (ts->kb_base != td->o.kb_base && !kb_base_warned) {
1851                         log_info("fio: kb_base differs for jobs in group, using"
1852                                  " %u as the base\n", ts->kb_base);
1853                         kb_base_warned = true;
1854                 } else if (ts->unit_base != td->o.unit_base && !unit_base_warned) {
1855                         log_info("fio: unit_base differs for jobs in group, using"
1856                                  " %u as the base\n", ts->unit_base);
1857                         unit_base_warned = true;
1858                 }
1859
1860                 ts->continue_on_error = td->o.continue_on_error;
1861                 ts->total_err_count += td->total_err_count;
1862                 ts->first_error = td->first_error;
1863                 if (!ts->error) {
1864                         if (!td->error && td->o.continue_on_error &&
1865                             td->first_error) {
1866                                 ts->error = td->first_error;
1867                                 ts->verror[sizeof(ts->verror) - 1] = '\0';
1868                                 strncpy(ts->verror, td->verror, sizeof(ts->verror) - 1);
1869                         } else  if (td->error) {
1870                                 ts->error = td->error;
1871                                 ts->verror[sizeof(ts->verror) - 1] = '\0';
1872                                 strncpy(ts->verror, td->verror, sizeof(ts->verror) - 1);
1873                         }
1874                 }
1875
1876                 ts->latency_depth = td->latency_qd;
1877                 ts->latency_target = td->o.latency_target;
1878                 ts->latency_percentile = td->o.latency_percentile;
1879                 ts->latency_window = td->o.latency_window;
1880
1881                 ts->nr_block_infos = td->ts.nr_block_infos;
1882                 for (k = 0; k < ts->nr_block_infos; k++)
1883                         ts->block_infos[k] = td->ts.block_infos[k];
1884
1885                 sum_thread_stats(ts, &td->ts, idx == 1);
1886
1887                 if (td->o.ss_dur) {
1888                         ts->ss_state = td->ss.state;
1889                         ts->ss_dur = td->ss.dur;
1890                         ts->ss_head = td->ss.head;
1891                         ts->ss_bw_data = td->ss.bw_data;
1892                         ts->ss_iops_data = td->ss.iops_data;
1893                         ts->ss_limit.u.f = td->ss.limit;
1894                         ts->ss_slope.u.f = td->ss.slope;
1895                         ts->ss_deviation.u.f = td->ss.deviation;
1896                         ts->ss_criterion.u.f = td->ss.criterion;
1897                 }
1898                 else
1899                         ts->ss_dur = ts->ss_state = 0;
1900         }
1901
1902         for (i = 0; i < nr_ts; i++) {
1903                 unsigned long long bw;
1904
1905                 ts = &threadstats[i];
1906                 if (ts->groupid == -1)
1907                         continue;
1908                 rs = &runstats[ts->groupid];
1909                 rs->kb_base = ts->kb_base;
1910                 rs->unit_base = ts->unit_base;
1911                 rs->sig_figs = ts->sig_figs;
1912                 rs->unified_rw_rep += ts->unified_rw_rep;
1913
1914                 for (j = 0; j < DDIR_RWDIR_CNT; j++) {
1915                         if (!ts->runtime[j])
1916                                 continue;
1917                         if (ts->runtime[j] < rs->min_run[j] || !rs->min_run[j])
1918                                 rs->min_run[j] = ts->runtime[j];
1919                         if (ts->runtime[j] > rs->max_run[j])
1920                                 rs->max_run[j] = ts->runtime[j];
1921
1922                         bw = 0;
1923                         if (ts->runtime[j])
1924                                 bw = ts->io_bytes[j] * 1000 / ts->runtime[j];
1925                         if (bw < rs->min_bw[j])
1926                                 rs->min_bw[j] = bw;
1927                         if (bw > rs->max_bw[j])
1928                                 rs->max_bw[j] = bw;
1929
1930                         rs->iobytes[j] += ts->io_bytes[j];
1931                 }
1932         }
1933
1934         for (i = 0; i < groupid + 1; i++) {
1935                 int ddir;
1936
1937                 rs = &runstats[i];
1938
1939                 for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
1940                         if (rs->max_run[ddir])
1941                                 rs->agg[ddir] = (rs->iobytes[ddir] * 1000) /
1942                                                 rs->max_run[ddir];
1943                 }
1944         }
1945
1946         for (i = 0; i < FIO_OUTPUT_NR; i++)
1947                 buf_output_init(&output[i]);
1948
1949         /*
1950          * don't overwrite last signal output
1951          */
1952         if (output_format & FIO_OUTPUT_NORMAL)
1953                 log_buf(&output[__FIO_OUTPUT_NORMAL], "\n");
1954         if (output_format & FIO_OUTPUT_JSON) {
1955                 struct thread_data *global;
1956                 char time_buf[32];
1957                 struct timeval now;
1958                 unsigned long long ms_since_epoch;
1959                 time_t tv_sec;
1960
1961                 gettimeofday(&now, NULL);
1962                 ms_since_epoch = (unsigned long long)(now.tv_sec) * 1000 +
1963                                  (unsigned long long)(now.tv_usec) / 1000;
1964
1965                 tv_sec = now.tv_sec;
1966                 os_ctime_r(&tv_sec, time_buf, sizeof(time_buf));
1967                 if (time_buf[strlen(time_buf) - 1] == '\n')
1968                         time_buf[strlen(time_buf) - 1] = '\0';
1969
1970                 root = json_create_object();
1971                 json_object_add_value_string(root, "fio version", fio_version_string);
1972                 json_object_add_value_int(root, "timestamp", now.tv_sec);
1973                 json_object_add_value_int(root, "timestamp_ms", ms_since_epoch);
1974                 json_object_add_value_string(root, "time", time_buf);
1975                 global = get_global_options();
1976                 json_add_job_opts(root, "global options", &global->opt_list);
1977                 array = json_create_array();
1978                 json_object_add_value_array(root, "jobs", array);
1979         }
1980
1981         if (is_backend)
1982                 fio_server_send_job_options(&get_global_options()->opt_list, -1U);
1983
1984         for (i = 0; i < nr_ts; i++) {
1985                 ts = &threadstats[i];
1986                 rs = &runstats[ts->groupid];
1987
1988                 if (is_backend) {
1989                         fio_server_send_job_options(opt_lists[i], i);
1990                         fio_server_send_ts(ts, rs);
1991                 } else {
1992                         if (output_format & FIO_OUTPUT_TERSE)
1993                                 show_thread_status_terse(ts, rs, &output[__FIO_OUTPUT_TERSE]);
1994                         if (output_format & FIO_OUTPUT_JSON) {
1995                                 struct json_object *tmp = show_thread_status_json(ts, rs, opt_lists[i]);
1996                                 json_array_add_value_object(array, tmp);
1997                         }
1998                         if (output_format & FIO_OUTPUT_NORMAL)
1999                                 show_thread_status_normal(ts, rs, &output[__FIO_OUTPUT_NORMAL]);
2000                 }
2001         }
2002         if (!is_backend && (output_format & FIO_OUTPUT_JSON)) {
2003                 /* disk util stats, if any */
2004                 show_disk_util(1, root, &output[__FIO_OUTPUT_JSON]);
2005
2006                 show_idle_prof_stats(FIO_OUTPUT_JSON, root, &output[__FIO_OUTPUT_JSON]);
2007
2008                 json_print_object(root, &output[__FIO_OUTPUT_JSON]);
2009                 log_buf(&output[__FIO_OUTPUT_JSON], "\n");
2010                 json_free_object(root);
2011         }
2012
2013         for (i = 0; i < groupid + 1; i++) {
2014                 rs = &runstats[i];
2015
2016                 rs->groupid = i;
2017                 if (is_backend)
2018                         fio_server_send_gs(rs);
2019                 else if (output_format & FIO_OUTPUT_NORMAL)
2020                         show_group_stats(rs, &output[__FIO_OUTPUT_NORMAL]);
2021         }
2022
2023         if (is_backend)
2024                 fio_server_send_du();
2025         else if (output_format & FIO_OUTPUT_NORMAL) {
2026                 show_disk_util(0, NULL, &output[__FIO_OUTPUT_NORMAL]);
2027                 show_idle_prof_stats(FIO_OUTPUT_NORMAL, NULL, &output[__FIO_OUTPUT_NORMAL]);
2028         }
2029
2030         for (i = 0; i < FIO_OUTPUT_NR; i++) {
2031                 struct buf_output *out = &output[i];
2032
2033                 log_info_buf(out->buf, out->buflen);
2034                 buf_output_free(out);
2035         }
2036
2037         fio_idle_prof_cleanup();
2038
2039         log_info_flush();
2040         free(runstats);
2041         free(threadstats);
2042         free(opt_lists);
2043 }
2044
2045 void __show_running_run_stats(void)
2046 {
2047         struct thread_data *td;
2048         unsigned long long *rt;
2049         struct timespec ts;
2050         int i;
2051
2052         fio_sem_down(stat_sem);
2053
2054         rt = malloc(thread_number * sizeof(unsigned long long));
2055         fio_gettime(&ts, NULL);
2056
2057         for_each_td(td, i) {
2058                 td->update_rusage = 1;
2059                 td->ts.io_bytes[DDIR_READ] = td->io_bytes[DDIR_READ];
2060                 td->ts.io_bytes[DDIR_WRITE] = td->io_bytes[DDIR_WRITE];
2061                 td->ts.io_bytes[DDIR_TRIM] = td->io_bytes[DDIR_TRIM];
2062                 td->ts.total_run_time = mtime_since(&td->epoch, &ts);
2063
2064                 rt[i] = mtime_since(&td->start, &ts);
2065                 if (td_read(td) && td->ts.io_bytes[DDIR_READ])
2066                         td->ts.runtime[DDIR_READ] += rt[i];
2067                 if (td_write(td) && td->ts.io_bytes[DDIR_WRITE])
2068                         td->ts.runtime[DDIR_WRITE] += rt[i];
2069                 if (td_trim(td) && td->ts.io_bytes[DDIR_TRIM])
2070                         td->ts.runtime[DDIR_TRIM] += rt[i];
2071         }
2072
2073         for_each_td(td, i) {
2074                 if (td->runstate >= TD_EXITED)
2075                         continue;
2076                 if (td->rusage_sem) {
2077                         td->update_rusage = 1;
2078                         fio_sem_down(td->rusage_sem);
2079                 }
2080                 td->update_rusage = 0;
2081         }
2082
2083         __show_run_stats();
2084
2085         for_each_td(td, i) {
2086                 if (td_read(td) && td->ts.io_bytes[DDIR_READ])
2087                         td->ts.runtime[DDIR_READ] -= rt[i];
2088                 if (td_write(td) && td->ts.io_bytes[DDIR_WRITE])
2089                         td->ts.runtime[DDIR_WRITE] -= rt[i];
2090                 if (td_trim(td) && td->ts.io_bytes[DDIR_TRIM])
2091                         td->ts.runtime[DDIR_TRIM] -= rt[i];
2092         }
2093
2094         free(rt);
2095         fio_sem_up(stat_sem);
2096 }
2097
2098 static bool status_interval_init;
2099 static struct timespec status_time;
2100 static bool status_file_disabled;
2101
2102 #define FIO_STATUS_FILE         "fio-dump-status"
2103
2104 static int check_status_file(void)
2105 {
2106         struct stat sb;
2107         const char *temp_dir;
2108         char fio_status_file_path[PATH_MAX];
2109
2110         if (status_file_disabled)
2111                 return 0;
2112
2113         temp_dir = getenv("TMPDIR");
2114         if (temp_dir == NULL) {
2115                 temp_dir = getenv("TEMP");
2116                 if (temp_dir && strlen(temp_dir) >= PATH_MAX)
2117                         temp_dir = NULL;
2118         }
2119         if (temp_dir == NULL)
2120                 temp_dir = "/tmp";
2121
2122         snprintf(fio_status_file_path, sizeof(fio_status_file_path), "%s/%s", temp_dir, FIO_STATUS_FILE);
2123
2124         if (stat(fio_status_file_path, &sb))
2125                 return 0;
2126
2127         if (unlink(fio_status_file_path) < 0) {
2128                 log_err("fio: failed to unlink %s: %s\n", fio_status_file_path,
2129                                                         strerror(errno));
2130                 log_err("fio: disabling status file updates\n");
2131                 status_file_disabled = true;
2132         }
2133
2134         return 1;
2135 }
2136
2137 void check_for_running_stats(void)
2138 {
2139         if (status_interval) {
2140                 if (!status_interval_init) {
2141                         fio_gettime(&status_time, NULL);
2142                         status_interval_init = true;
2143                 } else if (mtime_since_now(&status_time) >= status_interval) {
2144                         show_running_run_stats();
2145                         fio_gettime(&status_time, NULL);
2146                         return;
2147                 }
2148         }
2149         if (check_status_file()) {
2150                 show_running_run_stats();
2151                 return;
2152         }
2153 }
2154
2155 static inline void add_stat_sample(struct io_stat *is, unsigned long long data)
2156 {
2157         double val = data;
2158         double delta;
2159
2160         if (data > is->max_val)
2161                 is->max_val = data;
2162         if (data < is->min_val)
2163                 is->min_val = data;
2164
2165         delta = val - is->mean.u.f;
2166         if (delta) {
2167                 is->mean.u.f += delta / (is->samples + 1.0);
2168                 is->S.u.f += delta * (val - is->mean.u.f);
2169         }
2170
2171         is->samples++;
2172 }
2173
2174 /*
2175  * Return a struct io_logs, which is added to the tail of the log
2176  * list for 'iolog'.
2177  */
2178 static struct io_logs *get_new_log(struct io_log *iolog)
2179 {
2180         size_t new_size, new_samples;
2181         struct io_logs *cur_log;
2182
2183         /*
2184          * Cap the size at MAX_LOG_ENTRIES, so we don't keep doubling
2185          * forever
2186          */
2187         if (!iolog->cur_log_max)
2188                 new_samples = DEF_LOG_ENTRIES;
2189         else {
2190                 new_samples = iolog->cur_log_max * 2;
2191                 if (new_samples > MAX_LOG_ENTRIES)
2192                         new_samples = MAX_LOG_ENTRIES;
2193         }
2194
2195         new_size = new_samples * log_entry_sz(iolog);
2196
2197         cur_log = smalloc(sizeof(*cur_log));
2198         if (cur_log) {
2199                 INIT_FLIST_HEAD(&cur_log->list);
2200                 cur_log->log = malloc(new_size);
2201                 if (cur_log->log) {
2202                         cur_log->nr_samples = 0;
2203                         cur_log->max_samples = new_samples;
2204                         flist_add_tail(&cur_log->list, &iolog->io_logs);
2205                         iolog->cur_log_max = new_samples;
2206                         return cur_log;
2207                 }
2208                 sfree(cur_log);
2209         }
2210
2211         return NULL;
2212 }
2213
2214 /*
2215  * Add and return a new log chunk, or return current log if big enough
2216  */
2217 static struct io_logs *regrow_log(struct io_log *iolog)
2218 {
2219         struct io_logs *cur_log;
2220         int i;
2221
2222         if (!iolog || iolog->disabled)
2223                 goto disable;
2224
2225         cur_log = iolog_cur_log(iolog);
2226         if (!cur_log) {
2227                 cur_log = get_new_log(iolog);
2228                 if (!cur_log)
2229                         return NULL;
2230         }
2231
2232         if (cur_log->nr_samples < cur_log->max_samples)
2233                 return cur_log;
2234
2235         /*
2236          * No room for a new sample. If we're compressing on the fly, flush
2237          * out the current chunk
2238          */
2239         if (iolog->log_gz) {
2240                 if (iolog_cur_flush(iolog, cur_log)) {
2241                         log_err("fio: failed flushing iolog! Will stop logging.\n");
2242                         return NULL;
2243                 }
2244         }
2245
2246         /*
2247          * Get a new log array, and add to our list
2248          */
2249         cur_log = get_new_log(iolog);
2250         if (!cur_log) {
2251                 log_err("fio: failed extending iolog! Will stop logging.\n");
2252                 return NULL;
2253         }
2254
2255         if (!iolog->pending || !iolog->pending->nr_samples)
2256                 return cur_log;
2257
2258         /*
2259          * Flush pending items to new log
2260          */
2261         for (i = 0; i < iolog->pending->nr_samples; i++) {
2262                 struct io_sample *src, *dst;
2263
2264                 src = get_sample(iolog, iolog->pending, i);
2265                 dst = get_sample(iolog, cur_log, i);
2266                 memcpy(dst, src, log_entry_sz(iolog));
2267         }
2268         cur_log->nr_samples = iolog->pending->nr_samples;
2269
2270         iolog->pending->nr_samples = 0;
2271         return cur_log;
2272 disable:
2273         if (iolog)
2274                 iolog->disabled = true;
2275         return NULL;
2276 }
2277
2278 void regrow_logs(struct thread_data *td)
2279 {
2280         regrow_log(td->slat_log);
2281         regrow_log(td->clat_log);
2282         regrow_log(td->clat_hist_log);
2283         regrow_log(td->lat_log);
2284         regrow_log(td->bw_log);
2285         regrow_log(td->iops_log);
2286         td->flags &= ~TD_F_REGROW_LOGS;
2287 }
2288
2289 static struct io_logs *get_cur_log(struct io_log *iolog)
2290 {
2291         struct io_logs *cur_log;
2292
2293         cur_log = iolog_cur_log(iolog);
2294         if (!cur_log) {
2295                 cur_log = get_new_log(iolog);
2296                 if (!cur_log)
2297                         return NULL;
2298         }
2299
2300         if (cur_log->nr_samples < cur_log->max_samples)
2301                 return cur_log;
2302
2303         /*
2304          * Out of space. If we're in IO offload mode, or we're not doing
2305          * per unit logging (hence logging happens outside of the IO thread
2306          * as well), add a new log chunk inline. If we're doing inline
2307          * submissions, flag 'td' as needing a log regrow and we'll take
2308          * care of it on the submission side.
2309          */
2310         if ((iolog->td && iolog->td->o.io_submit_mode == IO_MODE_OFFLOAD) ||
2311             !per_unit_log(iolog))
2312                 return regrow_log(iolog);
2313
2314         if (iolog->td)
2315                 iolog->td->flags |= TD_F_REGROW_LOGS;
2316         if (iolog->pending)
2317                 assert(iolog->pending->nr_samples < iolog->pending->max_samples);
2318         return iolog->pending;
2319 }
2320
2321 static void __add_log_sample(struct io_log *iolog, union io_sample_data data,
2322                              enum fio_ddir ddir, unsigned long long bs,
2323                              unsigned long t, uint64_t offset)
2324 {
2325         struct io_logs *cur_log;
2326
2327         if (iolog->disabled)
2328                 return;
2329         if (flist_empty(&iolog->io_logs))
2330                 iolog->avg_last[ddir] = t;
2331
2332         cur_log = get_cur_log(iolog);
2333         if (cur_log) {
2334                 struct io_sample *s;
2335
2336                 s = get_sample(iolog, cur_log, cur_log->nr_samples);
2337
2338                 s->data = data;
2339                 s->time = t + (iolog->td ? iolog->td->unix_epoch : 0);
2340                 io_sample_set_ddir(iolog, s, ddir);
2341                 s->bs = bs;
2342
2343                 if (iolog->log_offset) {
2344                         struct io_sample_offset *so = (void *) s;
2345
2346                         so->offset = offset;
2347                 }
2348
2349                 cur_log->nr_samples++;
2350                 return;
2351         }
2352
2353         iolog->disabled = true;
2354 }
2355
2356 static inline void reset_io_stat(struct io_stat *ios)
2357 {
2358         ios->min_val = -1ULL;
2359         ios->max_val = ios->samples = 0;
2360         ios->mean.u.f = ios->S.u.f = 0;
2361 }
2362
2363 void reset_io_stats(struct thread_data *td)
2364 {
2365         struct thread_stat *ts = &td->ts;
2366         int i, j;
2367
2368         for (i = 0; i < DDIR_RWDIR_CNT; i++) {
2369                 reset_io_stat(&ts->clat_stat[i]);
2370                 reset_io_stat(&ts->slat_stat[i]);
2371                 reset_io_stat(&ts->lat_stat[i]);
2372                 reset_io_stat(&ts->bw_stat[i]);
2373                 reset_io_stat(&ts->iops_stat[i]);
2374
2375                 ts->io_bytes[i] = 0;
2376                 ts->runtime[i] = 0;
2377                 ts->total_io_u[i] = 0;
2378                 ts->short_io_u[i] = 0;
2379                 ts->drop_io_u[i] = 0;
2380
2381                 for (j = 0; j < FIO_IO_U_PLAT_NR; j++) {
2382                         ts->io_u_plat[i][j] = 0;
2383                         if (!i)
2384                                 ts->io_u_sync_plat[j] = 0;
2385                 }
2386         }
2387
2388         ts->total_io_u[DDIR_SYNC] = 0;
2389
2390         for (i = 0; i < FIO_IO_U_MAP_NR; i++) {
2391                 ts->io_u_map[i] = 0;
2392                 ts->io_u_submit[i] = 0;
2393                 ts->io_u_complete[i] = 0;
2394         }
2395
2396         for (i = 0; i < FIO_IO_U_LAT_N_NR; i++)
2397                 ts->io_u_lat_n[i] = 0;
2398         for (i = 0; i < FIO_IO_U_LAT_U_NR; i++)
2399                 ts->io_u_lat_u[i] = 0;
2400         for (i = 0; i < FIO_IO_U_LAT_M_NR; i++)
2401                 ts->io_u_lat_m[i] = 0;
2402
2403         ts->total_submit = 0;
2404         ts->total_complete = 0;
2405         ts->nr_zone_resets = 0;
2406         ts->cachehit = ts->cachemiss = 0;
2407 }
2408
2409 static void __add_stat_to_log(struct io_log *iolog, enum fio_ddir ddir,
2410                               unsigned long elapsed, bool log_max)
2411 {
2412         /*
2413          * Note an entry in the log. Use the mean from the logged samples,
2414          * making sure to properly round up. Only write a log entry if we
2415          * had actual samples done.
2416          */
2417         if (iolog->avg_window[ddir].samples) {
2418                 union io_sample_data data;
2419
2420                 if (log_max)
2421                         data.val = iolog->avg_window[ddir].max_val;
2422                 else
2423                         data.val = iolog->avg_window[ddir].mean.u.f + 0.50;
2424
2425                 __add_log_sample(iolog, data, ddir, 0, elapsed, 0);
2426         }
2427
2428         reset_io_stat(&iolog->avg_window[ddir]);
2429 }
2430
2431 static void _add_stat_to_log(struct io_log *iolog, unsigned long elapsed,
2432                              bool log_max)
2433 {
2434         int ddir;
2435
2436         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++)
2437                 __add_stat_to_log(iolog, ddir, elapsed, log_max);
2438 }
2439
2440 static unsigned long add_log_sample(struct thread_data *td,
2441                                     struct io_log *iolog,
2442                                     union io_sample_data data,
2443                                     enum fio_ddir ddir, unsigned long long bs,
2444                                     uint64_t offset)
2445 {
2446         unsigned long elapsed, this_window;
2447
2448         if (!ddir_rw(ddir))
2449                 return 0;
2450
2451         elapsed = mtime_since_now(&td->epoch);
2452
2453         /*
2454          * If no time averaging, just add the log sample.
2455          */
2456         if (!iolog->avg_msec) {
2457                 __add_log_sample(iolog, data, ddir, bs, elapsed, offset);
2458                 return 0;
2459         }
2460
2461         /*
2462          * Add the sample. If the time period has passed, then
2463          * add that entry to the log and clear.
2464          */
2465         add_stat_sample(&iolog->avg_window[ddir], data.val);
2466
2467         /*
2468          * If period hasn't passed, adding the above sample is all we
2469          * need to do.
2470          */
2471         this_window = elapsed - iolog->avg_last[ddir];
2472         if (elapsed < iolog->avg_last[ddir])
2473                 return iolog->avg_last[ddir] - elapsed;
2474         else if (this_window < iolog->avg_msec) {
2475                 unsigned long diff = iolog->avg_msec - this_window;
2476
2477                 if (inline_log(iolog) || diff > LOG_MSEC_SLACK)
2478                         return diff;
2479         }
2480
2481         __add_stat_to_log(iolog, ddir, elapsed, td->o.log_max != 0);
2482
2483         iolog->avg_last[ddir] = elapsed - (this_window - iolog->avg_msec);
2484         return iolog->avg_msec;
2485 }
2486
2487 void finalize_logs(struct thread_data *td, bool unit_logs)
2488 {
2489         unsigned long elapsed;
2490
2491         elapsed = mtime_since_now(&td->epoch);
2492
2493         if (td->clat_log && unit_logs)
2494                 _add_stat_to_log(td->clat_log, elapsed, td->o.log_max != 0);
2495         if (td->slat_log && unit_logs)
2496                 _add_stat_to_log(td->slat_log, elapsed, td->o.log_max != 0);
2497         if (td->lat_log && unit_logs)
2498                 _add_stat_to_log(td->lat_log, elapsed, td->o.log_max != 0);
2499         if (td->bw_log && (unit_logs == per_unit_log(td->bw_log)))
2500                 _add_stat_to_log(td->bw_log, elapsed, td->o.log_max != 0);
2501         if (td->iops_log && (unit_logs == per_unit_log(td->iops_log)))
2502                 _add_stat_to_log(td->iops_log, elapsed, td->o.log_max != 0);
2503 }
2504
2505 void add_agg_sample(union io_sample_data data, enum fio_ddir ddir, unsigned long long bs)
2506 {
2507         struct io_log *iolog;
2508
2509         if (!ddir_rw(ddir))
2510                 return;
2511
2512         iolog = agg_io_log[ddir];
2513         __add_log_sample(iolog, data, ddir, bs, mtime_since_genesis(), 0);
2514 }
2515
2516 void add_sync_clat_sample(struct thread_stat *ts, unsigned long long nsec)
2517 {
2518         unsigned int idx = plat_val_to_idx(nsec);
2519         assert(idx < FIO_IO_U_PLAT_NR);
2520
2521         ts->io_u_sync_plat[idx]++;
2522         add_stat_sample(&ts->sync_stat, nsec);
2523 }
2524
2525 static void add_clat_percentile_sample(struct thread_stat *ts,
2526                                 unsigned long long nsec, enum fio_ddir ddir)
2527 {
2528         unsigned int idx = plat_val_to_idx(nsec);
2529         assert(idx < FIO_IO_U_PLAT_NR);
2530
2531         ts->io_u_plat[ddir][idx]++;
2532 }
2533
2534 void add_clat_sample(struct thread_data *td, enum fio_ddir ddir,
2535                      unsigned long long nsec, unsigned long long bs,
2536                      uint64_t offset)
2537 {
2538         const bool needs_lock = td_async_processing(td);
2539         unsigned long elapsed, this_window;
2540         struct thread_stat *ts = &td->ts;
2541         struct io_log *iolog = td->clat_hist_log;
2542
2543         if (needs_lock)
2544                 __td_io_u_lock(td);
2545
2546         add_stat_sample(&ts->clat_stat[ddir], nsec);
2547
2548         if (td->clat_log)
2549                 add_log_sample(td, td->clat_log, sample_val(nsec), ddir, bs,
2550                                offset);
2551
2552         if (ts->clat_percentiles)
2553                 add_clat_percentile_sample(ts, nsec, ddir);
2554
2555         if (iolog && iolog->hist_msec) {
2556                 struct io_hist *hw = &iolog->hist_window[ddir];
2557
2558                 hw->samples++;
2559                 elapsed = mtime_since_now(&td->epoch);
2560                 if (!hw->hist_last)
2561                         hw->hist_last = elapsed;
2562                 this_window = elapsed - hw->hist_last;
2563                 
2564                 if (this_window >= iolog->hist_msec) {
2565                         uint64_t *io_u_plat;
2566                         struct io_u_plat_entry *dst;
2567
2568                         /*
2569                          * Make a byte-for-byte copy of the latency histogram
2570                          * stored in td->ts.io_u_plat[ddir], recording it in a
2571                          * log sample. Note that the matching call to free() is
2572                          * located in iolog.c after printing this sample to the
2573                          * log file.
2574                          */
2575                         io_u_plat = (uint64_t *) td->ts.io_u_plat[ddir];
2576                         dst = malloc(sizeof(struct io_u_plat_entry));
2577                         memcpy(&(dst->io_u_plat), io_u_plat,
2578                                 FIO_IO_U_PLAT_NR * sizeof(unsigned int));
2579                         flist_add(&dst->list, &hw->list);
2580                         __add_log_sample(iolog, sample_plat(dst), ddir, bs,
2581                                                 elapsed, offset);
2582
2583                         /*
2584                          * Update the last time we recorded as being now, minus
2585                          * any drift in time we encountered before actually
2586                          * making the record.
2587                          */
2588                         hw->hist_last = elapsed - (this_window - iolog->hist_msec);
2589                         hw->samples = 0;
2590                 }
2591         }
2592
2593         if (needs_lock)
2594                 __td_io_u_unlock(td);
2595 }
2596
2597 void add_slat_sample(struct thread_data *td, enum fio_ddir ddir,
2598                      unsigned long usec, unsigned long long bs, uint64_t offset)
2599 {
2600         const bool needs_lock = td_async_processing(td);
2601         struct thread_stat *ts = &td->ts;
2602
2603         if (!ddir_rw(ddir))
2604                 return;
2605
2606         if (needs_lock)
2607                 __td_io_u_lock(td);
2608
2609         add_stat_sample(&ts->slat_stat[ddir], usec);
2610
2611         if (td->slat_log)
2612                 add_log_sample(td, td->slat_log, sample_val(usec), ddir, bs, offset);
2613
2614         if (needs_lock)
2615                 __td_io_u_unlock(td);
2616 }
2617
2618 void add_lat_sample(struct thread_data *td, enum fio_ddir ddir,
2619                     unsigned long long nsec, unsigned long long bs,
2620                     uint64_t offset)
2621 {
2622         const bool needs_lock = td_async_processing(td);
2623         struct thread_stat *ts = &td->ts;
2624
2625         if (!ddir_rw(ddir))
2626                 return;
2627
2628         if (needs_lock)
2629                 __td_io_u_lock(td);
2630
2631         add_stat_sample(&ts->lat_stat[ddir], nsec);
2632
2633         if (td->lat_log)
2634                 add_log_sample(td, td->lat_log, sample_val(nsec), ddir, bs,
2635                                offset);
2636
2637         if (ts->lat_percentiles)
2638                 add_clat_percentile_sample(ts, nsec, ddir);
2639
2640         if (needs_lock)
2641                 __td_io_u_unlock(td);
2642 }
2643
2644 void add_bw_sample(struct thread_data *td, struct io_u *io_u,
2645                    unsigned int bytes, unsigned long long spent)
2646 {
2647         const bool needs_lock = td_async_processing(td);
2648         struct thread_stat *ts = &td->ts;
2649         unsigned long rate;
2650
2651         if (spent)
2652                 rate = (unsigned long) (bytes * 1000000ULL / spent);
2653         else
2654                 rate = 0;
2655
2656         if (needs_lock)
2657                 __td_io_u_lock(td);
2658
2659         add_stat_sample(&ts->bw_stat[io_u->ddir], rate);
2660
2661         if (td->bw_log)
2662                 add_log_sample(td, td->bw_log, sample_val(rate), io_u->ddir,
2663                                bytes, io_u->offset);
2664
2665         td->stat_io_bytes[io_u->ddir] = td->this_io_bytes[io_u->ddir];
2666
2667         if (needs_lock)
2668                 __td_io_u_unlock(td);
2669 }
2670
2671 static int __add_samples(struct thread_data *td, struct timespec *parent_tv,
2672                          struct timespec *t, unsigned int avg_time,
2673                          uint64_t *this_io_bytes, uint64_t *stat_io_bytes,
2674                          struct io_stat *stat, struct io_log *log,
2675                          bool is_kb)
2676 {
2677         const bool needs_lock = td_async_processing(td);
2678         unsigned long spent, rate;
2679         enum fio_ddir ddir;
2680         unsigned long next, next_log;
2681
2682         next_log = avg_time;
2683
2684         spent = mtime_since(parent_tv, t);
2685         if (spent < avg_time && avg_time - spent >= LOG_MSEC_SLACK)
2686                 return avg_time - spent;
2687
2688         if (needs_lock)
2689                 __td_io_u_lock(td);
2690
2691         /*
2692          * Compute both read and write rates for the interval.
2693          */
2694         for (ddir = 0; ddir < DDIR_RWDIR_CNT; ddir++) {
2695                 uint64_t delta;
2696
2697                 delta = this_io_bytes[ddir] - stat_io_bytes[ddir];
2698                 if (!delta)
2699                         continue; /* No entries for interval */
2700
2701                 if (spent) {
2702                         if (is_kb)
2703                                 rate = delta * 1000 / spent / 1024; /* KiB/s */
2704                         else
2705                                 rate = (delta * 1000) / spent;
2706                 } else
2707                         rate = 0;
2708
2709                 add_stat_sample(&stat[ddir], rate);
2710
2711                 if (log) {
2712                         unsigned long long bs = 0;
2713
2714                         if (td->o.min_bs[ddir] == td->o.max_bs[ddir])
2715                                 bs = td->o.min_bs[ddir];
2716
2717                         next = add_log_sample(td, log, sample_val(rate), ddir, bs, 0);
2718                         next_log = min(next_log, next);
2719                 }
2720
2721                 stat_io_bytes[ddir] = this_io_bytes[ddir];
2722         }
2723
2724         timespec_add_msec(parent_tv, avg_time);
2725
2726         if (needs_lock)
2727                 __td_io_u_unlock(td);
2728
2729         if (spent <= avg_time)
2730                 next = avg_time;
2731         else
2732                 next = avg_time - (1 + spent - avg_time);
2733
2734         return min(next, next_log);
2735 }
2736
2737 static int add_bw_samples(struct thread_data *td, struct timespec *t)
2738 {
2739         return __add_samples(td, &td->bw_sample_time, t, td->o.bw_avg_time,
2740                                 td->this_io_bytes, td->stat_io_bytes,
2741                                 td->ts.bw_stat, td->bw_log, true);
2742 }
2743
2744 void add_iops_sample(struct thread_data *td, struct io_u *io_u,
2745                      unsigned int bytes)
2746 {
2747         const bool needs_lock = td_async_processing(td);
2748         struct thread_stat *ts = &td->ts;
2749
2750         if (needs_lock)
2751                 __td_io_u_lock(td);
2752
2753         add_stat_sample(&ts->iops_stat[io_u->ddir], 1);
2754
2755         if (td->iops_log)
2756                 add_log_sample(td, td->iops_log, sample_val(1), io_u->ddir,
2757                                bytes, io_u->offset);
2758
2759         td->stat_io_blocks[io_u->ddir] = td->this_io_blocks[io_u->ddir];
2760
2761         if (needs_lock)
2762                 __td_io_u_unlock(td);
2763 }
2764
2765 static int add_iops_samples(struct thread_data *td, struct timespec *t)
2766 {
2767         return __add_samples(td, &td->iops_sample_time, t, td->o.iops_avg_time,
2768                                 td->this_io_blocks, td->stat_io_blocks,
2769                                 td->ts.iops_stat, td->iops_log, false);
2770 }
2771
2772 /*
2773  * Returns msecs to next event
2774  */
2775 int calc_log_samples(void)
2776 {
2777         struct thread_data *td;
2778         unsigned int next = ~0U, tmp;
2779         struct timespec now;
2780         int i;
2781
2782         fio_gettime(&now, NULL);
2783
2784         for_each_td(td, i) {
2785                 if (!td->o.stats)
2786                         continue;
2787                 if (in_ramp_time(td) ||
2788                     !(td->runstate == TD_RUNNING || td->runstate == TD_VERIFYING)) {
2789                         next = min(td->o.iops_avg_time, td->o.bw_avg_time);
2790                         continue;
2791                 }
2792                 if (!td->bw_log ||
2793                         (td->bw_log && !per_unit_log(td->bw_log))) {
2794                         tmp = add_bw_samples(td, &now);
2795                         if (tmp < next)
2796                                 next = tmp;
2797                 }
2798                 if (!td->iops_log ||
2799                         (td->iops_log && !per_unit_log(td->iops_log))) {
2800                         tmp = add_iops_samples(td, &now);
2801                         if (tmp < next)
2802                                 next = tmp;
2803                 }
2804         }
2805
2806         return next == ~0U ? 0 : next;
2807 }
2808
2809 void stat_init(void)
2810 {
2811         stat_sem = fio_sem_init(FIO_SEM_UNLOCKED);
2812 }
2813
2814 void stat_exit(void)
2815 {
2816         /*
2817          * When we have the mutex, we know out-of-band access to it
2818          * have ended.
2819          */
2820         fio_sem_down(stat_sem);
2821         fio_sem_remove(stat_sem);
2822 }
2823
2824 /*
2825  * Called from signal handler. Wake up status thread.
2826  */
2827 void show_running_run_stats(void)
2828 {
2829         helper_do_stat();
2830 }
2831
2832 uint32_t *io_u_block_info(struct thread_data *td, struct io_u *io_u)
2833 {
2834         /* Ignore io_u's which span multiple blocks--they will just get
2835          * inaccurate counts. */
2836         int idx = (io_u->offset - io_u->file->file_offset)
2837                         / td->o.bs[DDIR_TRIM];
2838         uint32_t *info = &td->ts.block_infos[idx];
2839         assert(idx < td->ts.nr_block_infos);
2840         return info;
2841 }