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