[PATCH] blkparse: optimize the read_sort_events() memory allocations
[blktrace.git] / blkparse.c
1 /*
2  * block queue tracing parse application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <locale.h>
32
33 #include "blktrace.h"
34 #include "rbtree.h"
35
36 #define SECONDS(x)              ((unsigned long long)(x) / 1000000000)
37 #define NANO_SECONDS(x)         ((unsigned long long)(x) % 1000000000)
38
39 static int backwards;
40 static unsigned long long genesis_time, last_reported_time;
41
42 struct io_stats {
43         unsigned long qreads, qwrites, creads, cwrites, mreads, mwrites;
44         unsigned long ireads, iwrites;
45         unsigned long long qread_kb, qwrite_kb, cread_kb, cwrite_kb;
46         unsigned long long iread_kb, iwrite_kb;
47 };
48
49 struct per_cpu_info {
50         int cpu;
51         int nelems;
52
53         int fd;
54         char fname[128];
55
56         struct io_stats io_stats;
57 };
58
59 struct per_process_info {
60         char name[16];
61         __u32 pid;
62         struct io_stats io_stats;
63         struct per_process_info *hash_next, *list_next;
64 };
65
66 #define PPI_HASH_SHIFT  (8)
67 static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
68 static struct per_process_info *ppi_list;
69
70 #define S_OPTS  "i:o:b:st"
71 static struct option l_opts[] = {
72         {
73                 .name = "input",
74                 .has_arg = 1,
75                 .flag = NULL,
76                 .val = 'i'
77         },
78         {
79                 .name = "output",
80                 .has_arg = 1,
81                 .flag = NULL,
82                 .val = 'o'
83         },
84         {
85                 .name = "batch",
86                 .has_arg = 1,
87                 .flag = NULL,
88                 .val = 'b'
89         },
90         {
91                 .name = "per program stats",
92                 .has_arg = 0,
93                 .flag = NULL,
94                 .val = 's'
95         },
96         {
97                 .name = "track ios",
98                 .has_arg = 0,
99                 .flag = NULL,
100                 .val = 't'
101         },
102         {
103                 .name = NULL,
104                 .has_arg = 0,
105                 .flag = NULL,
106                 .val = 0
107         }
108 };
109
110 static struct rb_root rb_sort_root;
111 static struct rb_root rb_track_root;
112
113 /*
114  * for sorting the displayed output
115  */
116 struct trace {
117         struct blk_io_trace *bit;
118         struct rb_node rb_node;
119 };
120
121 /*
122  * for tracking individual ios
123  */
124 struct io_track {
125         struct rb_node rb_node;
126
127         __u64 sector;
128         __u32 pid;
129         unsigned long long queue_time;
130         unsigned long long dispatch_time;
131         unsigned long long completion_time;
132 };
133
134 static int max_cpus;
135 static struct per_cpu_info *per_cpu_info;
136
137 static unsigned long long events;
138
139 static char *dev, *output_name;
140 static FILE *ofp;
141
142 static int per_process_stats;
143 static int track_ios;
144
145 #define RB_BATCH_DEFAULT        (1024)
146 static int rb_batch = RB_BATCH_DEFAULT;
147
148 #define is_done()       (*(volatile int *)(&done))
149 static volatile int done;
150
151 static inline unsigned long hash_long(unsigned long val)
152 {
153 #if __WORDSIZE == 32
154         val *= 0x9e370001UL;
155 #elif __WORDSIZE == 64
156         val *= 0x9e37fffffffc0001UL;
157 #else
158 #error unknown word size
159 #endif
160
161         return val >> (__WORDSIZE - PPI_HASH_SHIFT);
162 }
163
164 static inline void add_process_to_hash(struct per_process_info *ppi)
165 {
166         const int hash_idx = hash_long(ppi->pid);
167
168         ppi->hash_next = ppi_hash[hash_idx];
169         ppi_hash[hash_idx] = ppi;
170 }
171
172 static inline void add_process_to_list(struct per_process_info *ppi)
173 {
174         ppi->list_next = ppi_list;
175         ppi_list = ppi;
176 }
177
178 static struct per_process_info *find_process_by_pid(__u32 pid)
179 {
180         const int hash_idx = hash_long(pid);
181         struct per_process_info *ppi;
182
183         ppi = ppi_hash[hash_idx];
184         while (ppi) {
185                 if (ppi->pid == pid)
186                         return ppi;
187
188                 ppi = ppi->hash_next;
189         }
190
191         return NULL;
192 }
193
194 static inline int trace_rb_insert(struct trace *t)
195 {
196         struct rb_node **p = &rb_sort_root.rb_node;
197         struct rb_node *parent = NULL;
198         struct trace *__t;
199
200         while (*p) {
201                 parent = *p;
202                 __t = rb_entry(parent, struct trace, rb_node);
203
204                 if (t->bit->sequence < __t->bit->sequence)
205                         p = &(*p)->rb_left;
206                 else if (t->bit->sequence > __t->bit->sequence)
207                         p = &(*p)->rb_right;
208                 else {
209                         fprintf(stderr, "sequence alias!\n");
210                         return 1;
211                 }
212         }
213
214         rb_link_node(&t->rb_node, parent, p);
215         rb_insert_color(&t->rb_node, &rb_sort_root);
216         return 0;
217 }
218
219 static inline int track_rb_insert(struct io_track *iot)
220 {
221         struct rb_node **p = &rb_track_root.rb_node;
222         struct rb_node *parent = NULL;
223         struct io_track *__iot;
224
225         while (*p) {
226                 parent = *p;
227                 
228                 __iot = rb_entry(parent, struct io_track, rb_node);
229
230                 if (iot->sector < __iot->sector)
231                         p = &(*p)->rb_left;
232                 else if (iot->sector > __iot->sector)
233                         p = &(*p)->rb_right;
234                 else {
235                         fprintf(stderr, "sequence alias!\n");
236                         return 1;
237                 }
238         }
239
240         rb_link_node(&iot->rb_node, parent, p);
241         rb_insert_color(&iot->rb_node, &rb_track_root);
242         return 0;
243 }
244
245 static struct io_track *__find_track(__u64 sector)
246 {
247         struct rb_node **p = &rb_track_root.rb_node;
248         struct rb_node *parent = NULL;
249         struct io_track *__iot;
250
251         while (*p) {
252                 parent = *p;
253                 
254                 __iot = rb_entry(parent, struct io_track, rb_node);
255
256                 if (sector < __iot->sector)
257                         p = &(*p)->rb_left;
258                 else if (sector > __iot->sector)
259                         p = &(*p)->rb_right;
260                 else
261                         return __iot;
262         }
263
264         return NULL;
265 }
266
267 static struct io_track *find_track(__u64 sector)
268 {
269         struct io_track *iot = __find_track(sector);
270
271         iot = __find_track(sector);
272         if (!iot) {
273                 iot = malloc(sizeof(*iot));
274                 iot->sector = sector;
275                 track_rb_insert(iot);
276         }
277
278         return iot;
279 }
280
281 static void log_track_merge(struct blk_io_trace *t)
282 {
283         struct io_track *iot;
284
285         if (!track_ios)
286                 return;
287         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
288                 return;
289
290         iot = __find_track(t->sector - (t->bytes >> 10));
291         if (!iot) {
292                 fprintf(stderr, "Trying to merge on non-existing request\n");
293                 return;
294         }
295
296         rb_erase(&iot->rb_node, &rb_track_root);
297         iot->sector -= t->bytes >> 10;
298         track_rb_insert(iot);
299 }
300
301 static void log_track_queue(struct blk_io_trace *t)
302 {
303         struct io_track *iot;
304
305         if (!track_ios)
306                 return;
307
308         iot = find_track(t->sector);
309         iot->queue_time = t->time;
310 }
311
312 /*
313  * return time between queue and issue
314  */
315 static unsigned long long log_track_issue(struct blk_io_trace *t)
316 {
317         struct io_track *iot;
318
319         if (!track_ios)
320                 return -1;
321         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
322                 return -1;
323
324         iot = __find_track(t->sector);
325         if (!iot) {
326                 fprintf(stderr, "Trying to issue on non-existing request\n");
327                 return -1;
328         }
329
330         iot->dispatch_time = t->time;
331         return iot->dispatch_time - iot->queue_time;
332 }
333
334 /*
335  * return time between dispatch and complete
336  */
337 static unsigned long long log_track_complete(struct blk_io_trace *t)
338 {
339         unsigned long long elapsed;
340         struct io_track *iot;
341
342         if (!track_ios)
343                 return -1;
344         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
345                 return -1;
346
347         iot = __find_track(t->sector);
348         if (!iot) {
349                 fprintf(stderr, "Trying to dispatch on non-existing request\n");
350                 return -1;
351         }
352
353         iot->completion_time = t->time;
354         elapsed = iot->completion_time - iot->dispatch_time;
355
356         /*
357          * kill the trace, we don't need it after completion
358          */
359         rb_erase(&iot->rb_node, &rb_track_root);
360         free(iot);
361
362         return elapsed;
363 }
364
365
366 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
367 {
368         struct per_process_info *ppi = find_process_by_pid(pid);
369
370         if (!ppi) {
371                 ppi = malloc(sizeof(*ppi));
372                 memset(ppi, 0, sizeof(*ppi));
373                 strncpy(ppi->name, name, sizeof(ppi->name));
374                 ppi->pid = pid;
375                 add_process_to_hash(ppi);
376                 add_process_to_list(ppi);
377         }
378
379         return &ppi->io_stats;
380 }
381
382 static void resize_cpu_info(int cpuid)
383 {
384         int new_space, new_max = cpuid + 1;
385         char *new_start;
386
387         per_cpu_info = realloc(per_cpu_info, new_max * sizeof(*per_cpu_info));
388         if (!per_cpu_info) {
389                 fprintf(stderr, "Cannot allocate CPU info -- %d x %d bytes\n",
390                         new_max, (int) sizeof(*per_cpu_info));
391                 exit(1);
392         }
393
394         new_start = (char *)per_cpu_info + (max_cpus * sizeof(*per_cpu_info));
395         new_space = (new_max - max_cpus) * sizeof(*per_cpu_info);
396         memset(new_start, 0, new_space);
397         max_cpus = new_max;
398 }
399
400 static struct per_cpu_info *get_cpu_info(int cpu)
401 {
402         struct per_cpu_info *pci;
403
404         if (cpu >= max_cpus)
405                 resize_cpu_info(cpu);
406
407         /*
408          * ->cpu might already be set, but just set it unconditionally
409          */
410         pci = &per_cpu_info[cpu];
411         pci->cpu = cpu;
412
413         return pci;
414 }
415
416 static inline void check_time(struct blk_io_trace *bit)
417 {
418         unsigned long long this = bit->time;
419         unsigned long long last = last_reported_time;
420
421         backwards = (this < last) ? 'B' : ' ';
422         last_reported_time = this;
423 }
424
425 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
426                                int rw)
427 {
428         if (rw) {
429                 ios->mwrites++;
430                 ios->qwrite_kb += t->bytes >> 10;
431         } else {
432                 ios->mreads++;
433                 ios->qread_kb += t->bytes >> 10;
434         }
435 }
436
437 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
438                              int rw)
439 {
440         __account_m(&pci->io_stats, t, rw);
441
442         if (per_process_stats) {
443                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
444
445                 __account_m(ios, t, rw);
446         }
447 }
448
449 static inline void __account_q(struct io_stats *ios, struct blk_io_trace *t,
450                                int rw)
451 {
452         if (rw) {
453                 ios->qwrites++;
454                 ios->qwrite_kb += t->bytes >> 10;
455         } else {
456                 ios->qreads++;
457                 ios->qread_kb += t->bytes >> 10;
458         }
459 }
460
461 static inline void account_q(struct blk_io_trace *t, struct per_cpu_info *pci,
462                              int rw)
463 {
464         __account_q(&pci->io_stats, t, rw);
465
466         if (per_process_stats) {
467                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
468
469                 __account_q(ios, t, rw);
470         }
471 }
472
473 static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
474 {
475         if (rw) {
476                 ios->cwrites++;
477                 ios->cwrite_kb += bytes >> 10;
478         } else {
479                 ios->creads++;
480                 ios->cread_kb += bytes >> 10;
481         }
482 }
483
484 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
485                              int rw, int bytes)
486 {
487         __account_c(&pci->io_stats, rw, bytes);
488
489         if (per_process_stats) {
490                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
491
492                 __account_c(ios, rw, bytes);
493         }
494 }
495
496 static inline void __account_i(struct io_stats *ios, int rw, unsigned int bytes)
497 {
498         if (rw) {
499                 ios->iwrites++;
500                 ios->iwrite_kb += bytes >> 10;
501         } else {
502                 ios->ireads++;
503                 ios->iread_kb += bytes >> 10;
504         }
505 }
506
507 static inline void account_i(struct blk_io_trace *t, struct per_cpu_info *pci,
508                              int rw)
509 {
510         __account_i(&pci->io_stats, rw, t->bytes);
511
512         if (per_process_stats) {
513                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
514
515                 __account_i(ios, rw, t->bytes);
516         }
517 }
518
519 static void output(struct per_cpu_info *pci, char *s)
520 {
521         fprintf(ofp, "%s", s);
522 }
523
524 static char hstring[256];
525 static char tstring[256];
526
527 static inline char *setup_header(struct per_cpu_info *pci,
528                                  struct blk_io_trace *t, char act)
529 {
530         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
531         int b = t->action & BLK_TC_ACT(BLK_TC_BARRIER);
532         int s = t->action & BLK_TC_ACT(BLK_TC_SYNC);
533         char rwbs[4];
534         int i = 0;
535
536         if (w)
537                 rwbs[i++] = 'W';
538         else
539                 rwbs[i++] = 'R';
540         if (b)
541                 rwbs[i++] = 'B';
542         if (s)
543                 rwbs[i++] = 'S';
544
545         rwbs[i] = '\0';
546
547         sprintf(hstring, "%2d %15ld %5Lu.%09Lu %5u %c %3s",
548                 pci->cpu,
549                 (unsigned long)t->sequence, SECONDS(t->time), 
550                 NANO_SECONDS(t->time), t->pid, act, rwbs);
551
552         return hstring;
553 }
554
555 static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
556                          char act)
557 {
558         unsigned long long elapsed = log_track_complete(t);
559
560         if (elapsed != -1ULL) {
561                 double usec = (double) elapsed / 1000;
562
563                 sprintf(tstring,"%s %Lu + %u (%4.2f) [%d]\n",
564                         setup_header(pci, t, act),
565                         (unsigned long long)t->sector, t->bytes >> 9,
566                         usec, t->error);
567         } else {
568                 sprintf(tstring,"%s %Lu + %u [%d]\n", setup_header(pci, t, act),
569                         (unsigned long long)t->sector, t->bytes >> 9, t->error);
570         }
571         
572         output(pci, tstring);
573 }
574
575 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
576                       char act)
577 {
578         log_track_queue(t);
579
580         sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
581                 (unsigned long long)t->sector, t->bytes >> 9, t->comm);
582         output(pci, tstring);
583 }
584
585 static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
586                       char act)
587 {
588         unsigned long long elapsed = log_track_issue(t);
589
590         if (elapsed != -1ULL) {
591                 double usec = (double) elapsed / 1000;
592
593                 sprintf(tstring,"%s %Lu + %u (%4.2f) [%s]\n",
594                         setup_header(pci, t, act),
595                         (unsigned long long)t->sector, t->bytes >> 9,
596                         usec, t->comm);
597         } else {
598                 sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
599                         (unsigned long long)t->sector, t->bytes >> 9, t->comm);
600         }
601
602         output(pci, tstring);
603 }
604
605 static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
606                       char act)
607 {
608         log_track_merge(t);
609
610         sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
611                 (unsigned long long)t->sector, t->bytes >> 9, t->comm);
612         output(pci, tstring);
613 }
614
615 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
616                         char act)
617 {
618         sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
619                 (unsigned long long)t->sector, t->bytes >> 9, t->comm);
620         output(pci, tstring);
621 }
622
623 static int log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char act)
624 {
625         unsigned char *buf;
626         int i;
627
628         sprintf(tstring,"%s ", setup_header(pci, t, act));
629         output(pci, tstring);
630
631         buf = (unsigned char *) t + sizeof(*t);
632         for (i = 0; i < t->pdu_len; i++) {
633                 sprintf(tstring,"%02x ", buf[i]);
634                 output(pci, tstring);
635         }
636
637         if (act == 'C') {
638                 sprintf(tstring,"[%d]\n", t->error);
639                 output(pci, tstring);
640         } else {
641                 sprintf(tstring,"[%s]\n", t->comm);
642                 output(pci, tstring);
643         }
644         return 0;
645 }
646
647 static int dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
648 {
649         int ret = 0;
650
651         switch (t->action & 0xffff) {
652                 case __BLK_TA_QUEUE:
653                         log_generic(pci, t, 'Q');
654                         break;
655                 case __BLK_TA_GETRQ:
656                         log_generic(pci, t, 'G');
657                         break;
658                 case __BLK_TA_SLEEPRQ:
659                         log_generic(pci, t, 'S');
660                         break;
661                 case __BLK_TA_REQUEUE:
662                         log_generic(pci, t, 'R');
663                         break;
664                 case __BLK_TA_ISSUE:
665                         ret = log_pc(pci, t, 'D');
666                         break;
667                 case __BLK_TA_COMPLETE:
668                         log_pc(pci, t, 'C');
669                         break;
670                 default:
671                         fprintf(stderr, "Bad pc action %x\n", t->action);
672                         ret = 1;
673                         break;
674         }
675         
676         return ret;
677 }
678
679 static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
680 {
681         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
682         int act = t->action & 0xffff;
683
684         switch (act) {
685                 case __BLK_TA_QUEUE:
686                         account_q(t, pci, w);
687                         log_queue(pci, t, 'Q');
688                         break;
689                 case __BLK_TA_BACKMERGE:
690                         account_m(t, pci, w);
691                         log_merge(pci, t, 'M');
692                         break;
693                 case __BLK_TA_FRONTMERGE:
694                         account_m(t, pci, w);
695                         log_merge(pci, t, 'F');
696                         break;
697                 case __BLK_TA_GETRQ:
698                         log_generic(pci, t, 'G');
699                         break;
700                 case __BLK_TA_SLEEPRQ:
701                         log_generic(pci, t, 'S');
702                         break;
703                 case __BLK_TA_REQUEUE:
704                         account_c(t, pci, w, -t->bytes);
705                         log_queue(pci, t, 'R');
706                         break;
707                 case __BLK_TA_ISSUE:
708                         account_i(t, pci, w);
709                         log_issue(pci, t, 'D');
710                         break;
711                 case __BLK_TA_COMPLETE:
712                         account_c(t, pci, w, t->bytes);
713                         log_complete(pci, t, 'C');
714                         break;
715                 default:
716                         fprintf(stderr, "Bad fs action %x\n", t->action);
717                         break;
718         }
719 }
720
721 static int dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci)
722 {
723         int ret = 0;
724
725         if (t->action & BLK_TC_ACT(BLK_TC_PC))
726                 ret = dump_trace_pc(t, pci);
727         else
728                 dump_trace_fs(t, pci);
729
730         events++;
731         return ret;
732 }
733
734 static void dump_io_stats(struct io_stats *ios, char *msg)
735 {
736         fprintf(ofp, "%s\n", msg);
737
738         fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
739         fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
740
741         fprintf(ofp, " Read Dispatches: %'8lu, %'8LuKiB\t", ios->ireads, ios->iread_kb);
742         fprintf(ofp, " Write Dispatches: %'8lu, %'8LuKiB\n", ios->iwrites,ios->iwrite_kb);
743         fprintf(ofp, " Reads Completed: %'8lu, %'8LuKiB\t", ios->creads, ios->cread_kb);
744         fprintf(ofp, " Writes Completed: %'8lu, %'8LuKiB\n", ios->cwrites,ios->cwrite_kb);
745         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
746
747         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
748 }
749
750 static void show_process_stats(void)
751 {
752         struct per_process_info *ppi;
753
754         ppi = ppi_list;
755         while (ppi) {
756                 dump_io_stats(&ppi->io_stats, ppi->name);
757                 ppi = ppi->list_next;
758         }
759
760         fprintf(ofp, "\n");
761 }
762
763 static void show_cpu_stats(void)
764 {
765         struct per_cpu_info foo, *pci;
766         struct io_stats *ios;
767         int i, pci_events = 0;
768
769         memset(&foo, 0, sizeof(foo));
770
771         for (i = 0; i < max_cpus; i++) {
772                 char cpu[8];
773
774                 pci = &per_cpu_info[i];
775                 ios = &pci->io_stats;
776
777                 if (!pci->nelems)
778                         continue;
779
780                 foo.io_stats.qreads += ios->qreads;
781                 foo.io_stats.qwrites += ios->qwrites;
782                 foo.io_stats.creads += ios->creads;
783                 foo.io_stats.cwrites += ios->cwrites;
784                 foo.io_stats.mreads += ios->mreads;
785                 foo.io_stats.mwrites += ios->mwrites;
786                 foo.io_stats.ireads += ios->ireads;
787                 foo.io_stats.iwrites += ios->iwrites;
788                 foo.io_stats.qread_kb += ios->qread_kb;
789                 foo.io_stats.qwrite_kb += ios->qwrite_kb;
790                 foo.io_stats.cread_kb += ios->cread_kb;
791                 foo.io_stats.cwrite_kb += ios->cwrite_kb;
792                 foo.io_stats.iread_kb += ios->iread_kb;
793                 foo.io_stats.iwrite_kb += ios->iwrite_kb;
794
795                 snprintf(cpu, sizeof(cpu) - 1, "CPU%d:", i);
796                 dump_io_stats(ios, cpu);
797                 pci_events++;
798         }
799
800         if (pci_events > 1) {
801                 fprintf(ofp, "\n");
802                 dump_io_stats(&foo.io_stats, "Total:");
803         }
804
805         fprintf(ofp, "\nEvents: %'Lu\n", events);
806 }
807
808 #define min(a, b)       ((a) < (b) ? (a) : (b))
809
810 static struct blk_io_trace *find_trace(void *p, unsigned long offset, int nr)
811 {
812         unsigned long max_offset = min(offset,nr * sizeof(struct blk_io_trace));
813         unsigned long off;
814         struct blk_io_trace *bit;
815         __u32 magic;
816
817         for (off = 0; off < max_offset; off++) {
818                 bit = p + off;
819
820                 magic = be32_to_cpu(bit->magic);
821                 if ((magic & 0xffffff00) == BLK_IO_TRACE_MAGIC)
822                         return bit;
823         }
824
825         return NULL;
826 }
827
828 static int sort_entries(void *traces, unsigned long offset, int nr)
829 {
830         struct per_cpu_info *pci;
831         struct blk_io_trace *bit;
832         struct trace *t;
833         void *start = traces;
834         int nelems = 0;
835
836         while (traces - start <= offset - sizeof(*bit)) {
837                 if (!nr)
838                         break;
839
840                 bit = find_trace(traces, offset - (traces - start), nr);
841                 if (!bit)
842                         break;
843
844                 t = malloc(sizeof(*t));
845                 t->bit = bit;
846                 memset(&t->rb_node, 0, sizeof(t->rb_node));
847
848                 trace_to_cpu(bit);
849
850                 if (verify_trace(bit))
851                         break;
852
853                 pci = get_cpu_info(bit->cpu);
854                 pci->nelems++;
855
856                 if (trace_rb_insert(t))
857                         return -1;
858
859                 traces += sizeof(*bit) + bit->pdu_len;
860                 nelems++;
861                 nr--;
862         }
863
864         return nelems;
865 }
866
867 static void free_entries_rb(void)
868 {
869         struct rb_node *n;
870
871         while ((n = rb_first(&rb_sort_root)) != NULL) {
872                 struct trace *t = rb_entry(n, struct trace, rb_node);
873
874                 rb_erase(&t->rb_node, &rb_sort_root);
875                 free(t);
876         }
877 }
878
879 static void show_entries_rb(void)
880 {
881         struct blk_io_trace *bit;
882         struct rb_node *n;
883         struct trace *t;
884         int cpu;
885
886         n = rb_first(&rb_sort_root);
887         if (!n)
888                 return;
889
890         do {
891                 t = rb_entry(n, struct trace, rb_node);
892                 bit = t->bit;
893
894                 cpu = bit->cpu;
895                 if (cpu > max_cpus) {
896                         fprintf(stderr, "CPU number too large (%d)\n", cpu);
897                         break;
898                 }
899
900                 if (genesis_time == 0)
901                         genesis_time = bit->time;
902                 bit->time -= genesis_time;
903
904                 check_time(bit);
905
906                 if (dump_trace(bit, &per_cpu_info[cpu]))
907                         break;
908
909         } while ((n = rb_next(n)) != NULL);
910 }
911
912 static int read_data(int fd, void *buffer, int bytes, int block)
913 {
914         int ret, bytes_left, fl;
915         void *p;
916
917         fl = fcntl(fd, F_GETFL);
918
919         if (!block)
920                 fcntl(fd, F_SETFL, fl | O_NONBLOCK);
921         else
922                 fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
923
924         bytes_left = bytes;
925         p = buffer;
926         while (bytes_left > 0) {
927                 ret = read(fd, p, bytes_left);
928                 if (!ret)
929                         return 1;
930                 else if (ret < 0) {
931                         if (errno != EAGAIN)
932                                 perror("read");
933                         return -1;
934                 } else {
935                         p += ret;
936                         bytes_left -= ret;
937                 }
938         }
939
940         return 0;
941 }
942
943 static int do_file(void)
944 {
945         int i, nfiles;
946
947         for (i = 0, nfiles = 0;; i++, nfiles++) {
948                 struct per_cpu_info *pci;
949                 struct stat st;
950                 void *tb;
951
952                 pci = get_cpu_info(i);
953
954                 snprintf(pci->fname, sizeof(pci->fname)-1,"%s_out.%d", dev, i);
955                 if (stat(pci->fname, &st) < 0)
956                         break;
957                 if (!st.st_size)
958                         continue;
959
960                 printf("Processing %s\n", pci->fname);
961
962                 tb = malloc(st.st_size);
963
964                 pci->fd = open(pci->fname, O_RDONLY);
965                 if (pci->fd < 0) {
966                         perror(pci->fname);
967                         break;
968                 }
969
970                 if (read_data(pci->fd, tb, st.st_size, 1))
971                         break;
972
973                 if (sort_entries(tb, st.st_size, ~0U) == -1)
974                         break;
975
976                 close(pci->fd);
977                 printf("\t%2d %10s %15d\n", i, pci->fname, pci->nelems);
978
979         }
980
981         if (!nfiles) {
982                 fprintf(stderr, "No files found\n");
983                 return 1;
984         }
985
986         show_entries_rb();
987         return 0;
988 }
989
990 static void resize_buffer(void **buffer, long *size, long offset)
991 {
992         long old_size = *size;
993
994         *size *= 2;
995         *buffer = realloc(*buffer, *size);
996         memset(*buffer + offset, 0, *size - old_size);
997 }
998
999 static int read_sort_events(int fd, void **buffer, long *max_offset)
1000 {
1001         long offset;
1002         int events;
1003
1004         if (*max_offset == 0) {
1005                 *max_offset = 128 * sizeof(struct blk_io_trace);
1006                 *buffer = malloc(*max_offset);
1007         }
1008
1009         events = 0;
1010         offset = 0;
1011
1012         do {
1013                 struct blk_io_trace *t;
1014                 int pdu_len;
1015
1016                 if (*max_offset - offset < sizeof(*t))
1017                         resize_buffer(buffer, max_offset, offset);
1018
1019                 if (read_data(fd, *buffer + offset, sizeof(*t), !events)) {
1020                         if (events)
1021                                 break;
1022
1023                         usleep(1000);
1024                         continue;
1025                 }
1026
1027                 t = *buffer + offset;
1028                 offset += sizeof(*t);
1029
1030                 pdu_len = be16_to_cpu(t->pdu_len);
1031                 if (pdu_len) {
1032                         if (*max_offset - offset < pdu_len)
1033                                 resize_buffer(buffer, max_offset, offset);
1034
1035                         if (read_data(fd, *buffer + offset, pdu_len, 1))
1036                                 break;
1037
1038                         offset += pdu_len;
1039                 }
1040
1041                 events++;
1042         } while (!is_done() && events < rb_batch);
1043
1044         return events;
1045 }
1046
1047 static int do_stdin(void)
1048 {
1049         int fd;
1050         void *ptr;
1051         long max_offset;
1052
1053         fd = dup(STDIN_FILENO);
1054         max_offset = 0;
1055         do {
1056                 int events;
1057
1058                 events = read_sort_events(fd, &ptr, &max_offset);
1059                 if (!events)
1060                         break;
1061         
1062                 if (sort_entries(ptr, ~0UL, events) == -1)
1063                         break;
1064
1065                 show_entries_rb();
1066                 free_entries_rb();
1067         } while (1);
1068
1069         free(ptr);
1070         close(fd);
1071         return 0;
1072 }
1073
1074 static void flush_output(void)
1075 {
1076         fflush(ofp);
1077 }
1078
1079 static void handle_sigint(int sig)
1080 {
1081         done = 1;
1082         flush_output();
1083 }
1084
1085 static void usage(char *prog)
1086 {
1087         fprintf(stderr, "Usage: %s -i <name> [-o <output>][-s]\n", prog);
1088 }
1089
1090 int main(int argc, char *argv[])
1091 {
1092         char *ofp_buffer;
1093         int c, ret, mode;
1094
1095         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
1096                 switch (c) {
1097                 case 'i':
1098                         dev = optarg;
1099                         break;
1100                 case 'o':
1101                         output_name = optarg;
1102                         break;
1103                 case 'b':
1104                         rb_batch = atoi(optarg);
1105                         if (rb_batch <= 0)
1106                                 rb_batch = RB_BATCH_DEFAULT;
1107                         break;
1108                 case 's':
1109                         per_process_stats = 1;
1110                         break;
1111                 case 't':
1112                         track_ios = 1;
1113                         break;
1114                 default:
1115                         usage(argv[0]);
1116                         return 1;
1117                 }
1118         }
1119
1120         if (!dev) {
1121                 usage(argv[0]);
1122                 return 1;
1123         }
1124
1125         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
1126         memset(&rb_track_root, 0, sizeof(rb_track_root));
1127
1128         signal(SIGINT, handle_sigint);
1129         signal(SIGHUP, handle_sigint);
1130         signal(SIGTERM, handle_sigint);
1131
1132         setlocale(LC_NUMERIC, "en_US");
1133
1134         if (!output_name) {
1135                 ofp = fdopen(STDOUT_FILENO, "w");
1136                 mode = _IOLBF;
1137         } else {
1138                 char ofname[128];
1139
1140                 snprintf(ofname, sizeof(ofname) - 1, "%s.log", output_name);
1141                 ofp = fopen(ofname, "w");
1142                 mode = _IOFBF;
1143         }
1144
1145         if (!ofp) {
1146                 perror("fopen");
1147                 return 1;
1148         }
1149
1150         ofp_buffer = malloc(4096);      
1151         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
1152                 perror("setvbuf");
1153                 return 1;
1154         }
1155
1156         if (!strcmp(dev, "-"))
1157                 ret = do_stdin();
1158         else
1159                 ret = do_file();
1160
1161         if (per_process_stats)
1162                 show_process_stats();
1163
1164         show_cpu_stats();
1165
1166         flush_output();
1167         return ret;
1168 }