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