iowatcher: Improve xticks logic
[blktrace.git] / iowatcher / plot.c
1 /*
2  * Copyright (C) 2012 Fusion-io
3  *
4  *  This program is free software; you can redistribute it and/or
5  *  modify it under the terms of the GNU General Public
6  *  License v2 as published by the Free Software Foundation.
7  *
8  *  This program is distributed in the hope that it will be useful,
9  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
10  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  *  GNU General Public License for more details.
12  *
13  *  You should have received a copy of the GNU General Public License
14  *  along with this program; if not, write to the Free Software
15  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16  *
17  *  Parts of this file were imported from Jens Axboe's blktrace sources (also GPL)
18  */
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <math.h>
26 #include <inttypes.h>
27 #include <string.h>
28 #include <asm/types.h>
29 #include <errno.h>
30 #include <sys/mman.h>
31 #include <time.h>
32 #include <math.h>
33
34 #include "plot.h"
35
36 static int io_graph_scale = 8;
37 static int graph_width = 700;
38 static int graph_height = 250;
39 static int graph_circle_extra = 30;
40 static int graph_inner_x_margin = 2;
41 static int graph_inner_y_margin = 2;
42 static int graph_tick_len = 5;
43 static int graph_left_pad = 120;
44 static int tick_label_pad = 16;
45 static int tick_font_size = 15;
46 static char *font_family = "sans-serif";
47
48 /* this is the title for the whole page */
49 static int plot_title_height = 50;
50 static int plot_title_font_size = 25;
51
52 /* this is the label at the top of each plot */
53 static int plot_label_height = 60;
54 static int plot_label_font_size = 20;
55
56 /* label for each axis is slightly smaller */
57 static int axis_label_font_size = 16;
58
59 int legend_x_off = 45;
60 int legend_y_off = -10;
61 int legend_font_size = 15;
62 int legend_width = 80;
63
64 static int rolling_avg_secs = 0;
65
66 static int line_len = 1024;
67 static char line[1024];
68
69 static int final_height = 0;
70 static int final_width = 0;
71
72 struct graph_line_data *alloc_line_data(int min_seconds, int max_seconds, int stop_seconds)
73 {
74         int size = sizeof(struct graph_line_data) + (stop_seconds + 1) * sizeof(struct graph_line_pair);
75         struct graph_line_data *gld;
76
77         gld = calloc(1, size);
78         if (!gld) {
79                 fprintf(stderr, "Unable to allocate memory for graph data\n");
80                 exit(1);
81         }
82         gld->min_seconds = min_seconds;
83         gld->max_seconds = max_seconds;
84         gld->stop_seconds = stop_seconds;
85         return gld;
86 }
87
88 void free_line_data(struct graph_line_data *gld)
89 {
90         free(gld->label);
91         free(gld);
92 }
93
94 struct graph_dot_data *alloc_dot_data(int min_seconds, int max_seconds, u64 min_offset, u64 max_offset, int stop_seconds)
95 {
96         int size;
97         int arr_size;
98         int rows = graph_height * io_graph_scale;
99         int cols = graph_width;
100         struct graph_dot_data *gdd;
101
102         size = sizeof(struct graph_dot_data);
103
104         /* the number of bits */
105         arr_size = (rows + 1) * cols;
106
107         /* the number of bytes */
108         arr_size /= 8;
109
110         gdd = calloc(1, size + arr_size);
111         if (!gdd) {
112                 fprintf(stderr, "Unable to allocate memory for graph data\n");
113                 exit(1);
114         }
115         gdd->min_seconds = min_seconds;
116         gdd->max_seconds = max_seconds;
117         gdd->stop_seconds = stop_seconds;
118         gdd->rows = rows;
119         gdd->cols = cols;
120         gdd->min_offset = min_offset;
121         gdd->max_offset = max_offset;
122         return gdd;
123 }
124
125 void free_dot_data(struct graph_dot_data *gdd)
126 {
127         free(gdd);
128 }
129
130 void set_gdd_bit(struct graph_dot_data *gdd, u64 offset, double bytes, double time)
131 {
132         double bytes_per_row = (double)(gdd->max_offset - gdd->min_offset + 1) / gdd->rows;
133         double secs_per_col = (double)(gdd->max_seconds - gdd->min_seconds) / gdd->cols;
134         double col;
135         double row;
136         int col_int;
137         int row_int;
138         int bit_index;
139         int arr_index;
140         int bit_mod;
141         double mod = bytes_per_row;
142
143         if (offset > gdd->max_offset || offset < gdd->min_offset)
144                 return;
145
146         gdd->total_ios++;
147         time = time / 1000000000.0;
148         while (bytes > 0) {
149                 row = (double)(offset - gdd->min_offset) / bytes_per_row;
150                 col = (time - gdd->min_seconds) / secs_per_col;
151
152                 col_int = floor(col);
153                 row_int = floor(row);
154                 bit_index = row_int * gdd->cols + col_int;
155                 arr_index = bit_index / 8;
156                 bit_mod = bit_index % 8;
157
158                 gdd->data[arr_index] |= 1 << bit_mod;
159                 offset += mod;
160                 bytes -= mod;
161         }
162 }
163
164 void print_gdd(struct graph_dot_data *gdd)
165 {
166         int col = 0;
167         int row = 0;
168         int arr_index;
169         u64 val;
170         int bit_index;
171         int bit_mod;
172
173         for (row = gdd->rows - 1; row >= 0; row--) {
174                 for (col = 0; col < gdd->cols; col++) {
175                         bit_index = row * gdd->cols + col;
176                         arr_index = bit_index / sizeof(unsigned long);
177                         bit_mod = bit_index % sizeof(unsigned long);
178
179                         val = gdd->data[arr_index];
180                         if (val & (1 << bit_mod))
181                                 printf("*");
182                         else
183                                 printf(" ");
184                 }
185                 printf("\n");
186         }
187 }
188
189 static double rolling_avg(struct graph_line_pair *data, int index, int distance)
190 {
191         double sum = 0;
192         int start;
193
194         if (distance < 0)
195                 distance = 1;
196         if (distance > index) {
197                 start = 0;
198         } else {
199                 start = index - distance;
200         }
201         distance = 0;
202         while (start <= index) {
203                 double avg;
204
205                 if (data[start].count)
206                         avg = ((double)data[start].sum) / data[start].count;
207                 else
208                         avg= 0;
209
210                 sum += avg;
211                 distance++;
212                 start++;
213         }
214         return sum / distance;
215 }
216
217 void write_svg_header(int fd)
218 {
219         char *spaces = "                                                    \n";
220         char *header = "<svg  xmlns=\"http://www.w3.org/2000/svg\">\n";
221         char *filter1 ="<filter id=\"shadow\">\n "
222                 "<feOffset result=\"offOut\" in=\"SourceAlpha\" dx=\"4\" dy=\"4\" />\n "
223                 "<feGaussianBlur result=\"blurOut\" in=\"offOut\" stdDeviation=\"2\" />\n "
224                 "<feBlend in=\"SourceGraphic\" in2=\"blurOut\" mode=\"normal\" />\n "
225                 "</filter>\n";
226         char *filter2 ="<filter id=\"textshadow\" x=\"0\" y=\"0\" width=\"200%\" height=\"200%\">\n "
227                 "<feOffset result=\"offOut\" in=\"SourceAlpha\" dx=\"1\" dy=\"1\" />\n "
228                 "<feGaussianBlur result=\"blurOut\" in=\"offOut\" stdDeviation=\"1.5\" />\n "
229                 "<feBlend in=\"SourceGraphic\" in2=\"blurOut\" mode=\"normal\" />\n "
230                 "</filter>\n";
231         char *filter3 ="<filter id=\"labelshadow\" x=\"0\" y=\"0\" width=\"200%\" height=\"200%\">\n "
232                 "<feOffset result=\"offOut\" in=\"SourceGraphic\" dx=\"3\" dy=\"3\" />\n "
233                 "<feColorMatrix result=\"matrixOut\" in=\"offOut\" type=\"matrix\" "
234                 "values=\"0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0\" /> "
235                 "<feGaussianBlur result=\"blurOut\" in=\"offOut\" stdDeviation=\"2\" />\n "
236                 "<feBlend in=\"SourceGraphic\" in2=\"blurOut\" mode=\"normal\" />\n "
237                 "</filter>\n";
238         char *defs_start = "<defs>\n";
239         char *defs_close = "</defs>\n";
240         final_width = 0;
241         final_height = 0;
242
243         write(fd, header, strlen(header));
244         /* write a bunch of spaces so we can stuff in the width and height later */
245         write(fd, spaces, strlen(spaces));
246         write(fd, spaces, strlen(spaces));
247         write(fd, spaces, strlen(spaces));
248
249         write(fd, defs_start, strlen(defs_start));
250         write(fd, filter1, strlen(filter1));
251         write(fd, filter2, strlen(filter2));
252         write(fd, filter3, strlen(filter3));
253         write(fd, defs_close, strlen(defs_close));
254 }
255
256 void write_drop_shadow(struct plot *plot)
257 {
258         snprintf(line, line_len, "<rect x=\"0\" y=\"%d\" width=\"%d\" height=\"%d\" fill=\"white\"/>\n",
259                  plot->start_y_offset, plot->total_width, 45);
260         write(plot->fd, line, strlen(line));
261
262         snprintf(line, line_len, "<path d=\"M %d %d h %d v %d h %d t %d %d V %d H %d Z\" "
263                  "fill=\"white\" filter=\"url(#shadow)\"/>",
264                 0, plot->start_y_offset,
265                 plot->total_width - graph_left_pad / 2,
266                 -plot->total_height, 24, 1, 1,
267                 plot->start_y_offset + 10, 0);
268         write(plot->fd, line, strlen(line));
269
270         snprintf(line, line_len, "<path d=\"M %d %d H %d V %d h %d V %d H %d Z\" "
271                  "fill=\"white\"/>",
272                 0, plot->start_y_offset - 15, /* start */
273                 plot->total_width - graph_left_pad / 2 - 10, /* hline over */
274                 plot->start_y_offset - plot->total_height, /* vline up */
275                 15, /*hline over */
276                 plot->start_y_offset, /* vline back down */
277                 0);
278         write(plot->fd, line, strlen(line));
279
280         plot->start_y_offset += 45;
281 }
282
283 /* svg y offset for the traditional 0,0 (bottom left corner) of the plot */
284 static int axis_y(void)
285 {
286         return plot_label_height + graph_height + graph_inner_y_margin;
287 }
288
289 /* this gives you the correct pixel for a given offset from the bottom left y axis */
290 static double axis_y_off_double(double y)
291 {
292         return plot_label_height + graph_height - y;
293 }
294
295 static int axis_y_off(int y)
296 {
297         return axis_y_off_double(y);
298 }
299
300 /* svg x axis offset from 0 */
301 static int axis_x(void)
302 {
303         return graph_left_pad;
304 }
305
306 /* the correct pixel for a given X offset */
307 static double axis_x_off_double(double x)
308 {
309         return graph_left_pad + graph_inner_x_margin + x;
310 }
311
312 static int axis_x_off(int x)
313 {
314         return (int)axis_x_off_double(x);
315 }
316
317 /*
318  * this draws a backing rectangle for the plot and it
319  * also creates a new svg element so our offsets can
320  * be relative to this one plot.
321  */
322 void setup_axis(struct plot *plot)
323 {
324         int ret;
325         int len;
326         int fd = plot->fd;
327         int bump_height = tick_font_size * 3 + axis_label_font_size;
328         int local_legend_width = legend_width;
329
330         if (plot->no_legend)
331                 local_legend_width = 0;
332
333         plot->total_width = axis_x_off(graph_width) + graph_left_pad / 2 + local_legend_width;
334         plot->total_height = axis_y() + tick_label_pad + tick_font_size;
335
336         if (plot->add_xlabel)
337                 plot->total_height += bump_height;
338
339         /* backing rect */
340         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"%d\" "
341                  "height=\"%d\" fill=\"white\" stroke=\"none\"/>",
342                  plot->start_x_offset,
343                 plot->start_y_offset, plot->total_width + 40,
344                 plot->total_height + 20);
345         len = strlen(line);
346         write(fd, line, len);
347
348         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"%d\" "
349                  "filter=\"url(#shadow)\" "
350                  "height=\"%d\" fill=\"white\" stroke=\"none\"/>",
351                  plot->start_x_offset + 15,
352                 plot->start_y_offset, plot->total_width, plot->total_height);
353         len = strlen(line);
354         write(fd, line, len);
355         plot->total_height += 20;
356         plot->total_width += 20;
357
358         if (plot->total_height + plot->start_y_offset > final_height)
359                 final_height = plot->total_height + plot->start_y_offset;
360         if (plot->start_x_offset + plot->total_width + 40 > final_width)
361                 final_width = plot->start_x_offset + plot->total_width + 40;
362
363         /* create an svg object for all our coords to be relative against */
364         snprintf(line, line_len, "<svg x=\"%d\" y=\"%d\">\n", plot->start_x_offset, plot->start_y_offset);
365         write(fd, line, strlen(line));
366
367         snprintf(line, 1024, "<path d=\"M%d %d h %d V %d H %d Z\" stroke=\"black\" stroke-width=\"2\" fill=\"none\"/>\n",
368                  axis_x(), axis_y(),
369                  graph_width + graph_inner_x_margin * 2, axis_y_off(graph_height) - graph_inner_y_margin,
370                  axis_x());
371         len = strlen(line);
372         ret = write(fd, line, len);
373         if (ret != len) {
374                 fprintf(stderr, "failed to write svg axis\n");
375                 exit(1);
376         }
377 }
378
379 /*
380  * this draws a backing rectangle for the plot and it
381  * also creates a new svg element so our offsets can
382  * be relative to this one plot.
383  */
384 void setup_axis_spindle(struct plot *plot)
385 {
386         int len;
387         int fd = plot->fd;
388         int bump_height = tick_font_size * 3 + axis_label_font_size;
389
390         legend_x_off = -60;
391
392         plot->total_width = axis_x_off(graph_width) + legend_width;
393         plot->total_height = axis_y() + tick_label_pad + tick_font_size;
394
395         if (plot->add_xlabel)
396                 plot->total_height += bump_height;
397
398         /* backing rect */
399         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"%d\" "
400                  "height=\"%d\" fill=\"white\" stroke=\"none\"/>",
401                  plot->start_x_offset,
402                 plot->start_y_offset, plot->total_width + 10,
403                 plot->total_height + 20);
404         len = strlen(line);
405         write(fd, line, len);
406
407         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"%d\" "
408                  "filter=\"url(#shadow)\" "
409                  "height=\"%d\" fill=\"white\" stroke=\"none\"/>",
410                  plot->start_x_offset + 15,
411                 plot->start_y_offset, plot->total_width - 30,
412                 plot->total_height);
413         len = strlen(line);
414         write(fd, line, len);
415         plot->total_height += 20;
416
417         if (plot->total_height + plot->start_y_offset > final_height)
418                 final_height = plot->total_height + plot->start_y_offset;
419         if (plot->start_x_offset + plot->total_width + 40 > final_width)
420                 final_width = plot->start_x_offset + plot->total_width + 40;
421
422         /* create an svg object for all our coords to be relative against */
423         snprintf(line, line_len, "<svg x=\"%d\" y=\"%d\">\n", plot->start_x_offset, plot->start_y_offset);
424         write(fd, line, strlen(line));
425
426 }
427
428 /* draw a plot title.  This should be done only once,
429  * and it bumps the plot width/height numbers by
430  * what it draws.
431  *
432  * Call this before setting up the first axis
433  */
434 void set_plot_title(struct plot *plot, char *title)
435 {
436         int len;
437         int fd = plot->fd;
438
439         plot->total_height = plot_title_height;
440         plot->total_width = axis_x_off(graph_width) + graph_left_pad / 2 + legend_width;
441
442         /* backing rect */
443         snprintf(line, line_len, "<rect x=\"0\" y=\"%d\" width=\"%d\" height=\"%d\" fill=\"white\" stroke=\"none\"/>",
444                 plot->start_y_offset, plot->total_width + 40, plot_title_height + 20);
445         len = strlen(line);
446         write(fd, line, len);
447
448         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
449                  "font-weight=\"bold\" fill=\"black\" style=\"text-anchor: %s\">%s</text>\n",
450                  axis_x_off(graph_width / 2),
451                 plot->start_y_offset + plot_title_height / 2,
452                 font_family, plot_title_font_size, "middle", title);
453         plot->start_y_offset += plot_title_height;
454         len = strlen(line);
455         write(fd, line, len);
456 }
457
458 #define TICK_MINI_STEPS 3
459
460 static double find_step(double first, double last, int num_ticks)
461 {
462         int mini_step[TICK_MINI_STEPS] = { 1, 2, 5 };
463         int cur_mini_step = 0;
464         double step = (last - first) / num_ticks;
465         double log10 = log(10);
466
467         /* Round to power of 10 */
468         step = exp(floor(log(step) / log10) * log10);
469         /* Scale down step to provide enough ticks */
470         while ((last - first) / (step * mini_step[cur_mini_step]) > num_ticks
471                && cur_mini_step < TICK_MINI_STEPS)
472                 cur_mini_step++;
473         step *= mini_step[cur_mini_step - 1];
474
475         return step;
476 }
477
478 /*
479  * create evenly spread out ticks along the xaxis.  if tick only is set
480  * this just makes the ticks, otherwise it labels each tick as it goes
481  */
482 void set_xticks(struct plot *plot, int num_ticks, int first, int last)
483 {
484         int pixels_per_tick;
485         double step;
486         int i;
487         int tick_y = axis_y_off(graph_tick_len) + graph_inner_y_margin;
488         int tick_x = axis_x();
489         int tick_only = plot->add_xlabel == 0;
490
491         int text_y = axis_y() + tick_label_pad;
492
493         char *middle = "middle";
494         char *start = "start";
495
496         step = find_step(first, last, num_ticks);
497         /*
498          * We don't want last two ticks to be too close together so subtract
499          * 20% of the step from the interval
500          */
501         num_ticks = (double)(last - first - step / 5) / step + 1;
502         pixels_per_tick = graph_width * step / (double)(last - first);
503
504         for (i = 0; i < num_ticks; i++) {
505                 char *anchor;
506                 if (i != 0) {
507                         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"2\" height=\"%d\" style=\"stroke:none;fill:black;\"/>\n",
508                                 tick_x, tick_y, graph_tick_len);
509                         write(plot->fd, line, strlen(line));
510                         anchor = middle;
511                 } else {
512                         anchor = start;
513                 }
514
515                 if (!tick_only) {
516                         if (step >= 1)
517                                 snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
518                                         "fill=\"black\" style=\"text-anchor: %s\">%d</text>\n",
519                                         tick_x, text_y, font_family, tick_font_size, anchor,
520                                         (int)(first + step * i));
521                         else
522                                 snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
523                                         "fill=\"black\" style=\"text-anchor: %s\">%.2f</text>\n",
524                                         tick_x, text_y, font_family, tick_font_size, anchor,
525                                         first + step * i);
526                         write(plot->fd, line, strlen(line));
527                 }
528                 tick_x += pixels_per_tick;
529         }
530
531         if (!tick_only) {
532                 if (step >= 1)
533                         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
534                                 "fill=\"black\" style=\"text-anchor: middle\">%d</text>\n",
535                                 axis_x_off(graph_width - 2),
536                                 text_y, font_family, tick_font_size, last);
537                 else
538                         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
539                                 "fill=\"black\" style=\"text-anchor: middle\">%.2f</text>\n",
540                                 axis_x_off(graph_width - 2),
541                                 text_y, font_family, tick_font_size, (double)last);
542                 write(plot->fd, line, strlen(line));
543         }
544 }
545
546 void set_ylabel(struct plot *plot, char *label)
547 {
548         int len;
549         int fd = plot->fd;
550
551         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" "
552                  "transform=\"rotate(-90 %d %d)\" font-weight=\"bold\" "
553                  "font-size=\"%d\" fill=\"black\" style=\"text-anchor: %s\">%s</text>\n",
554                  graph_left_pad / 2 - axis_label_font_size,
555                  axis_y_off(graph_height / 2),
556                  font_family,
557                  graph_left_pad / 2 - axis_label_font_size,
558                  (int)axis_y_off(graph_height / 2),
559                  axis_label_font_size, "middle", label);
560         len = strlen(line);
561         write(fd, line, len);
562 }
563
564 void set_xlabel(struct plot *plot, char *label)
565 {
566         int len;
567         int fd = plot->fd;
568         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" "
569                  "font-weight=\"bold\" "
570                  "font-size=\"%d\" fill=\"black\" style=\"text-anchor: %s\">%s</text>\n",
571                  axis_x_off(graph_width / 2),
572                  axis_y() + tick_font_size * 3 + axis_label_font_size / 2,
573                  font_family,
574                  axis_label_font_size, "middle", label);
575         len = strlen(line);
576         write(fd, line, len);
577
578 }
579
580 /*
581  * create evenly spread out ticks along the y axis.
582  * The ticks are labeled as it goes
583  */
584 void set_yticks(struct plot *plot, int num_ticks, int first, int last, char *units)
585 {
586         int pixels_per_tick = graph_height / num_ticks;
587         int step = (last - first) / num_ticks;
588         int i;
589         int tick_y = 0;
590         int text_x = axis_x() - 6;
591         int tick_x = axis_x();
592         char *anchor = "end";
593
594         for (i = 0; i < num_ticks; i++) {
595                 if (i != 0) {
596                         snprintf(line, line_len, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" "
597                                  "style=\"stroke:lightgray;stroke-width:2;stroke-dasharray:9,12;\"/>\n",
598                                 tick_x, axis_y_off(tick_y),
599                                 axis_x_off(graph_width), axis_y_off(tick_y));
600                         write(plot->fd, line, strlen(line));
601                 }
602
603                 snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
604                          "fill=\"black\" style=\"text-anchor: %s\">%d%s</text>\n",
605                         text_x,
606                         axis_y_off(tick_y - tick_font_size / 2),
607                         font_family, tick_font_size, anchor, first + step * i, units);
608                 write(plot->fd, line, strlen(line));
609                 tick_y += pixels_per_tick;
610         }
611         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
612                  "fill=\"black\" style=\"text-anchor: %s\">%d%s</text>\n",
613                  text_x, axis_y_off(graph_height), font_family, tick_font_size, anchor, last, units);
614         write(plot->fd, line, strlen(line));
615 }
616
617 void set_plot_label(struct plot *plot, char *label)
618 {
619         int len;
620         int fd = plot->fd;
621
622         snprintf(line, line_len, "<text x=\"%d\" y=\"%d\" font-family=\"%s\" "
623                  "font-size=\"%d\" fill=\"black\" style=\"text-anchor: %s\">%s</text>\n",
624                  axis_x() + graph_width / 2,
625                  plot_label_height / 2,
626                 font_family, plot_label_font_size, "middle", label);
627         len = strlen(line);
628         write(fd, line, len);
629 }
630
631 static void close_svg(int fd)
632 {
633         char *close_line = "</svg>\n";
634
635         write(fd, close_line, strlen(close_line));
636 }
637
638 int close_plot(struct plot *plot)
639 {
640         close_svg(plot->fd);
641         if (plot->direction == PLOT_DOWN)
642                 plot->start_y_offset += plot->total_height;
643         else if (plot->direction == PLOT_ACROSS)
644                 plot->start_x_offset += plot->total_width;
645         return 0;
646 }
647
648 struct plot *alloc_plot(void)
649 {
650         struct plot *plot;
651         plot = calloc(1, sizeof(*plot));
652         if (!plot) {
653                 fprintf(stderr, "Unable to allocate memory %s\n", strerror(errno));
654                 exit(1);
655         }
656         plot->fd = 0;
657         return plot;
658 }
659
660 int close_plot_file(struct plot *plot)
661 {
662         int ret;
663         ret = lseek(plot->fd, 0, SEEK_SET);
664         if (ret == (off_t)-1) {
665                 perror("seek");
666                 exit(1);
667         }
668         final_width = ((final_width  + 1) / 2) * 2;
669         final_height = ((final_height  + 1) / 2) * 2;
670         snprintf(line, line_len, "<svg  xmlns=\"http://www.w3.org/2000/svg\" "
671                  "width=\"%d\" height=\"%d\">\n",
672                  final_width, final_height);
673         write(plot->fd, line, strlen(line));
674         snprintf(line, line_len, "<rect x=\"0\" y=\"0\" width=\"%d\" "
675                  "height=\"%d\" fill=\"white\"/>\n", final_width, final_height);
676         write(plot->fd, line, strlen(line));
677         close(plot->fd);
678         plot->fd = 0;
679         return 0;
680 }
681
682 void set_plot_output(struct plot *plot, char *filename)
683 {
684         int fd;
685
686         if (plot->fd)
687                 close_plot_file(plot);
688         fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0600);
689         if (fd < 0) {
690                 fprintf(stderr, "Unable to open output file %s err %s\n", filename, strerror(errno));
691                 exit(1);
692         }
693         plot->fd = fd;
694         plot->start_y_offset = plot->start_x_offset = 0;
695         write_svg_header(fd);
696 }
697
698 char *byte_unit_names[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", "unobtainium" };
699 int MAX_BYTE_UNIT_SCALE = 9;
700
701 char *time_unit_names[] = { "n", "u", "m", "s" };
702 int MAX_TIME_UNIT_SCALE = 3;
703
704 void scale_line_graph_bytes(u64 *max, char **units, u64 factor)
705 {
706         int scale = 0;
707         u64 val = *max;
708         u64 div = 1;
709         while (val > factor * 64) {
710                 val /= factor;
711                 scale++;
712                 div *= factor;
713         }
714         *units = byte_unit_names[scale];
715         if (scale == 0)
716                 return;
717
718         if (scale > MAX_BYTE_UNIT_SCALE)
719                 scale = MAX_BYTE_UNIT_SCALE;
720
721         *max /= div;
722 }
723
724 void scale_line_graph_time(u64 *max, char **units)
725 {
726         int scale = 0;
727         u64 val = *max;
728         u64 div = 1;
729         while (val > 1000 * 10) {
730                 val /= 1000;
731                 scale++;
732                 div *= 1000;
733                 if (scale == MAX_TIME_UNIT_SCALE)
734                         break;
735         }
736         *units = time_unit_names[scale];
737         if (scale == 0)
738                 return;
739
740         *max /= div;
741 }
742
743 int svg_line_graph(struct plot *plot, struct graph_line_data *gld, char *color, int thresh1, int thresh2)
744 {
745         int i;
746         double val;
747         double avg;
748         int rolling;
749         int fd = plot->fd;
750         char *start = "<path d=\"";
751         double yscale = ((double)gld->max) / graph_height;
752         double xscale = (double)(gld->max_seconds - gld->min_seconds - 1) / graph_width;
753         char c = 'M';
754         double x;
755         int printed_header = 0;
756         int printed_lines = 0;
757
758         if (thresh1 && thresh2)
759                 rolling = 0;
760         else if (rolling_avg_secs)
761                 rolling = rolling_avg_secs;
762         else
763                 rolling = (gld->stop_seconds - gld->min_seconds) / 25;
764
765         for (i = gld->min_seconds; i < gld->stop_seconds; i++) {
766                 avg = rolling_avg(gld->data, i, rolling);
767                 if (yscale == 0)
768                         val = 0;
769                 else
770                         val = avg / yscale;
771
772                 if (val > graph_height)
773                         val = graph_height;
774                 if (val < 0)
775                         val = 0;
776
777                 x = (double)(i - gld->min_seconds) / xscale;
778                 if (!thresh1 && !thresh2) {
779
780                         if (!printed_header) {
781                                 write(fd, start, strlen(start));
782                                 printed_header = 1;
783                         }
784
785                         /* in full line mode, everything in the graph is connected */
786                         snprintf(line, line_len, "%c %d %d ", c, axis_x_off(x), axis_y_off(val));
787                         c = 'L';
788                         write(fd, line, strlen(line));
789                         printed_lines = 1;
790                 } else if (avg > thresh1 || avg > thresh2) {
791                         int len = 10;
792                         if (!printed_header) {
793                                 write(fd, start, strlen(start));
794                                 printed_header = 1;
795                         }
796
797                         /* otherwise, we just print a bar up there to show this one data point */
798                         if (i >= gld->stop_seconds - 2)
799                                 len = -10;
800
801                         /*
802                          * we don't use the rolling averages here to show high
803                          * points in the data
804                          */
805                         snprintf(line, line_len, "M %d %d h %d ", axis_x_off(x),
806                                  axis_y_off(val), len);
807                         write(fd, line, strlen(line));
808                         printed_lines = 1;
809                 }
810
811         }
812         if (printed_lines) {
813                 snprintf(line, line_len, "\" fill=\"none\" stroke=\"%s\" stroke-width=\"2\"/>\n", color);
814                 write(fd, line, strlen(line));
815         }
816         if (plot->timeline)
817                 svg_write_time_line(plot, plot->timeline);
818
819         return 0;
820 }
821
822 void svg_write_time_line(struct plot *plot, int col)
823 {
824         snprintf(line, line_len, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" "
825                                  "style=\"stroke:black;stroke-width:2;\"/>\n",
826                                  axis_x_off(col), axis_y_off(0),
827                                  axis_x_off(col), axis_y_off(graph_height));
828         write(plot->fd, line, strlen(line));
829 }
830
831 static int svg_add_io(int fd, double row, double col, double width, double height, char *color)
832 {
833         float rx = 0;
834
835         snprintf(line, line_len, "<rect x=\"%.2f\" y=\"%.2f\" width=\"%.1f\" height=\"%.1f\" "
836                  "rx=\"%.2f\" style=\"stroke:none;fill:%s;stroke-width:0\"/>\n",
837                  axis_x_off_double(col), axis_y_off_double(row), width, height, rx, color);
838         return write(fd, line, strlen(line));
839 }
840
841 int svg_io_graph_movie_array(struct plot *plot, struct plot_history *ph)
842 {
843         double cell_index;
844         double movie_row;
845         double movie_col;
846         int i;
847
848         for (i = 0; i < ph->num_used; i++) {
849                 cell_index = ph->history[i];
850                 movie_row = floor(cell_index / graph_width);
851                 movie_col = cell_index - movie_row * graph_width;
852                 svg_add_io(plot->fd, movie_row, movie_col, 4, 4, ph->color);
853         }
854         return 0;
855 }
856
857 static float spindle_steps = 0;
858
859 void rewind_spindle_steps(int num)
860 {
861         spindle_steps -= num * 0.01;
862 }
863
864 int svg_io_graph_movie_array_spindle(struct plot *plot, struct plot_history *ph)
865 {
866         double cell_index;
867         int i;
868         int num_circles = 0;
869         double cells_per_circle;
870         double circle_num;
871         double degrees_per_cell;
872         double rot;
873         double center_x;
874         double center_y;
875         double graph_width_extra = graph_width + graph_circle_extra;
876         double graph_height_extra = graph_height + graph_circle_extra;
877         double radius;;
878
879         if (graph_width_extra > graph_height_extra)
880                 graph_width_extra = graph_height_extra;
881
882         if (graph_width_extra < graph_height_extra)
883                 graph_height_extra = graph_width_extra;
884
885         radius = graph_width_extra;
886
887         center_x = axis_x_off_double(graph_width_extra / 2);
888         center_y = axis_y_off_double(graph_height_extra / 2);
889
890         snprintf(line, line_len, "<g transform=\"rotate(%.4f, %.2f, %.2f)\"> "
891                  "<circle cx=\"%.2f\" cy=\"%.2f\" "
892                  "stroke=\"black\" stroke-width=\"6\" "
893                  "r=\"%.2f\" fill=\"none\"/>\n",
894                  -spindle_steps * 1.2, center_x, center_y, center_x, center_y, graph_width_extra / 2);
895         write(plot->fd, line, strlen(line));
896         snprintf(line, line_len, "<circle cx=\"%.2f\" cy=\"%.2f\" "
897                 "stroke=\"none\" fill=\"red\" r=\"%.2f\"/>\n</g>\n",
898                 axis_x_off_double(graph_width_extra), center_y, 4.5);
899         write(plot->fd, line, strlen(line));
900         spindle_steps += 0.01;
901
902         radius = floor(radius / 2);
903         num_circles = radius / 4 - 3;
904         cells_per_circle = ph->history_max / num_circles;
905         degrees_per_cell = 360 / cells_per_circle;
906
907         for (i = 0; i < ph->num_used; i++) {
908                 cell_index = ph->history[i];
909                 circle_num = floor(cell_index / cells_per_circle);
910                 rot = cell_index - circle_num * cells_per_circle;
911                 circle_num = num_circles - circle_num;
912                 radius = circle_num * 4;
913
914                 rot = rot * degrees_per_cell;
915                 rot -= spindle_steps;
916                 snprintf(line, line_len, "<path transform=\"rotate(%.4f, %.2f, %.2f)\" "
917                          "d=\"M %.2f %.2f a %.2f %.2f 0 0 1 0 5\" "
918                          "stroke=\"%s\" stroke-width=\"4\"/>\n",
919                          rot, center_x, center_y,
920                          axis_x_off_double(graph_width_extra / 2 + radius) + 8, center_y,
921                          radius, radius, ph->color);
922
923                 write(plot->fd, line, strlen(line));
924         }
925         return 0;
926 }
927
928 static int add_plot_history(struct plot_history *ph, double val)
929 {
930         if (ph->num_used == ph->history_len) {
931                 ph->history = realloc(ph->history,
932                                       (ph->history_len + 4096) * sizeof(double));
933                 if (!ph->history) {
934                         perror("Unable to allocate memory");
935                         exit(1);
936                 }
937                 ph->history_len += 4096;
938         }
939         ph->history[ph->num_used++] = val;
940         return 0;
941 }
942
943 int svg_io_graph_movie(struct graph_dot_data *gdd, struct plot_history *ph, int col)
944 {
945         int row = 0;
946         int arr_index;
947         unsigned char val;
948         int bit_index;
949         int bit_mod;
950         double blocks_per_row = (gdd->max_offset - gdd->min_offset + 1) / gdd->rows;
951         double movie_blocks_per_cell = (gdd->max_offset - gdd->min_offset + 1) / (graph_width * graph_height);
952         double cell_index;
953         int margin_orig = graph_inner_y_margin;
954
955         graph_inner_y_margin += 5;
956         ph->history_max = (gdd->max_offset - gdd->min_offset + 1) / movie_blocks_per_cell;
957
958         for (row = gdd->rows - 1; row >= 0; row--) {
959                 bit_index = row * gdd->cols + col;
960                 arr_index = bit_index / 8;
961                 bit_mod = bit_index % 8;
962
963                 if (arr_index < 0)
964                         continue;
965                 val = gdd->data[arr_index];
966                 if (val & (1 << bit_mod)) {
967                         /* in bytes, linear offset from the start of the drive */
968                         cell_index = (double)row * blocks_per_row;
969
970                         /* a cell number in the graph */
971                         cell_index /= movie_blocks_per_cell;
972
973                         add_plot_history(ph, cell_index);
974                 }
975         }
976         graph_inner_y_margin = margin_orig;
977         return 0;
978 }
979
980 int svg_io_graph(struct plot *plot, struct graph_dot_data *gdd, char *color)
981 {
982         int fd = plot->fd;;
983         int col = 0;
984         int row = 0;
985         int arr_index;
986         unsigned char val;
987         int bit_index;
988         int bit_mod;
989
990         for (row = gdd->rows - 1; row >= 0; row--) {
991                 for (col = 0; col < gdd->cols; col++) {
992                         bit_index = row * gdd->cols + col;
993                         arr_index = bit_index / 8;
994                         bit_mod = bit_index % 8;
995
996                         if (arr_index < 0)
997                                 continue;
998                         val = gdd->data[arr_index];
999                         if (val & (1 << bit_mod))
1000                                 svg_add_io(fd, floor(row / io_graph_scale), col, 1.5, 1.5, color);
1001                 }
1002         }
1003         return 0;
1004 }
1005
1006 void svg_alloc_legend(struct plot *plot, int num_lines)
1007 {
1008         char **lines = calloc(num_lines, sizeof(char *));
1009         plot->legend_index = 0;
1010         plot->legend_lines = lines;
1011         plot->num_legend_lines = num_lines;
1012 }
1013
1014 void svg_free_legend(struct plot *plot)
1015 {
1016         int i;
1017         for (i = 0; i < plot->legend_index; i++)
1018                 free(plot->legend_lines[i]);
1019         free(plot->legend_lines);
1020         plot->legend_lines = NULL;
1021         plot->legend_index = 0;
1022 }
1023
1024 void svg_write_legend(struct plot *plot)
1025 {
1026         int legend_line_x = axis_x_off(graph_width) + legend_x_off;
1027         int legend_line_y = axis_y_off(graph_height) + legend_y_off;
1028         int i;
1029
1030         if (plot->legend_index == 0)
1031                 return;
1032
1033         snprintf(line, line_len, "<rect x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" "
1034                  "fill=\"white\" filter=\"url(#shadow)\"/>\n",
1035                  legend_line_x - 15,
1036                  legend_line_y - 12,
1037                  legend_width,
1038                  plot->legend_index * legend_font_size + legend_font_size / 2 + 12);
1039
1040         write(plot->fd, line, strlen(line));
1041         for (i = 0; i < plot->legend_index; i++) {
1042                 write(plot->fd, plot->legend_lines[i],
1043                       strlen(plot->legend_lines[i]));
1044                 free(plot->legend_lines[i]);
1045         }
1046         free(plot->legend_lines);
1047         plot->legend_lines = NULL;
1048         plot->legend_index = 0;
1049 }
1050
1051 void svg_add_legend(struct plot *plot, char *text, char *extra, char *color)
1052 {
1053         int legend_line_x = axis_x_off(graph_width) + legend_x_off;
1054         int legend_line_y = axis_y_off(graph_height) + legend_y_off;
1055
1056         if (!text && (!extra || strlen(extra) == 0))
1057                 return;
1058
1059         legend_line_y += plot->legend_index * legend_font_size + legend_font_size / 2;
1060         snprintf(line, line_len, "<path d=\"M %d %d h 8\" stroke=\"%s\" stroke-width=\"8\" "
1061                  "filter=\"url(#labelshadow)\"/> "
1062                  "<text x=\"%d\" y=\"%d\" font-family=\"%s\" font-size=\"%d\" "
1063                  "fill=\"black\" style=\"text-anchor: left\">%s%s</text>\n",
1064                  legend_line_x, legend_line_y,
1065                  color, legend_line_x + 13,
1066                  legend_line_y + 4, font_family, legend_font_size,
1067                  text, extra);
1068
1069         plot->legend_lines[plot->legend_index++] = strdup(line);
1070 }
1071
1072 void set_legend_width(int longest_str)
1073 {
1074         if (longest_str)
1075                 legend_width = longest_str * (legend_font_size * 3 / 4) + 25;
1076         else
1077                 legend_width = 0;
1078 }
1079
1080 void set_rolling_avg(int rolling)
1081 {
1082         rolling_avg_secs = rolling;
1083 }
1084
1085 void set_io_graph_scale(int scale)
1086 {
1087         io_graph_scale = scale;
1088 }
1089
1090 void set_graph_size(int width, int height)
1091 {
1092         graph_width = width;
1093         graph_height = height;
1094 }
1095
1096 void get_graph_size(int *width, int *height)
1097 {
1098         *width = graph_width;
1099         *height = graph_height;
1100 }
1101
1102 void set_graph_height(int h)
1103 {
1104         graph_height = h;
1105 }
1106 void set_graph_width(int w)
1107 {
1108         graph_width = w;
1109 }