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