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