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