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