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