[PATCH] blkparse: split format parsing into seperate file
[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 #include <limits.h>
33
34 #include "blktrace.h"
35 #include "rbtree.h"
36
37 static char blkparse_version[] = "0.90";
38
39 struct per_dev_info {
40         dev_t id;
41         char *name;
42
43         int backwards;
44         unsigned long long events;
45         unsigned long long last_reported_time;
46         unsigned long long last_read_time;
47         struct io_stats io_stats;
48         unsigned long last_sequence;
49         unsigned long skips;
50
51         int nfiles;
52         int ncpus;
53         struct per_cpu_info *cpus;
54 };
55
56 struct per_process_info {
57         char name[16];
58         __u32 pid;
59         struct io_stats io_stats;
60         struct per_process_info *hash_next, *list_next;
61
62         /*
63          * individual io stats
64          */
65         unsigned long long longest_allocation_wait[2];
66         unsigned long long longest_dispatch_wait[2];
67         unsigned long long longest_completion_wait[2];
68 };
69
70 #define PPI_HASH_SHIFT  (8)
71 static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
72 static struct per_process_info *ppi_list;
73 static int ppi_list_entries;
74
75 #define S_OPTS  "i:o:b:stqw:f:F:v"
76 static struct option l_opts[] = {
77         {
78                 .name = "input",
79                 .has_arg = required_argument,
80                 .flag = NULL,
81                 .val = 'i'
82         },
83         {
84                 .name = "output",
85                 .has_arg = required_argument,
86                 .flag = NULL,
87                 .val = 'o'
88         },
89         {
90                 .name = "batch",
91                 .has_arg = required_argument,
92                 .flag = NULL,
93                 .val = 'b'
94         },
95         {
96                 .name = "per program stats",
97                 .has_arg = no_argument,
98                 .flag = NULL,
99                 .val = 's'
100         },
101         {
102                 .name = "track ios",
103                 .has_arg = no_argument,
104                 .flag = NULL,
105                 .val = 't'
106         },
107         {
108                 .name = "quiet",
109                 .has_arg = no_argument,
110                 .flag = NULL,
111                 .val = 'q'
112         },
113         {
114                 .name = "stopwatch",
115                 .has_arg = required_argument,
116                 .flag = NULL,
117                 .val = 'w'
118         },
119         {
120                 .name = "format",
121                 .has_arg = required_argument,
122                 .flag = NULL,
123                 .val = 'f'
124         },
125         {
126                 .name = "format-spec",
127                 .has_arg = required_argument,
128                 .flag = NULL,
129                 .val = 'F'
130         },
131         {
132                 .name = "version",
133                 .has_arg = no_argument,
134                 .flag = NULL,
135                 .val = 'v'
136         },
137 };
138
139 /*
140  * for sorting the displayed output
141  */
142 struct trace {
143         struct blk_io_trace *bit;
144         struct rb_node rb_node;
145         struct trace *next;
146         int skipped;
147 };
148
149 static struct rb_root rb_sort_root;
150 static struct rb_root rb_track_root;
151
152 static struct trace *trace_list;
153
154 /*
155  * allocation cache
156  */
157 static struct blk_io_trace *bit_alloc_list;
158 static struct trace *t_alloc_list;
159
160 /*
161  * for tracking individual ios
162  */
163 struct io_track {
164         struct rb_node rb_node;
165
166         dev_t device;
167         __u64 sector;
168         __u32 pid;
169         unsigned long long allocation_time;
170         unsigned long long queue_time;
171         unsigned long long dispatch_time;
172         unsigned long long completion_time;
173 };
174
175 static int ndevices;
176 static struct per_dev_info *devices;
177 static char *get_dev_name(struct per_dev_info *, char *, int);
178
179 FILE *ofp = NULL;
180 static char *output_name;
181
182 static unsigned long long genesis_time;
183 static unsigned long long last_allowed_time;
184 static unsigned long long stopwatch_start;      /* start from zero by default */
185 static unsigned long long stopwatch_end = ULONG_LONG_MAX;       /* "infinity" */
186
187 static int per_process_stats;
188 static int track_ios;
189
190 #define RB_BATCH_DEFAULT        (512)
191 static int rb_batch = RB_BATCH_DEFAULT;
192
193 static int pipeline;
194
195 #define is_done()       (*(volatile int *)(&done))
196 static volatile int done;
197
198 static inline unsigned long hash_long(unsigned long val)
199 {
200 #if __WORDSIZE == 32
201         val *= 0x9e370001UL;
202 #elif __WORDSIZE == 64
203         val *= 0x9e37fffffffc0001UL;
204 #else
205 #error unknown word size
206 #endif
207
208         return val >> (__WORDSIZE - PPI_HASH_SHIFT);
209 }
210
211 static inline void add_process_to_hash(struct per_process_info *ppi)
212 {
213         const int hash_idx = hash_long(ppi->pid);
214
215         ppi->hash_next = ppi_hash[hash_idx];
216         ppi_hash[hash_idx] = ppi;
217 }
218
219 static inline void add_process_to_list(struct per_process_info *ppi)
220 {
221         ppi->list_next = ppi_list;
222         ppi_list = ppi;
223         ppi_list_entries++;
224 }
225
226 static struct per_process_info *find_process_by_pid(__u32 pid)
227 {
228         const int hash_idx = hash_long(pid);
229         struct per_process_info *ppi;
230
231         ppi = ppi_hash[hash_idx];
232         while (ppi) {
233                 if (ppi->pid == pid)
234                         return ppi;
235
236                 ppi = ppi->hash_next;
237         }
238
239         return NULL;
240 }
241
242 static inline int trace_rb_insert(struct trace *t)
243 {
244         struct rb_node **p = &rb_sort_root.rb_node;
245         struct rb_node *parent = NULL;
246         struct trace *__t;
247
248         while (*p) {
249                 parent = *p;
250                 __t = rb_entry(parent, struct trace, rb_node);
251
252                 if (t->bit->time < __t->bit->time)
253                         p = &(*p)->rb_left;
254                 else if (t->bit->time > __t->bit->time)
255                         p = &(*p)->rb_right;
256                 else if (t->bit->device < __t->bit->device)
257                         p = &(*p)->rb_left;
258                 else if (t->bit->device > __t->bit->device)
259                         p = &(*p)->rb_right;
260                 else if (t->bit->sequence < __t->bit->sequence)
261                         p = &(*p)->rb_left;
262                 else if (t->bit->sequence > __t->bit->sequence)
263                         p = &(*p)->rb_right;
264                 else if (t->bit->device == __t->bit->device) {
265                         fprintf(stderr,
266                                 "sequence alias (%d) on device %d,%d!\n",
267                                 t->bit->sequence,
268                                 MAJOR(t->bit->device), MINOR(t->bit->device));
269                         return 1;
270                 }
271         }
272
273         rb_link_node(&t->rb_node, parent, p);
274         rb_insert_color(&t->rb_node, &rb_sort_root);
275         return 0;
276 }
277
278 static inline int track_rb_insert(struct io_track *iot)
279 {
280         struct rb_node **p = &rb_track_root.rb_node;
281         struct rb_node *parent = NULL;
282         struct io_track *__iot;
283
284         while (*p) {
285                 parent = *p;
286
287                 __iot = rb_entry(parent, struct io_track, rb_node);
288
289                 if (iot->device < __iot->device)
290                         p = &(*p)->rb_left;
291                 else if (iot->device > __iot->device)
292                         p = &(*p)->rb_right;
293                 else if (iot->sector < __iot->sector)
294                         p = &(*p)->rb_left;
295                 else if (iot->sector > __iot->sector)
296                         p = &(*p)->rb_right;
297                 else {
298                         fprintf(stderr,
299                                 "sector alias (%Lu) on device %d,%d!\n",
300                                 (unsigned long long) iot->sector,
301                                 MAJOR(iot->device), MINOR(iot->device));
302                         return 1;
303                 }
304         }
305
306         rb_link_node(&iot->rb_node, parent, p);
307         rb_insert_color(&iot->rb_node, &rb_track_root);
308         return 0;
309 }
310
311 static struct io_track *__find_track(dev_t device, __u64 sector)
312 {
313         struct rb_node **p = &rb_track_root.rb_node;
314         struct rb_node *parent = NULL;
315         struct io_track *__iot;
316
317         while (*p) {
318                 parent = *p;
319                 
320                 __iot = rb_entry(parent, struct io_track, rb_node);
321
322                 if (device < __iot->device)
323                         p = &(*p)->rb_left;
324                 else if (device > __iot->device)
325                         p = &(*p)->rb_right;
326                 else if (sector < __iot->sector)
327                         p = &(*p)->rb_left;
328                 else if (sector > __iot->sector)
329                         p = &(*p)->rb_right;
330                 else
331                         return __iot;
332         }
333
334         return NULL;
335 }
336
337 static struct io_track *find_track(__u32 pid, dev_t device, __u64 sector)
338 {
339         struct io_track *iot;
340
341         iot = __find_track(device, sector);
342         if (!iot) {
343                 iot = malloc(sizeof(*iot));
344                 iot->pid = pid;
345                 iot->device = device;
346                 iot->sector = sector;
347                 track_rb_insert(iot);
348         }
349
350         return iot;
351 }
352
353 static void log_track_frontmerge(struct blk_io_trace *t)
354 {
355         struct io_track *iot;
356
357         if (!track_ios)
358                 return;
359
360         iot = __find_track(t->device, t->sector + (t->bytes >> 9));
361         if (!iot) {
362                 fprintf(stderr, "failed to find mergeable event\n");
363                 return;
364         }
365
366         rb_erase(&iot->rb_node, &rb_track_root);
367         iot->sector -= t->bytes >> 9;
368         track_rb_insert(iot);
369 }
370
371 static void log_track_getrq(struct blk_io_trace *t)
372 {
373         struct io_track *iot;
374
375         if (!track_ios)
376                 return;
377
378         iot = find_track(t->pid, t->device, t->sector);
379         iot->allocation_time = t->time;
380 }
381
382
383 /*
384  * return time between rq allocation and insertion
385  */
386 static unsigned long long log_track_insert(struct blk_io_trace *t)
387 {
388         unsigned long long elapsed;
389         struct io_track *iot;
390
391         if (!track_ios)
392                 return -1;
393
394         iot = find_track(t->pid, t->device, t->sector);
395         iot->queue_time = t->time;
396         elapsed = iot->queue_time - iot->allocation_time;
397
398         if (per_process_stats) {
399                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
400                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
401
402                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
403                         ppi->longest_allocation_wait[w] = elapsed;
404         }
405
406         return elapsed;
407 }
408
409 /*
410  * return time between queue and issue
411  */
412 static unsigned long long log_track_issue(struct blk_io_trace *t)
413 {
414         unsigned long long elapsed;
415         struct io_track *iot;
416
417         if (!track_ios)
418                 return -1;
419         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
420                 return -1;
421
422         iot = __find_track(t->device, t->sector);
423         if (!iot) {
424                 fprintf(stderr, "failed to find issue event\n");
425                 return -1;
426         }
427
428         iot->dispatch_time = t->time;
429         elapsed = iot->dispatch_time - iot->queue_time;
430
431         if (per_process_stats) {
432                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
433                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
434
435                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
436                         ppi->longest_dispatch_wait[w] = elapsed;
437         }
438
439         return elapsed;
440 }
441
442 /*
443  * return time between dispatch and complete
444  */
445 static unsigned long long log_track_complete(struct blk_io_trace *t)
446 {
447         unsigned long long elapsed;
448         struct io_track *iot;
449
450         if (!track_ios)
451                 return -1;
452         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
453                 return -1;
454
455         iot = __find_track(t->device, t->sector);
456         if (!iot) {
457                 fprintf(stderr, "failed to find complete event\n");
458                 return -1;
459         }
460
461         iot->completion_time = t->time;
462         elapsed = iot->completion_time - iot->dispatch_time;
463
464         if (per_process_stats) {
465                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
466                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
467
468                 if (ppi && elapsed > ppi->longest_completion_wait[w])
469                         ppi->longest_completion_wait[w] = elapsed;
470         }
471
472         /*
473          * kill the trace, we don't need it after completion
474          */
475         rb_erase(&iot->rb_node, &rb_track_root);
476         free(iot);
477
478         return elapsed;
479 }
480
481
482 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
483 {
484         struct per_process_info *ppi = find_process_by_pid(pid);
485
486         if (!ppi) {
487                 ppi = malloc(sizeof(*ppi));
488                 memset(ppi, 0, sizeof(*ppi));
489                 strncpy(ppi->name, name, sizeof(ppi->name));
490                 ppi->pid = pid;
491                 add_process_to_hash(ppi);
492                 add_process_to_list(ppi);
493         }
494
495         return &ppi->io_stats;
496 }
497
498
499 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
500 {
501         struct per_cpu_info *cpus = pdi->cpus;
502         int ncpus = pdi->ncpus;
503         int new_count = cpu + 1;
504         int new_space, size;
505         char *new_start;
506
507         size = new_count * sizeof(struct per_cpu_info);
508         cpus = realloc(cpus, size);
509         if (!cpus) {
510                 char name[20];
511                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
512                         get_dev_name(pdi, name, sizeof(name)), size);
513                 exit(1);
514         }
515
516         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
517         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
518         memset(new_start, 0, new_space);
519
520         pdi->ncpus = new_count;
521         pdi->cpus = cpus;
522 }
523
524 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
525 {
526         struct per_cpu_info *pci;
527
528         if (cpu >= pdi->ncpus)
529                 resize_cpu_info(pdi, cpu);
530
531         pci = &pdi->cpus[cpu];
532         pci->cpu = cpu;
533         return pci;
534 }
535
536
537 static int resize_devices(char *name)
538 {
539         int size = (ndevices + 1) * sizeof(struct per_dev_info);
540
541         devices = realloc(devices, size);
542         if (!devices) {
543                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
544                 return 1;
545         }
546         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
547         devices[ndevices].name = name;
548         ndevices++;
549         return 0;
550 }
551
552 static struct per_dev_info *get_dev_info(dev_t id)
553 {
554         struct per_dev_info *pdi;
555         int i;
556
557         for (i = 0; i < ndevices; i++) {
558                 if (!devices[i].id)
559                         devices[i].id = id;
560                 if (devices[i].id == id)
561                         return &devices[i];
562         }
563
564         if (resize_devices(NULL) != 0)
565                 return NULL;
566
567         pdi = &devices[ndevices - 1];
568         pdi->id = id;
569         pdi->last_sequence = -1;
570         pdi->last_read_time = 0;
571         return pdi;
572 }
573
574 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
575 {
576         if (pdi->name)
577                 snprintf(buffer, size, "%s", pdi->name);
578         else
579                 snprintf(buffer, size, "%d,%d", MAJOR(pdi->id), MINOR(pdi->id));
580         return buffer;
581 }
582
583 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
584 {
585         unsigned long long this = bit->time;
586         unsigned long long last = pdi->last_reported_time;
587
588         pdi->backwards = (this < last) ? 'B' : ' ';
589         pdi->last_reported_time = this;
590 }
591
592 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
593                                int rw)
594 {
595         if (rw) {
596                 ios->mwrites++;
597                 ios->qwrite_kb += t->bytes >> 10;
598         } else {
599                 ios->mreads++;
600                 ios->qread_kb += t->bytes >> 10;
601         }
602 }
603
604 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
605                              int rw)
606 {
607         __account_m(&pci->io_stats, t, rw);
608
609         if (per_process_stats) {
610                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
611
612                 __account_m(ios, t, rw);
613         }
614 }
615
616 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
617                                    int rw)
618 {
619         if (rw) {
620                 ios->qwrites++;
621                 ios->qwrite_kb += t->bytes >> 10;
622         } else {
623                 ios->qreads++;
624                 ios->qread_kb += t->bytes >> 10;
625         }
626 }
627
628 static inline void account_queue(struct blk_io_trace *t,
629                                  struct per_cpu_info *pci, int rw)
630 {
631         __account_queue(&pci->io_stats, t, rw);
632
633         if (per_process_stats) {
634                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
635
636                 __account_queue(ios, t, rw);
637         }
638 }
639
640 static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
641 {
642         if (rw) {
643                 ios->cwrites++;
644                 ios->cwrite_kb += bytes >> 10;
645         } else {
646                 ios->creads++;
647                 ios->cread_kb += bytes >> 10;
648         }
649 }
650
651 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
652                              int rw, int bytes)
653 {
654         __account_c(&pci->io_stats, rw, bytes);
655
656         if (per_process_stats) {
657                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
658
659                 __account_c(ios, rw, bytes);
660         }
661 }
662
663 static inline void __account_issue(struct io_stats *ios, int rw,
664                                    unsigned int bytes)
665 {
666         if (rw) {
667                 ios->iwrites++;
668                 ios->iwrite_kb += bytes >> 10;
669         } else {
670                 ios->ireads++;
671                 ios->iread_kb += bytes >> 10;
672         }
673 }
674
675 static inline void account_issue(struct blk_io_trace *t,
676                                  struct per_cpu_info *pci, int rw)
677 {
678         __account_issue(&pci->io_stats, rw, t->bytes);
679
680         if (per_process_stats) {
681                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
682
683                 __account_issue(ios, rw, t->bytes);
684         }
685 }
686
687 static inline void __account_unplug(struct io_stats *ios, int timer)
688 {
689         if (timer)
690                 ios->timer_unplugs++;
691         else
692                 ios->io_unplugs++;
693 }
694
695 static inline void account_unplug(struct blk_io_trace *t,
696                                   struct per_cpu_info *pci, int timer)
697 {
698         __account_unplug(&pci->io_stats, timer);
699
700         if (per_process_stats) {
701                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
702
703                 __account_unplug(ios, timer);
704         }
705 }
706
707 static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
708                          char *act)
709 {
710         process_fmt(act, pci, t, log_track_complete(t), 0, NULL);
711 }
712
713 static void log_insert(struct per_cpu_info *pci, struct blk_io_trace *t,
714                       char *act)
715 {
716         process_fmt(act, pci, t, log_track_insert(t), 0, NULL);
717 }
718
719 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
720                       char *act)
721 {
722         process_fmt(act, pci, t, -1, 0, NULL);
723 }
724
725 static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
726                       char *act)
727 {
728         process_fmt(act, pci, t, log_track_issue(t), 0, NULL);
729 }
730
731 static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
732                       char *act)
733 {
734         if (act[0] == 'F')
735                 log_track_frontmerge(t);
736
737         process_fmt(act, pci, t, -1ULL, 0, NULL);
738 }
739
740 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
741                         char *act)
742 {
743         process_fmt(act, pci, t, -1ULL, 0, NULL);
744 }
745
746 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
747                         char *act)
748 {
749         process_fmt(act, pci, t, -1ULL, 0, NULL);
750 }
751
752 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
753                       char *act)
754 {
755         process_fmt(act, pci, t, -1ULL, 0, NULL);
756 }
757
758 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
759                       char *act)
760 {
761         process_fmt(act, pci, t, -1ULL, 0, NULL);
762 }
763
764 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
765 {
766         unsigned char *buf = (unsigned char *) t + sizeof(*t);
767
768         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
769 }
770
771 static void dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
772 {
773         int act = t->action & 0xffff;
774
775         switch (act) {
776                 case __BLK_TA_QUEUE:
777                         log_generic(pci, t, "Q");
778                         break;
779                 case __BLK_TA_GETRQ:
780                         log_generic(pci, t, "G");
781                         break;
782                 case __BLK_TA_SLEEPRQ:
783                         log_generic(pci, t, "S");
784                         break;
785                 case __BLK_TA_REQUEUE:
786                         log_generic(pci, t, "R");
787                         break;
788                 case __BLK_TA_ISSUE:
789                         log_pc(pci, t, "D");
790                         break;
791                 case __BLK_TA_COMPLETE:
792                         log_pc(pci, t, "C");
793                         break;
794                 case __BLK_TA_INSERT:
795                         log_pc(pci, t, "I");
796                         break;
797                 default:
798                         fprintf(stderr, "Bad pc action %x\n", act);
799                         break;
800         }
801 }
802
803 static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
804 {
805         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
806         int act = t->action & 0xffff;
807
808         switch (act) {
809                 case __BLK_TA_QUEUE:
810                         account_queue(t, pci, w);
811                         log_queue(pci, t, "Q");
812                         break;
813                 case __BLK_TA_INSERT:
814                         log_insert(pci, t, "I");
815                         break;
816                 case __BLK_TA_BACKMERGE:
817                         account_m(t, pci, w);
818                         log_merge(pci, t, "M");
819                         break;
820                 case __BLK_TA_FRONTMERGE:
821                         account_m(t, pci, w);
822                         log_merge(pci, t, "F");
823                         break;
824                 case __BLK_TA_GETRQ:
825                         log_track_getrq(t);
826                         log_generic(pci, t, "G");
827                         break;
828                 case __BLK_TA_SLEEPRQ:
829                         log_generic(pci, t, "S");
830                         break;
831                 case __BLK_TA_REQUEUE:
832                         account_c(t, pci, w, -t->bytes);
833                         log_queue(pci, t, "R");
834                         break;
835                 case __BLK_TA_ISSUE:
836                         account_issue(t, pci, w);
837                         log_issue(pci, t, "D");
838                         break;
839                 case __BLK_TA_COMPLETE:
840                         account_c(t, pci, w, t->bytes);
841                         log_complete(pci, t, "C");
842                         break;
843                 case __BLK_TA_PLUG:
844                         log_action(pci, t, "P");
845                         break;
846                 case __BLK_TA_UNPLUG_IO:
847                         account_unplug(t, pci, 0);
848                         log_unplug(pci, t, "U");
849                         break;
850                 case __BLK_TA_UNPLUG_TIMER:
851                         account_unplug(t, pci, 1);
852                         log_unplug(pci, t, "UT");
853                         break;
854                 case __BLK_TA_SPLIT:
855                         log_split(pci, t, "X");
856                         break;
857                 case __BLK_TA_BOUNCE:
858                         log_generic(pci, t, "B");
859                         break;
860                 default:
861                         fprintf(stderr, "Bad fs action %x\n", t->action);
862                         break;
863         }
864 }
865
866 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
867                        struct per_dev_info *pdi)
868 {
869         if (t->action & BLK_TC_ACT(BLK_TC_PC))
870                 dump_trace_pc(t, pci);
871         else
872                 dump_trace_fs(t, pci);
873
874         pdi->events++;
875 }
876
877 static void dump_io_stats(struct io_stats *ios, char *msg)
878 {
879         fprintf(ofp, "%s\n", msg);
880
881         fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
882         fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
883
884         fprintf(ofp, " Read Dispatches: %'8lu, %'8LuKiB\t", ios->ireads, ios->iread_kb);
885         fprintf(ofp, " Write Dispatches: %'8lu, %'8LuKiB\n", ios->iwrites,ios->iwrite_kb);
886         fprintf(ofp, " Reads Completed: %'8lu, %'8LuKiB\t", ios->creads, ios->cread_kb);
887         fprintf(ofp, " Writes Completed: %'8lu, %'8LuKiB\n", ios->cwrites,ios->cwrite_kb);
888         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
889         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
890         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
891         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
892 }
893
894 static void dump_wait_stats(struct per_process_info *ppi)
895 {
896         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
897         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
898         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
899         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
900         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
901         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
902
903         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
904         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
905         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
906         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
907         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
908         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
909 }
910
911 static int ppi_name_compare(const void *p1, const void *p2)
912 {
913         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
914         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
915         int res;
916
917         res = strverscmp(ppi1->name, ppi2->name);
918         if (!res)
919                 res = ppi1->pid > ppi2->pid;
920
921         return res;
922 }
923
924 static void sort_process_list(void)
925 {
926         struct per_process_info **ppis;
927         struct per_process_info *ppi;
928         int i = 0;
929
930         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
931
932         ppi = ppi_list;
933         while (ppi) {
934                 ppis[i++] = ppi;
935                 ppi = ppi->list_next;
936         }
937
938         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
939
940         i = ppi_list_entries - 1;
941         ppi_list = NULL;
942         while (i >= 0) {
943                 ppi = ppis[i];
944
945                 ppi->list_next = ppi_list;
946                 ppi_list = ppi;
947                 i--;
948         }
949
950         free(ppis);
951 }
952
953 static void show_process_stats(void)
954 {
955         struct per_process_info *ppi;
956
957         sort_process_list();
958
959         ppi = ppi_list;
960         while (ppi) {
961                 char name[64];
962
963                 snprintf(name, sizeof(name)-1, "%s (%u)", ppi->name, ppi->pid);
964                 dump_io_stats(&ppi->io_stats, name);
965                 dump_wait_stats(ppi);
966                 ppi = ppi->list_next;
967         }
968
969         fprintf(ofp, "\n");
970 }
971
972 static void show_device_and_cpu_stats(void)
973 {
974         struct per_dev_info *pdi;
975         struct per_cpu_info *pci;
976         struct io_stats total, *ios;
977         int i, j, pci_events;
978         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
979         char name[32];
980
981         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
982
983                 memset(&total, 0, sizeof(total));
984                 pci_events = 0;
985
986                 if (i > 0)
987                         fprintf(ofp, "\n");
988
989                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
990                         if (!pci->nelems)
991                                 continue;
992
993                         ios = &pci->io_stats;
994                         total.qreads += ios->qreads;
995                         total.qwrites += ios->qwrites;
996                         total.creads += ios->creads;
997                         total.cwrites += ios->cwrites;
998                         total.mreads += ios->mreads;
999                         total.mwrites += ios->mwrites;
1000                         total.ireads += ios->ireads;
1001                         total.iwrites += ios->iwrites;
1002                         total.qread_kb += ios->qread_kb;
1003                         total.qwrite_kb += ios->qwrite_kb;
1004                         total.cread_kb += ios->cread_kb;
1005                         total.cwrite_kb += ios->cwrite_kb;
1006                         total.iread_kb += ios->iread_kb;
1007                         total.iwrite_kb += ios->iwrite_kb;
1008                         total.timer_unplugs += ios->timer_unplugs;
1009                         total.io_unplugs += ios->io_unplugs;
1010
1011                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1012                                  j, get_dev_name(pdi, name, sizeof(name)));
1013                         dump_io_stats(ios, line);
1014                         pci_events++;
1015                 }
1016
1017                 if (pci_events > 1) {
1018                         fprintf(ofp, "\n");
1019                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1020                                  get_dev_name(pdi, name, sizeof(name)));
1021                         dump_io_stats(&total, line);
1022                 }
1023
1024                 fprintf(ofp, "\nEvents (%s): %'Lu entries, %'lu skips\n",
1025                         get_dev_name(pdi, line, sizeof(line)), pdi->events,
1026                         pdi->skips);
1027         }
1028 }
1029
1030 static int sort_entries(void)
1031 {
1032         struct trace *t;
1033         int nr = 0;
1034
1035         while ((t = trace_list) != NULL) {
1036                 trace_list = t->next;
1037
1038                 if (verify_trace(t->bit))
1039                         continue;
1040                 if (trace_rb_insert(t))
1041                         break;
1042                 nr++;
1043         }
1044
1045         return nr;
1046 }
1047
1048 /*
1049  * struct trace and blktrace allocation cache, we do potentially
1050  * millions of mallocs for these structures while only using at most
1051  * a few thousand at the time
1052  */
1053 static inline void t_free(struct trace *t)
1054 {
1055         t->next = t_alloc_list;
1056         t_alloc_list = t;
1057 }
1058
1059 static inline struct trace *t_alloc(void)
1060 {
1061         struct trace *t = t_alloc_list;
1062
1063         if (t) {
1064                 t_alloc_list = t->next;
1065                 return t;
1066         }
1067
1068         return malloc(sizeof(*t));
1069 }
1070
1071 static inline void bit_free(struct blk_io_trace *bit)
1072 {
1073         /*
1074          * abuse a 64-bit field for a next pointer for the free item
1075          */
1076         bit->time = (__u64) (unsigned long) bit_alloc_list;
1077         bit_alloc_list = (struct blk_io_trace *) bit;
1078 }
1079
1080 static inline struct blk_io_trace *bit_alloc(void)
1081 {
1082         struct blk_io_trace *bit = bit_alloc_list;
1083
1084         if (bit) {
1085                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
1086                                  bit->time;
1087                 return bit;
1088         }
1089
1090         return malloc(sizeof(*bit));
1091 }
1092
1093 static void show_entries_rb(void)
1094 {
1095         struct per_dev_info *pdi = NULL;
1096         struct per_cpu_info *pci = NULL;
1097         struct blk_io_trace *bit;
1098         struct rb_node *n;
1099         struct trace *t;
1100
1101         while ((n = rb_first(&rb_sort_root)) != NULL) {
1102
1103                 if (done)
1104                         break;
1105
1106                 t = rb_entry(n, struct trace, rb_node);
1107                 bit = t->bit;
1108
1109                 if (!pdi || pdi->id != bit->device)
1110                         pdi = get_dev_info(bit->device);
1111
1112                 if (!pdi) {
1113                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1114                                 MAJOR(bit->device), MINOR(bit->device));
1115                         break;
1116                 }
1117
1118                 if (bit->cpu > pdi->ncpus) {
1119                         fprintf(stderr, "Unknown CPU ID? (%d, device %d,%d)\n",
1120                                 bit->cpu, MAJOR(bit->device),
1121                                 MINOR(bit->device));
1122                         break;
1123                 }
1124
1125                 /*
1126                  * back off displaying more info if we are out of sync
1127                  * on SMP systems. to prevent stalling on lost events,
1128                  * only allow an event to skip us a few times
1129                  */
1130                 if (bit->sequence != (pdi->last_sequence + 1)
1131                     && pdi->last_sequence != -1) {
1132                         if (t->skipped < 5) {
1133                                 t->skipped++;
1134                                 break;
1135                         } else {
1136                                 fprintf(stderr, "skipping from %lu to %u\n", pdi->last_sequence, bit->sequence);
1137                                 pdi->skips++;
1138                         }
1139                 }
1140
1141                 if (bit->time >= stopwatch_end || bit->time > last_allowed_time)
1142                         break;
1143
1144                 pdi->last_sequence = bit->sequence;
1145
1146                 if (bit->time >= stopwatch_start) {
1147                         check_time(pdi, bit);
1148
1149                         if (!pci || pci->cpu != bit->cpu)
1150                                 pci = get_cpu_info(pdi, bit->cpu);
1151
1152                         dump_trace(bit, pci, pdi);
1153                 }
1154
1155                 rb_erase(&t->rb_node, &rb_sort_root);
1156                 bit_free(bit);
1157                 t_free(t);
1158         }
1159 }
1160
1161 static int read_data(int fd, void *buffer, int bytes, int block)
1162 {
1163         int ret, bytes_left, fl;
1164         void *p;
1165
1166         fl = fcntl(fd, F_GETFL);
1167
1168         if (!block)
1169                 fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1170         else
1171                 fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1172
1173         bytes_left = bytes;
1174         p = buffer;
1175         while (bytes_left > 0) {
1176                 ret = read(fd, p, bytes_left);
1177                 if (!ret)
1178                         return 1;
1179                 else if (ret < 0) {
1180                         if (errno != EAGAIN)
1181                                 perror("read");
1182                         return -1;
1183                 } else {
1184                         p += ret;
1185                         bytes_left -= ret;
1186                 }
1187         }
1188
1189         return 0;
1190 }
1191
1192 static int read_events(int fd)
1193 {
1194         struct per_dev_info *pdi = NULL;
1195         int events = 0;
1196
1197         while (!is_done() && events < rb_batch) {
1198                 struct blk_io_trace *bit;
1199                 struct trace *t;
1200                 int pdu_len;
1201                 __u32 magic;
1202
1203                 bit = bit_alloc();
1204
1205                 if (read_data(fd, bit, sizeof(*bit), !events))
1206                         break;
1207
1208                 magic = be32_to_cpu(bit->magic);
1209                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1210                         fprintf(stderr, "Bad magic %x\n", magic);
1211                         break;
1212                 }
1213
1214                 pdu_len = be16_to_cpu(bit->pdu_len);
1215                 if (pdu_len) {
1216                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1217
1218                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1))
1219                                 break;
1220
1221                         bit = ptr;
1222                 }
1223
1224                 t = t_alloc();
1225                 memset(t, 0, sizeof(*t));
1226                 t->bit = bit;
1227
1228                 trace_to_cpu(bit);
1229                 t->next = trace_list;
1230                 trace_list = t;
1231
1232                 if (genesis_time == 0 || t->bit->time < genesis_time)
1233                         genesis_time = t->bit->time;
1234
1235                 bit->time -= genesis_time;
1236
1237                 if (!pdi || pdi->id != bit->device)
1238                         pdi = get_dev_info(bit->device);
1239
1240                 if (bit->time > pdi->last_read_time)
1241                         pdi->last_read_time = bit->time;
1242
1243                 events++;
1244         }
1245
1246         return events;
1247 }
1248
1249 static int do_file(void)
1250 {
1251         struct per_cpu_info *pci;
1252         struct per_dev_info *pdi;
1253         int i, j, events, events_added;
1254
1255         /*
1256          * first prepare all files for reading
1257          */
1258         for (i = 0; i < ndevices; i++) {
1259                 pdi = &devices[i];
1260                 pdi->nfiles = 0;
1261                 pdi->last_sequence = -1;
1262
1263                 for (j = 0;; j++) {
1264                         struct stat st;
1265
1266                         pci = get_cpu_info(pdi, j);
1267                         pci->cpu = j;
1268                         pci->fd = -1;
1269
1270                         snprintf(pci->fname, sizeof(pci->fname)-1,
1271                                  "%s.blktrace.%d", pdi->name, pci->cpu);
1272                         if (stat(pci->fname, &st) < 0)
1273                                 break;
1274                         if (st.st_size) {
1275                                 pci->fd = open(pci->fname, O_RDONLY);
1276                                 if (pci->fd < 0) {
1277                                         perror(pci->fname);
1278                                         continue;
1279                                 }
1280                         }
1281
1282                         printf("Input file %s added\n", pci->fname);
1283                         pdi->nfiles++;
1284                 }
1285         }
1286
1287         /*
1288          * now loop over the files reading in the data
1289          */
1290         do {
1291                 events_added = 0;
1292                 last_allowed_time = -1ULL;
1293
1294                 for (i = 0; i < ndevices; i++) {
1295                         pdi = &devices[i];
1296
1297                         for (j = 0; j < pdi->nfiles; j++) {
1298
1299                                 pci = get_cpu_info(pdi, j);
1300
1301                                 if (pci->fd == -1)
1302                                         continue;
1303
1304                                 events = read_events(pci->fd);
1305                                 if (!events) {
1306                                         close(pci->fd);
1307                                         pci->fd = -1;
1308                                         continue;
1309                                 }
1310
1311                                 if (pdi->last_read_time < last_allowed_time)
1312                                         last_allowed_time = pdi->last_read_time;
1313
1314                                 events_added += events;
1315                         }
1316                 }
1317
1318                 if (sort_entries() == -1)
1319                         break;
1320
1321                 show_entries_rb();
1322
1323         } while (events_added);
1324
1325         return 0;
1326 }
1327
1328 static int do_stdin(void)
1329 {
1330         int fd;
1331
1332         last_allowed_time = -1ULL;
1333         fd = dup(STDIN_FILENO);
1334         do {
1335                 int events;
1336
1337                 events = read_events(fd);
1338                 if (!events)
1339                         break;
1340         
1341                 if (sort_entries() == -1)
1342                         break;
1343
1344                 show_entries_rb();
1345         } while (1);
1346
1347         close(fd);
1348         return 0;
1349 }
1350
1351 static void flush_output(void)
1352 {
1353         fflush(ofp);
1354 }
1355
1356 static void handle_sigint(int sig)
1357 {
1358         done = 1;
1359         flush_output();
1360 }
1361
1362 /*
1363  * Extract start and duration times from a string, allowing
1364  * us to specify a time interval of interest within a trace.
1365  * Format: "duration" (start is zero) or "start:duration".
1366  */
1367 static int find_stopwatch_interval(char *string)
1368 {
1369         double value;
1370         char *sp;
1371
1372         value = strtod(string, &sp);
1373         if (sp == string) {
1374                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
1375                 return 1;
1376         }
1377         if (*sp == ':') {
1378                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
1379                 string = sp + 1;
1380                 value = strtod(string, &sp);
1381                 if (sp == string || *sp != '\0') {
1382                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
1383                                 string);
1384                         return 1;
1385                 }
1386         } else if (*sp != '\0') {
1387                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
1388                 return 1;
1389         }
1390         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
1391         if (stopwatch_end <= stopwatch_start) {
1392                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
1393                         stopwatch_start, stopwatch_end);
1394                 return 1;
1395         }
1396
1397         return 0;
1398 }
1399
1400 static char usage_str[] = \
1401         "[ -i <input name> ] [-o <output name> [ -s ] [ -t ] [ -q ]\n" \
1402         "[ -w start:stop ] [ -f output format ] [ -F format spec ] [ -v] \n\n" \
1403         "\t-i Input file containing trace data, or '-' for stdin\n" \
1404         "\t-o Output file. If not given, output is stdout\n" \
1405         "\t-b stdin read batching\n" \
1406         "\t-s Show per-program io statistics\n" \
1407         "\t-t Track individual ios. Will tell you the time a request took\n" \
1408         "\t   to get queued, to get dispatched, and to get completed\n" \
1409         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
1410         "\t-w Only parse data between the given time interval in seconds.\n" \
1411         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
1412         "\t -f Output format. Customize the output format. The format field\n" \
1413         "\t    identifies can be found in the documentation\n" \
1414         "\t-F Format specification. Can be found in the documentation\n" \
1415         "\t-v Print program version info\n\n";
1416
1417 static void usage(char *prog)
1418 {
1419         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
1420 }
1421
1422 int main(int argc, char *argv[])
1423 {
1424         char *ofp_buffer;
1425         int c, ret, mode;
1426         int per_device_and_cpu_stats = 1;
1427
1428         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
1429                 switch (c) {
1430                 case 'i':
1431                         if (!strcmp(optarg, "-") && !pipeline)
1432                                 pipeline = 1;
1433                         else if (resize_devices(optarg) != 0)
1434                                 return 1;
1435                         break;
1436                 case 'o':
1437                         output_name = optarg;
1438                         break;
1439                 case 'b':
1440                         rb_batch = atoi(optarg);
1441                         if (rb_batch <= 0)
1442                                 rb_batch = RB_BATCH_DEFAULT;
1443                         break;
1444                 case 's':
1445                         per_process_stats = 1;
1446                         break;
1447                 case 't':
1448                         track_ios = 1;
1449                         break;
1450                 case 'q':
1451                         per_device_and_cpu_stats = 0;
1452                         break;
1453                 case 'w':
1454                         if (find_stopwatch_interval(optarg) != 0)
1455                                 return 1;
1456                         break;
1457                 case 'f':
1458                         set_all_format_specs(optarg);
1459                         break;
1460                 case 'F':
1461                         if (add_format_spec(optarg) != 0)
1462                                 return 1;
1463                         break;
1464                 case 'v':
1465                         printf("%s version %s\n", argv[0], blkparse_version);
1466                         return 0;
1467                 default:
1468                         usage(argv[0]);
1469                         return 1;
1470                 }
1471         }
1472
1473         while (optind < argc) {
1474                 if (!strcmp(argv[optind], "-") && !pipeline)
1475                         pipeline = 1;
1476                 else if (resize_devices(argv[optind]) != 0)
1477                         return 1;
1478                 optind++;
1479         }
1480
1481         if (!pipeline && !ndevices) {
1482                 usage(argv[0]);
1483                 return 1;
1484         }
1485
1486         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
1487         memset(&rb_track_root, 0, sizeof(rb_track_root));
1488
1489         signal(SIGINT, handle_sigint);
1490         signal(SIGHUP, handle_sigint);
1491         signal(SIGTERM, handle_sigint);
1492
1493         setlocale(LC_NUMERIC, "en_US");
1494
1495         if (!output_name) {
1496                 ofp = fdopen(STDOUT_FILENO, "w");
1497                 mode = _IOLBF;
1498         } else {
1499                 char ofname[128];
1500
1501                 snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
1502                 ofp = fopen(ofname, "w");
1503                 mode = _IOFBF;
1504         }
1505
1506         if (!ofp) {
1507                 perror("fopen");
1508                 return 1;
1509         }
1510
1511         ofp_buffer = malloc(4096);      
1512         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
1513                 perror("setvbuf");
1514                 return 1;
1515         }
1516
1517         if (pipeline)
1518                 ret = do_stdin();
1519         else
1520                 ret = do_file();
1521
1522         if (per_process_stats)
1523                 show_process_stats();
1524
1525         if (per_device_and_cpu_stats)
1526                 show_device_and_cpu_stats();
1527
1528         flush_output();
1529         return ret;
1530 }