[PATCH] Fixed the Makefile in btt/
[blktrace.git] / blkparse.c
1 /*
2  * block queue tracing parse application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <getopt.h>
30 #include <errno.h>
31 #include <signal.h>
32 #include <locale.h>
33 #include <libgen.h>
34
35 #include "blktrace.h"
36 #include "rbtree.h"
37 #include "jhash.h"
38
39 static char blkparse_version[] = "0.99.1";
40
41 struct skip_info {
42         unsigned long start, end;
43         struct skip_info *prev, *next;
44 };
45
46 struct per_dev_info {
47         dev_t dev;
48         char *name;
49
50         int backwards;
51         unsigned long long events;
52         unsigned long long first_reported_time;
53         unsigned long long last_reported_time;
54         unsigned long long last_read_time;
55         struct io_stats io_stats;
56         unsigned long skips;
57         unsigned long long seq_skips;
58         unsigned int max_depth[2];
59         unsigned int cur_depth[2];
60
61         struct rb_root rb_track;
62
63         int nfiles;
64         int ncpus;
65
66         unsigned long *cpu_map;
67         unsigned int cpu_map_max;
68
69         struct per_cpu_info *cpus;
70 };
71
72 /*
73  * some duplicated effort here, we can unify this hash and the ppi hash later
74  */
75 struct process_pid_map {
76         pid_t pid;
77         char comm[16];
78         struct process_pid_map *hash_next, *list_next;
79 };
80
81 #define PPM_HASH_SHIFT  (8)
82 #define PPM_HASH_SIZE   (1 << PPM_HASH_SHIFT)
83 #define PPM_HASH_MASK   (PPM_HASH_SIZE - 1)
84 static struct process_pid_map *ppm_hash_table[PPM_HASH_SIZE];
85
86 struct per_process_info {
87         struct process_pid_map *ppm;
88         struct io_stats io_stats;
89         struct per_process_info *hash_next, *list_next;
90         int more_than_one;
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 #define PPI_HASH_SIZE   (1 << PPI_HASH_SHIFT)
102 #define PPI_HASH_MASK   (PPI_HASH_SIZE - 1)
103 static struct per_process_info *ppi_hash_table[PPI_HASH_SIZE];
104 static struct per_process_info *ppi_list;
105 static int ppi_list_entries;
106
107 #define S_OPTS  "a:A:i:o:b:stqw:f:F:vVhD:d:"
108 static struct option l_opts[] = {
109         {
110                 .name = "act-mask",
111                 .has_arg = required_argument,
112                 .flag = NULL,
113                 .val = 'a'
114         },
115         {
116                 .name = "set-mask",
117                 .has_arg = required_argument,
118                 .flag = NULL,
119                 .val = 'A'
120         },
121         {
122                 .name = "input",
123                 .has_arg = required_argument,
124                 .flag = NULL,
125                 .val = 'i'
126         },
127         {
128                 .name = "output",
129                 .has_arg = required_argument,
130                 .flag = NULL,
131                 .val = 'o'
132         },
133         {
134                 .name = "batch",
135                 .has_arg = required_argument,
136                 .flag = NULL,
137                 .val = 'b'
138         },
139         {
140                 .name = "per-program-stats",
141                 .has_arg = no_argument,
142                 .flag = NULL,
143                 .val = 's'
144         },
145         {
146                 .name = "track-ios",
147                 .has_arg = no_argument,
148                 .flag = NULL,
149                 .val = 't'
150         },
151         {
152                 .name = "quiet",
153                 .has_arg = no_argument,
154                 .flag = NULL,
155                 .val = 'q'
156         },
157         {
158                 .name = "stopwatch",
159                 .has_arg = required_argument,
160                 .flag = NULL,
161                 .val = 'w'
162         },
163         {
164                 .name = "format",
165                 .has_arg = required_argument,
166                 .flag = NULL,
167                 .val = 'f'
168         },
169         {
170                 .name = "format-spec",
171                 .has_arg = required_argument,
172                 .flag = NULL,
173                 .val = 'F'
174         },
175         {
176                 .name = "hash-by-name",
177                 .has_arg = no_argument,
178                 .flag = NULL,
179                 .val = 'h'
180         },
181         {
182                 .name = "verbose",
183                 .has_arg = no_argument,
184                 .flag = NULL,
185                 .val = 'v'
186         },
187         {
188                 .name = "version",
189                 .has_arg = no_argument,
190                 .flag = NULL,
191                 .val = 'V'
192         },
193         {
194                 .name = "input-directory",
195                 .has_arg = required_argument,
196                 .flag = NULL,
197                 .val = 'D'
198         },
199         {
200                 .name = "dump-binary",
201                 .has_arg = required_argument,
202                 .flag = NULL,
203                 .val = 'd'
204         },
205         {
206                 .name = NULL,
207         }
208 };
209
210 /*
211  * for sorting the displayed output
212  */
213 struct trace {
214         struct blk_io_trace *bit;
215         struct rb_node rb_node;
216         struct trace *next;
217         unsigned long read_sequence;
218 };
219
220 static struct rb_root rb_sort_root;
221 static unsigned long rb_sort_entries;
222
223 static struct trace *trace_list;
224
225 /*
226  * allocation cache
227  */
228 static struct blk_io_trace *bit_alloc_list;
229 static struct trace *t_alloc_list;
230
231 /*
232  * for tracking individual ios
233  */
234 struct io_track {
235         struct rb_node rb_node;
236
237         struct process_pid_map *ppm;
238         __u64 sector;
239         unsigned long long allocation_time;
240         unsigned long long queue_time;
241         unsigned long long dispatch_time;
242         unsigned long long completion_time;
243 };
244
245 static int ndevices;
246 static struct per_dev_info *devices;
247 static char *get_dev_name(struct per_dev_info *, char *, int);
248 static int trace_rb_insert_last(struct per_dev_info *, struct trace *);
249
250 FILE *ofp = NULL;
251 static char *output_name;
252 static char *input_dir;
253
254 static unsigned long long genesis_time;
255 static unsigned long long last_allowed_time;
256 static unsigned long long stopwatch_start;      /* start from zero by default */
257 static unsigned long long stopwatch_end = -1ULL;        /* "infinity" */
258 static unsigned long read_sequence;
259
260 static int per_process_stats;
261 static int per_device_and_cpu_stats = 1;
262 static int track_ios;
263 static int ppi_hash_by_pid = 1;
264 static int verbose;
265 static unsigned int act_mask = -1U;
266 static int stats_printed;
267 int data_is_native = -1;
268
269 static int dump_fd;
270 static char *dump_binary;
271
272 static unsigned int t_alloc_cache;
273 static unsigned int bit_alloc_cache;
274
275 #define RB_BATCH_DEFAULT        (512)
276 static unsigned int rb_batch = RB_BATCH_DEFAULT;
277
278 static int pipeline;
279
280 #define is_done()       (*(volatile int *)(&done))
281 static volatile int done;
282
283 #define JHASH_RANDOM    (0x3af5f2ee)
284
285 #define CPUS_PER_LONG   (8 * sizeof(unsigned long))
286 #define CPU_IDX(cpu)    ((cpu) / CPUS_PER_LONG)
287 #define CPU_BIT(cpu)    ((cpu) & (CPUS_PER_LONG - 1))
288
289 static void output_binary(void *buf, int len)
290 {
291         if (dump_binary) {
292                 int n = write(dump_fd, buf, len);
293                 if (n != len) {
294                         perror(dump_binary);
295                         close(dump_fd);
296                         dump_binary = NULL;
297                 }
298         }
299 }
300
301 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
302 {
303         struct per_cpu_info *cpus = pdi->cpus;
304         int ncpus = pdi->ncpus;
305         int new_count = cpu + 1;
306         int new_space, size;
307         char *new_start;
308
309         size = new_count * sizeof(struct per_cpu_info);
310         cpus = realloc(cpus, size);
311         if (!cpus) {
312                 char name[20];
313                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
314                         get_dev_name(pdi, name, sizeof(name)), size);
315                 exit(1);
316         }
317
318         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
319         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
320         memset(new_start, 0, new_space);
321
322         pdi->ncpus = new_count;
323         pdi->cpus = cpus;
324
325         for (new_count = 0; new_count < pdi->ncpus; new_count++) {
326                 struct per_cpu_info *pci = &pdi->cpus[new_count];
327
328                 if (!pci->fd) {
329                         pci->fd = -1;
330                         memset(&pci->rb_last, 0, sizeof(pci->rb_last));
331                         pci->rb_last_entries = 0;
332                         pci->last_sequence = -1;
333                 }
334         }
335 }
336
337 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
338 {
339         struct per_cpu_info *pci;
340
341         if (cpu >= pdi->ncpus)
342                 resize_cpu_info(pdi, cpu);
343
344         pci = &pdi->cpus[cpu];
345         pci->cpu = cpu;
346         return pci;
347 }
348
349
350 static int resize_devices(char *name)
351 {
352         int size = (ndevices + 1) * sizeof(struct per_dev_info);
353
354         devices = realloc(devices, size);
355         if (!devices) {
356                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
357                 return 1;
358         }
359         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
360         devices[ndevices].name = name;
361         ndevices++;
362         return 0;
363 }
364
365 static struct per_dev_info *get_dev_info(dev_t dev)
366 {
367         struct per_dev_info *pdi;
368         int i;
369
370         for (i = 0; i < ndevices; i++) {
371                 if (!devices[i].dev)
372                         devices[i].dev = dev;
373                 if (devices[i].dev == dev)
374                         return &devices[i];
375         }
376
377         if (resize_devices(NULL))
378                 return NULL;
379
380         pdi = &devices[ndevices - 1];
381         pdi->dev = dev;
382         pdi->first_reported_time = 0;
383         pdi->last_read_time = 0;
384
385         return pdi;
386 }
387
388 static void insert_skip(struct per_cpu_info *pci, unsigned long start,
389                         unsigned long end)
390 {
391         struct skip_info *sip;
392
393         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
394                 if (end == (sip->start - 1)) {
395                         sip->start = start;
396                         return;
397                 } else if (start == (sip->end + 1)) {
398                         sip->end = end;
399                         return;
400                 }
401         }
402
403         sip = malloc(sizeof(struct skip_info));
404         sip->start = start;
405         sip->end = end;
406         sip->prev = sip->next = NULL;
407         if (pci->skips_tail == NULL)
408                 pci->skips_head = pci->skips_tail = sip;
409         else {
410                 sip->prev = pci->skips_tail;
411                 pci->skips_tail->next = sip;
412                 pci->skips_tail = sip;
413         }
414 }
415
416 static void remove_sip(struct per_cpu_info *pci, struct skip_info *sip)
417 {
418         if (sip->prev == NULL) {
419                 if (sip->next == NULL)
420                         pci->skips_head = pci->skips_tail = NULL;
421                 else {
422                         pci->skips_head = sip->next;
423                         sip->next->prev = NULL;
424                 }
425         } else if (sip->next == NULL) {
426                 pci->skips_tail = sip->prev;
427                 sip->prev->next = NULL;
428         } else {
429                 sip->prev->next = sip->next;
430                 sip->next->prev = sip->prev;
431         }
432
433         sip->prev = sip->next = NULL;
434         free(sip);
435 }
436
437 #define IN_SKIP(sip,seq) (((sip)->start <= (seq)) && ((seq) <= sip->end))
438 static int check_current_skips(struct per_cpu_info *pci, unsigned long seq)
439 {
440         struct skip_info *sip;
441
442         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
443                 if (IN_SKIP(sip, seq)) {
444                         if (sip->start == seq) {
445                                 if (sip->end == seq)
446                                         remove_sip(pci, sip);
447                                 else
448                                         sip->start += 1;
449                         } else if (sip->end == seq)
450                                 sip->end -= 1;
451                         else {
452                                 sip->end = seq - 1;
453                                 insert_skip(pci, seq + 1, sip->end);
454                         }
455                         return 1;
456                 }
457         }
458
459         return 0;
460 }
461
462 static void collect_pdi_skips(struct per_dev_info *pdi)
463 {
464         struct skip_info *sip;
465         int cpu;
466
467         pdi->skips = 0;
468         pdi->seq_skips = 0;
469
470         for (cpu = 0; cpu < pdi->ncpus; cpu++) {
471                 struct per_cpu_info *pci = &pdi->cpus[cpu];
472
473                 for (sip = pci->skips_head; sip != NULL; sip = sip->next) {
474                         pdi->skips++;
475                         pdi->seq_skips += (sip->end - sip->start + 1);
476                         if (verbose)
477                                 fprintf(stderr,"(%d,%d): skipping %lu -> %lu\n",
478                                         MAJOR(pdi->dev), MINOR(pdi->dev),
479                                         sip->start, sip->end);
480                 }
481         }
482 }
483
484 static void cpu_mark_online(struct per_dev_info *pdi, unsigned int cpu)
485 {
486         if (cpu >= pdi->cpu_map_max || !pdi->cpu_map) {
487                 int new_max = (cpu + CPUS_PER_LONG) & ~(CPUS_PER_LONG - 1);
488                 unsigned long *map = malloc(new_max / sizeof(long));
489
490                 memset(map, 0, new_max / sizeof(long));
491
492                 if (pdi->cpu_map) {
493                         memcpy(map, pdi->cpu_map, pdi->cpu_map_max / sizeof(long));
494                         free(pdi->cpu_map);
495                 }
496
497                 pdi->cpu_map = map;
498                 pdi->cpu_map_max = new_max;
499         }
500
501         pdi->cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
502 }
503
504 static inline void cpu_mark_offline(struct per_dev_info *pdi, int cpu)
505 {
506         pdi->cpu_map[CPU_IDX(cpu)] &= ~(1UL << CPU_BIT(cpu));
507 }
508
509 static inline int cpu_is_online(struct per_dev_info *pdi, int cpu)
510 {
511         return (pdi->cpu_map[CPU_IDX(cpu)] & (1UL << CPU_BIT(cpu))) != 0;
512 }
513
514 static inline int ppm_hash_pid(pid_t pid)
515 {
516         return jhash_1word(pid, JHASH_RANDOM) & PPM_HASH_MASK;
517 }
518
519 static struct process_pid_map *find_ppm(pid_t pid)
520 {
521         const int hash_idx = ppm_hash_pid(pid);
522         struct process_pid_map *ppm;
523
524         ppm = ppm_hash_table[hash_idx];
525         while (ppm) {
526                 if (ppm->pid == pid)
527                         return ppm;
528
529                 ppm = ppm->hash_next;
530         }
531
532         return NULL;
533 }
534
535 static void add_ppm_hash(pid_t pid, const char *name)
536 {
537         const int hash_idx = ppm_hash_pid(pid);
538         struct process_pid_map *ppm;
539
540         ppm = find_ppm(pid);
541         if (!ppm) {
542                 ppm = malloc(sizeof(*ppm));
543                 memset(ppm, 0, sizeof(*ppm));
544                 ppm->pid = pid;
545                 strcpy(ppm->comm, name);
546                 ppm->hash_next = ppm_hash_table[hash_idx];
547                 ppm_hash_table[hash_idx] = ppm;
548         }
549 }
550
551 char *find_process_name(pid_t pid)
552 {
553         struct process_pid_map *ppm = find_ppm(pid);
554
555         if (ppm)
556                 return ppm->comm;
557
558         return NULL;
559 }
560
561 static inline int ppi_hash_pid(pid_t pid)
562 {
563         return jhash_1word(pid, JHASH_RANDOM) & PPI_HASH_MASK;
564 }
565
566 static inline int ppi_hash_name(const char *name)
567 {
568         return jhash(name, 16, JHASH_RANDOM) & PPI_HASH_MASK;
569 }
570
571 static inline int ppi_hash(struct per_process_info *ppi)
572 {
573         struct process_pid_map *ppm = ppi->ppm;
574
575         if (ppi_hash_by_pid)
576                 return ppi_hash_pid(ppm->pid);
577
578         return ppi_hash_name(ppm->comm);
579 }
580
581 static inline void add_ppi_to_hash(struct per_process_info *ppi)
582 {
583         const int hash_idx = ppi_hash(ppi);
584
585         ppi->hash_next = ppi_hash_table[hash_idx];
586         ppi_hash_table[hash_idx] = ppi;
587 }
588
589 static inline void add_ppi_to_list(struct per_process_info *ppi)
590 {
591         ppi->list_next = ppi_list;
592         ppi_list = ppi;
593         ppi_list_entries++;
594 }
595
596 static struct per_process_info *find_ppi_by_name(char *name)
597 {
598         const int hash_idx = ppi_hash_name(name);
599         struct per_process_info *ppi;
600
601         ppi = ppi_hash_table[hash_idx];
602         while (ppi) {
603                 struct process_pid_map *ppm = ppi->ppm;
604
605                 if (!strcmp(ppm->comm, name))
606                         return ppi;
607
608                 ppi = ppi->hash_next;
609         }
610
611         return NULL;
612 }
613
614 static struct per_process_info *find_ppi_by_pid(pid_t pid)
615 {
616         const int hash_idx = ppi_hash_pid(pid);
617         struct per_process_info *ppi;
618
619         ppi = ppi_hash_table[hash_idx];
620         while (ppi) {
621                 struct process_pid_map *ppm = ppi->ppm;
622
623                 if (ppm->pid == pid)
624                         return ppi;
625
626                 ppi = ppi->hash_next;
627         }
628
629         return NULL;
630 }
631
632 static struct per_process_info *find_ppi(pid_t pid)
633 {
634         struct per_process_info *ppi;
635         char *name;
636
637         if (ppi_hash_by_pid)
638                 return find_ppi_by_pid(pid);
639
640         name = find_process_name(pid);
641         if (!name)
642                 return NULL;
643
644         ppi = find_ppi_by_name(name);
645         if (ppi && ppi->ppm->pid != pid)
646                 ppi->more_than_one = 1;
647
648         return ppi;
649 }
650
651 /*
652  * struct trace and blktrace allocation cache, we do potentially
653  * millions of mallocs for these structures while only using at most
654  * a few thousand at the time
655  */
656 static inline void t_free(struct trace *t)
657 {
658         if (t_alloc_cache < 1024) {
659                 t->next = t_alloc_list;
660                 t_alloc_list = t;
661                 t_alloc_cache++;
662         } else
663                 free(t);
664 }
665
666 static inline struct trace *t_alloc(void)
667 {
668         struct trace *t = t_alloc_list;
669
670         if (t) {
671                 t_alloc_list = t->next;
672                 t_alloc_cache--;
673                 return t;
674         }
675
676         return malloc(sizeof(*t));
677 }
678
679 static inline void bit_free(struct blk_io_trace *bit)
680 {
681         if (bit_alloc_cache < 1024 && !bit->pdu_len) {
682                 /*
683                  * abuse a 64-bit field for a next pointer for the free item
684                  */
685                 bit->time = (__u64) (unsigned long) bit_alloc_list;
686                 bit_alloc_list = (struct blk_io_trace *) bit;
687                 bit_alloc_cache++;
688         } else
689                 free(bit);
690 }
691
692 static inline struct blk_io_trace *bit_alloc(void)
693 {
694         struct blk_io_trace *bit = bit_alloc_list;
695
696         if (bit) {
697                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
698                                  bit->time;
699                 bit_alloc_cache--;
700                 return bit;
701         }
702
703         return malloc(sizeof(*bit));
704 }
705
706 static inline void __put_trace_last(struct per_dev_info *pdi, struct trace *t)
707 {
708         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
709
710         rb_erase(&t->rb_node, &pci->rb_last);
711         pci->rb_last_entries--;
712
713         bit_free(t->bit);
714         t_free(t);
715 }
716
717 static void put_trace(struct per_dev_info *pdi, struct trace *t)
718 {
719         rb_erase(&t->rb_node, &rb_sort_root);
720         rb_sort_entries--;
721
722         trace_rb_insert_last(pdi, t);
723 }
724
725 static inline int trace_rb_insert(struct trace *t, struct rb_root *root)
726 {
727         struct rb_node **p = &root->rb_node;
728         struct rb_node *parent = NULL;
729         struct trace *__t;
730
731         while (*p) {
732                 parent = *p;
733
734                 __t = rb_entry(parent, struct trace, rb_node);
735
736                 if (t->bit->time < __t->bit->time)
737                         p = &(*p)->rb_left;
738                 else if (t->bit->time > __t->bit->time)
739                         p = &(*p)->rb_right;
740                 else if (t->bit->device < __t->bit->device)
741                         p = &(*p)->rb_left;
742                 else if (t->bit->device > __t->bit->device)
743                         p = &(*p)->rb_right;
744                 else if (t->bit->sequence < __t->bit->sequence)
745                         p = &(*p)->rb_left;
746                 else    /* >= sequence */
747                         p = &(*p)->rb_right;
748         }
749
750         rb_link_node(&t->rb_node, parent, p);
751         rb_insert_color(&t->rb_node, root);
752         return 0;
753 }
754
755 static inline int trace_rb_insert_sort(struct trace *t)
756 {
757         if (!trace_rb_insert(t, &rb_sort_root)) {
758                 rb_sort_entries++;
759                 return 0;
760         }
761
762         return 1;
763 }
764
765 static int trace_rb_insert_last(struct per_dev_info *pdi, struct trace *t)
766 {
767         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
768
769         if (trace_rb_insert(t, &pci->rb_last))
770                 return 1;
771
772         pci->rb_last_entries++;
773
774         if (pci->rb_last_entries > rb_batch * pdi->nfiles) {
775                 struct rb_node *n = rb_first(&pci->rb_last);
776
777                 t = rb_entry(n, struct trace, rb_node);
778                 __put_trace_last(pdi, t);
779         }
780
781         return 0;
782 }
783
784 static struct trace *trace_rb_find(dev_t device, unsigned long sequence,
785                                    struct rb_root *root, int order)
786 {
787         struct rb_node *n = root->rb_node;
788         struct rb_node *prev = NULL;
789         struct trace *__t;
790
791         while (n) {
792                 __t = rb_entry(n, struct trace, rb_node);
793                 prev = n;
794
795                 if (device < __t->bit->device)
796                         n = n->rb_left;
797                 else if (device > __t->bit->device)
798                         n = n->rb_right;
799                 else if (sequence < __t->bit->sequence)
800                         n = n->rb_left;
801                 else if (sequence > __t->bit->sequence)
802                         n = n->rb_right;
803                 else
804                         return __t;
805         }
806
807         /*
808          * hack - the list may not be sequence ordered because some
809          * events don't have sequence and time matched. so we end up
810          * being a little off in the rb lookup here, because we don't
811          * know the time we are looking for. compensate by browsing
812          * a little ahead from the last entry to find the match
813          */
814         if (order && prev) {
815                 int max = 5;
816
817                 while (((n = rb_next(prev)) != NULL) && max--) {
818                         __t = rb_entry(n, struct trace, rb_node);
819
820                         if (__t->bit->device == device &&
821                             __t->bit->sequence == sequence)
822                                 return __t;
823
824                         prev = n;
825                 }
826         }
827
828         return NULL;
829 }
830
831 static inline struct trace *trace_rb_find_last(struct per_dev_info *pdi,
832                                                struct per_cpu_info *pci,
833                                                unsigned long seq)
834 {
835         return trace_rb_find(pdi->dev, seq, &pci->rb_last, 0);
836 }
837
838 static inline int track_rb_insert(struct per_dev_info *pdi,struct io_track *iot)
839 {
840         struct rb_node **p = &pdi->rb_track.rb_node;
841         struct rb_node *parent = NULL;
842         struct io_track *__iot;
843
844         while (*p) {
845                 parent = *p;
846                 __iot = rb_entry(parent, struct io_track, rb_node);
847
848                 if (iot->sector < __iot->sector)
849                         p = &(*p)->rb_left;
850                 else if (iot->sector > __iot->sector)
851                         p = &(*p)->rb_right;
852                 else {
853                         fprintf(stderr,
854                                 "sector alias (%Lu) on device %d,%d!\n",
855                                 (unsigned long long) iot->sector,
856                                 MAJOR(pdi->dev), MINOR(pdi->dev));
857                         return 1;
858                 }
859         }
860
861         rb_link_node(&iot->rb_node, parent, p);
862         rb_insert_color(&iot->rb_node, &pdi->rb_track);
863         return 0;
864 }
865
866 static struct io_track *__find_track(struct per_dev_info *pdi, __u64 sector)
867 {
868         struct rb_node *n = pdi->rb_track.rb_node;
869         struct io_track *__iot;
870
871         while (n) {
872                 __iot = rb_entry(n, struct io_track, rb_node);
873
874                 if (sector < __iot->sector)
875                         n = n->rb_left;
876                 else if (sector > __iot->sector)
877                         n = n->rb_right;
878                 else
879                         return __iot;
880         }
881
882         return NULL;
883 }
884
885 static struct io_track *find_track(struct per_dev_info *pdi, pid_t pid,
886                                    __u64 sector)
887 {
888         struct io_track *iot;
889
890         iot = __find_track(pdi, sector);
891         if (!iot) {
892                 iot = malloc(sizeof(*iot));
893                 iot->ppm = find_ppm(pid);
894                 iot->sector = sector;
895                 track_rb_insert(pdi, iot);
896         }
897
898         return iot;
899 }
900
901 static void log_track_frontmerge(struct per_dev_info *pdi,
902                                  struct blk_io_trace *t)
903 {
904         struct io_track *iot;
905
906         if (!track_ios)
907                 return;
908
909         iot = __find_track(pdi, t->sector + t_sec(t));
910         if (!iot) {
911                 if (verbose)
912                         fprintf(stderr, "merge not found for (%d,%d): %llu\n",
913                                 MAJOR(pdi->dev), MINOR(pdi->dev),
914                                 (unsigned long long) t->sector + t_sec(t));
915                 return;
916         }
917
918         rb_erase(&iot->rb_node, &pdi->rb_track);
919         iot->sector -= t_sec(t);
920         track_rb_insert(pdi, iot);
921 }
922
923 static void log_track_getrq(struct per_dev_info *pdi, struct blk_io_trace *t)
924 {
925         struct io_track *iot;
926
927         if (!track_ios)
928                 return;
929
930         iot = find_track(pdi, t->pid, t->sector);
931         iot->allocation_time = t->time;
932 }
933
934 static inline int is_remapper(struct per_dev_info *pdi)
935 {
936         int major = MAJOR(pdi->dev);
937
938         return (major == 253 || major == 9);
939 }
940
941 /*
942  * for md/dm setups, the interesting cycle is Q -> C. So track queueing
943  * time here, as dispatch time
944  */
945 static void log_track_queue(struct per_dev_info *pdi, struct blk_io_trace *t)
946 {
947         struct io_track *iot;
948
949         if (!track_ios)
950                 return;
951         if (!is_remapper(pdi))
952                 return;
953
954         iot = find_track(pdi, t->pid, t->sector);
955         iot->dispatch_time = t->time;
956 }
957
958 /*
959  * return time between rq allocation and insertion
960  */
961 static unsigned long long log_track_insert(struct per_dev_info *pdi,
962                                            struct blk_io_trace *t)
963 {
964         unsigned long long elapsed;
965         struct io_track *iot;
966
967         if (!track_ios)
968                 return -1;
969
970         iot = find_track(pdi, t->pid, t->sector);
971         iot->queue_time = t->time;
972
973         if (!iot->allocation_time)
974                 return -1;
975
976         elapsed = iot->queue_time - iot->allocation_time;
977
978         if (per_process_stats) {
979                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
980                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
981
982                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
983                         ppi->longest_allocation_wait[w] = elapsed;
984         }
985
986         return elapsed;
987 }
988
989 /*
990  * return time between queue and issue
991  */
992 static unsigned long long log_track_issue(struct per_dev_info *pdi,
993                                           struct blk_io_trace *t)
994 {
995         unsigned long long elapsed;
996         struct io_track *iot;
997
998         if (!track_ios)
999                 return -1;
1000         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
1001                 return -1;
1002
1003         iot = __find_track(pdi, t->sector);
1004         if (!iot) {
1005                 if (verbose)
1006                         fprintf(stderr, "issue not found for (%d,%d): %llu\n",
1007                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1008                                 (unsigned long long) t->sector);
1009                 return -1;
1010         }
1011
1012         iot->dispatch_time = t->time;
1013         elapsed = iot->dispatch_time - iot->queue_time;
1014
1015         if (per_process_stats) {
1016                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1017                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1018
1019                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
1020                         ppi->longest_dispatch_wait[w] = elapsed;
1021         }
1022
1023         return elapsed;
1024 }
1025
1026 /*
1027  * return time between dispatch and complete
1028  */
1029 static unsigned long long log_track_complete(struct per_dev_info *pdi,
1030                                              struct blk_io_trace *t)
1031 {
1032         unsigned long long elapsed;
1033         struct io_track *iot;
1034
1035         if (!track_ios)
1036                 return -1;
1037
1038         iot = __find_track(pdi, t->sector);
1039         if (!iot) {
1040                 if (verbose)
1041                         fprintf(stderr,"complete not found for (%d,%d): %llu\n",
1042                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1043                                 (unsigned long long) t->sector);
1044                 return -1;
1045         }
1046
1047         iot->completion_time = t->time;
1048         elapsed = iot->completion_time - iot->dispatch_time;
1049
1050         if (per_process_stats) {
1051                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1052                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1053
1054                 if (ppi && elapsed > ppi->longest_completion_wait[w])
1055                         ppi->longest_completion_wait[w] = elapsed;
1056         }
1057
1058         /*
1059          * kill the trace, we don't need it after completion
1060          */
1061         rb_erase(&iot->rb_node, &pdi->rb_track);
1062         free(iot);
1063
1064         return elapsed;
1065 }
1066
1067
1068 static struct io_stats *find_process_io_stats(pid_t pid)
1069 {
1070         struct per_process_info *ppi = find_ppi(pid);
1071
1072         if (!ppi) {
1073                 ppi = malloc(sizeof(*ppi));
1074                 memset(ppi, 0, sizeof(*ppi));
1075                 ppi->ppm = find_ppm(pid);
1076                 add_ppi_to_hash(ppi);
1077                 add_ppi_to_list(ppi);
1078         }
1079
1080         return &ppi->io_stats;
1081 }
1082
1083 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
1084 {
1085         if (pdi->name)
1086                 snprintf(buffer, size, "%s", pdi->name);
1087         else
1088                 snprintf(buffer, size, "%d,%d",MAJOR(pdi->dev),MINOR(pdi->dev));
1089         return buffer;
1090 }
1091
1092 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
1093 {
1094         unsigned long long this = bit->time;
1095         unsigned long long last = pdi->last_reported_time;
1096
1097         pdi->backwards = (this < last) ? 'B' : ' ';
1098         pdi->last_reported_time = this;
1099 }
1100
1101 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
1102                                int rw)
1103 {
1104         if (rw) {
1105                 ios->mwrites++;
1106                 ios->qwrite_kb += t_kb(t);
1107         } else {
1108                 ios->mreads++;
1109                 ios->qread_kb += t_kb(t);
1110         }
1111 }
1112
1113 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
1114                              int rw)
1115 {
1116         __account_m(&pci->io_stats, t, rw);
1117
1118         if (per_process_stats) {
1119                 struct io_stats *ios = find_process_io_stats(t->pid);
1120
1121                 __account_m(ios, t, rw);
1122         }
1123 }
1124
1125 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
1126                                    int rw)
1127 {
1128         if (rw) {
1129                 ios->qwrites++;
1130                 ios->qwrite_kb += t_kb(t);
1131         } else {
1132                 ios->qreads++;
1133                 ios->qread_kb += t_kb(t);
1134         }
1135 }
1136
1137 static inline void account_queue(struct blk_io_trace *t,
1138                                  struct per_cpu_info *pci, int rw)
1139 {
1140         __account_queue(&pci->io_stats, t, rw);
1141
1142         if (per_process_stats) {
1143                 struct io_stats *ios = find_process_io_stats(t->pid);
1144
1145                 __account_queue(ios, t, rw);
1146         }
1147 }
1148
1149 static inline void __account_c(struct io_stats *ios, int rw, int bytes)
1150 {
1151         if (rw) {
1152                 ios->cwrites++;
1153                 ios->cwrite_kb += bytes >> 10;
1154         } else {
1155                 ios->creads++;
1156                 ios->cread_kb += bytes >> 10;
1157         }
1158 }
1159
1160 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
1161                              int rw, int bytes)
1162 {
1163         __account_c(&pci->io_stats, rw, bytes);
1164
1165         if (per_process_stats) {
1166                 struct io_stats *ios = find_process_io_stats(t->pid);
1167
1168                 __account_c(ios, rw, bytes);
1169         }
1170 }
1171
1172 static inline void __account_issue(struct io_stats *ios, int rw,
1173                                    unsigned int bytes)
1174 {
1175         if (rw) {
1176                 ios->iwrites++;
1177                 ios->iwrite_kb += bytes >> 10;
1178         } else {
1179                 ios->ireads++;
1180                 ios->iread_kb += bytes >> 10;
1181         }
1182 }
1183
1184 static inline void account_issue(struct blk_io_trace *t,
1185                                  struct per_cpu_info *pci, int rw)
1186 {
1187         __account_issue(&pci->io_stats, rw, t->bytes);
1188
1189         if (per_process_stats) {
1190                 struct io_stats *ios = find_process_io_stats(t->pid);
1191
1192                 __account_issue(ios, rw, t->bytes);
1193         }
1194 }
1195
1196 static inline void __account_unplug(struct io_stats *ios, int timer)
1197 {
1198         if (timer)
1199                 ios->timer_unplugs++;
1200         else
1201                 ios->io_unplugs++;
1202 }
1203
1204 static inline void account_unplug(struct blk_io_trace *t,
1205                                   struct per_cpu_info *pci, int timer)
1206 {
1207         __account_unplug(&pci->io_stats, timer);
1208
1209         if (per_process_stats) {
1210                 struct io_stats *ios = find_process_io_stats(t->pid);
1211
1212                 __account_unplug(ios, timer);
1213         }
1214 }
1215
1216 static inline void __account_requeue(struct io_stats *ios,
1217                                      struct blk_io_trace *t, int rw)
1218 {
1219         if (rw) {
1220                 ios->wrqueue++;
1221                 ios->iwrite_kb -= t_kb(t);
1222         } else {
1223                 ios->rrqueue++;
1224                 ios->iread_kb -= t_kb(t);
1225         }
1226 }
1227
1228 static inline void account_requeue(struct blk_io_trace *t,
1229                                    struct per_cpu_info *pci, int rw)
1230 {
1231         __account_requeue(&pci->io_stats, t, rw);
1232
1233         if (per_process_stats) {
1234                 struct io_stats *ios = find_process_io_stats(t->pid);
1235
1236                 __account_requeue(ios, t, rw);
1237         }
1238 }
1239
1240 static void log_complete(struct per_dev_info *pdi, struct per_cpu_info *pci,
1241                          struct blk_io_trace *t, char *act)
1242 {
1243         process_fmt(act, pci, t, log_track_complete(pdi, t), 0, NULL);
1244 }
1245
1246 static void log_insert(struct per_dev_info *pdi, struct per_cpu_info *pci,
1247                        struct blk_io_trace *t, char *act)
1248 {
1249         process_fmt(act, pci, t, log_track_insert(pdi, t), 0, NULL);
1250 }
1251
1252 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
1253                       char *act)
1254 {
1255         process_fmt(act, pci, t, -1, 0, NULL);
1256 }
1257
1258 static void log_issue(struct per_dev_info *pdi, struct per_cpu_info *pci,
1259                       struct blk_io_trace *t, char *act)
1260 {
1261         process_fmt(act, pci, t, log_track_issue(pdi, t), 0, NULL);
1262 }
1263
1264 static void log_merge(struct per_dev_info *pdi, struct per_cpu_info *pci,
1265                       struct blk_io_trace *t, char *act)
1266 {
1267         if (act[0] == 'F')
1268                 log_track_frontmerge(pdi, t);
1269
1270         process_fmt(act, pci, t, -1ULL, 0, NULL);
1271 }
1272
1273 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
1274                         char *act)
1275 {
1276         process_fmt(act, pci, t, -1ULL, 0, NULL);
1277 }
1278
1279 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
1280                         char *act)
1281 {
1282         process_fmt(act, pci, t, -1ULL, 0, NULL);
1283 }
1284
1285 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
1286                       char *act)
1287 {
1288         process_fmt(act, pci, t, -1ULL, 0, NULL);
1289 }
1290
1291 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
1292                       char *act)
1293 {
1294         process_fmt(act, pci, t, -1ULL, 0, NULL);
1295 }
1296
1297 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
1298 {
1299         unsigned char *buf = (unsigned char *) t + sizeof(*t);
1300
1301         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
1302 }
1303
1304 static void dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
1305 {
1306         int act = t->action & 0xffff;
1307
1308         switch (act) {
1309                 case __BLK_TA_QUEUE:
1310                         log_generic(pci, t, "Q");
1311                         break;
1312                 case __BLK_TA_GETRQ:
1313                         log_generic(pci, t, "G");
1314                         break;
1315                 case __BLK_TA_SLEEPRQ:
1316                         log_generic(pci, t, "S");
1317                         break;
1318                 case __BLK_TA_REQUEUE:
1319                         log_generic(pci, t, "R");
1320                         break;
1321                 case __BLK_TA_ISSUE:
1322                         log_pc(pci, t, "D");
1323                         break;
1324                 case __BLK_TA_COMPLETE:
1325                         log_pc(pci, t, "C");
1326                         break;
1327                 case __BLK_TA_INSERT:
1328                         log_pc(pci, t, "I");
1329                         break;
1330                 default:
1331                         fprintf(stderr, "Bad pc action %x\n", act);
1332                         break;
1333         }
1334 }
1335
1336 static void dump_trace_fs(struct blk_io_trace *t, struct per_dev_info *pdi,
1337                           struct per_cpu_info *pci)
1338 {
1339         int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1340         int act = t->action & 0xffff;
1341
1342         switch (act) {
1343                 case __BLK_TA_QUEUE:
1344                         log_track_queue(pdi, t);
1345                         account_queue(t, pci, w);
1346                         log_queue(pci, t, "Q");
1347                         break;
1348                 case __BLK_TA_INSERT:
1349                         log_insert(pdi, pci, t, "I");
1350                         break;
1351                 case __BLK_TA_BACKMERGE:
1352                         account_m(t, pci, w);
1353                         log_merge(pdi, pci, t, "M");
1354                         break;
1355                 case __BLK_TA_FRONTMERGE:
1356                         account_m(t, pci, w);
1357                         log_merge(pdi, pci, t, "F");
1358                         break;
1359                 case __BLK_TA_GETRQ:
1360                         log_track_getrq(pdi, t);
1361                         log_generic(pci, t, "G");
1362                         break;
1363                 case __BLK_TA_SLEEPRQ:
1364                         log_generic(pci, t, "S");
1365                         break;
1366                 case __BLK_TA_REQUEUE:
1367                         /*
1368                          * can happen if we miss traces, don't let it go
1369                          * below zero
1370                          */
1371                         if (pdi->cur_depth[w])
1372                                 pdi->cur_depth[w]--;
1373                         account_requeue(t, pci, w);
1374                         log_queue(pci, t, "R");
1375                         break;
1376                 case __BLK_TA_ISSUE:
1377                         account_issue(t, pci, w);
1378                         pdi->cur_depth[w]++;
1379                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1380                                 pdi->max_depth[w] = pdi->cur_depth[w];
1381                         log_issue(pdi, pci, t, "D");
1382                         break;
1383                 case __BLK_TA_COMPLETE:
1384                         if (pdi->cur_depth[w])
1385                                 pdi->cur_depth[w]--;
1386                         account_c(t, pci, w, t->bytes);
1387                         log_complete(pdi, pci, t, "C");
1388                         break;
1389                 case __BLK_TA_PLUG:
1390                         log_action(pci, t, "P");
1391                         break;
1392                 case __BLK_TA_UNPLUG_IO:
1393                         account_unplug(t, pci, 0);
1394                         log_unplug(pci, t, "U");
1395                         break;
1396                 case __BLK_TA_UNPLUG_TIMER:
1397                         account_unplug(t, pci, 1);
1398                         log_unplug(pci, t, "UT");
1399                         break;
1400                 case __BLK_TA_SPLIT:
1401                         log_split(pci, t, "X");
1402                         break;
1403                 case __BLK_TA_BOUNCE:
1404                         log_generic(pci, t, "B");
1405                         break;
1406                 case __BLK_TA_REMAP:
1407                         log_generic(pci, t, "A");
1408                         break;
1409                 default:
1410                         fprintf(stderr, "Bad fs action %x\n", t->action);
1411                         break;
1412         }
1413 }
1414
1415 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1416                        struct per_dev_info *pdi)
1417 {
1418         if (t->action & BLK_TC_ACT(BLK_TC_PC))
1419                 dump_trace_pc(t, pci);
1420         else
1421                 dump_trace_fs(t, pdi, pci);
1422
1423         if (!pdi->events)
1424                 pdi->first_reported_time = t->time;
1425
1426         pdi->events++;
1427
1428         output_binary(t, sizeof(*t) + t->pdu_len);
1429 }
1430
1431 /*
1432  * print in a proper way, not too small and not too big. if more than
1433  * 1000,000K, turn into M and so on
1434  */
1435 static char *size_cnv(char *dst, unsigned long long num, int in_kb)
1436 {
1437         char suff[] = { '\0', 'K', 'M', 'G', 'P' };
1438         unsigned int i = 0;
1439
1440         if (in_kb)
1441                 i++;
1442
1443         while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
1444                 i++;
1445                 num /= 1000;
1446         }
1447
1448         sprintf(dst, "%'8Lu%c", num, suff[i]);
1449         return dst;
1450 }
1451
1452 static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
1453                           char *msg)
1454 {
1455         static char x[256], y[256];
1456
1457         fprintf(ofp, "%s\n", msg);
1458
1459         fprintf(ofp, " Reads Queued:    %s, %siB\t", size_cnv(x, ios->qreads, 0), size_cnv(y, ios->qread_kb, 1));
1460         fprintf(ofp, " Writes Queued:    %s, %siB\n", size_cnv(x, ios->qwrites, 0), size_cnv(y, ios->qwrite_kb, 1));
1461
1462         fprintf(ofp, " Read Dispatches: %s, %siB\t", size_cnv(x, ios->ireads, 0), size_cnv(y, ios->iread_kb, 1));
1463         fprintf(ofp, " Write Dispatches: %s, %siB\n", size_cnv(x, ios->iwrites, 0), size_cnv(y, ios->iwrite_kb, 1));
1464         fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
1465         fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
1466         fprintf(ofp, " Reads Completed: %s, %siB\t", size_cnv(x, ios->creads, 0), size_cnv(y, ios->cread_kb, 1));
1467         fprintf(ofp, " Writes Completed: %s, %siB\n", size_cnv(x, ios->cwrites, 0), size_cnv(y, ios->cwrite_kb, 1));
1468         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
1469         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
1470         if (pdi) {
1471                 fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
1472                 fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
1473         }
1474         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1475         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1476 }
1477
1478 static void dump_wait_stats(struct per_process_info *ppi)
1479 {
1480         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1481         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1482         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1483         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1484         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1485         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1486
1487         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1488         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1489         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1490         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1491         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1492         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1493 }
1494
1495 static int ppi_name_compare(const void *p1, const void *p2)
1496 {
1497         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1498         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1499         int res;
1500
1501         res = strverscmp(ppi1->ppm->comm, ppi2->ppm->comm);
1502         if (!res)
1503                 res = ppi1->ppm->pid > ppi2->ppm->pid;
1504
1505         return res;
1506 }
1507
1508 static void sort_process_list(void)
1509 {
1510         struct per_process_info **ppis;
1511         struct per_process_info *ppi;
1512         int i = 0;
1513
1514         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1515
1516         ppi = ppi_list;
1517         while (ppi) {
1518                 ppis[i++] = ppi;
1519                 ppi = ppi->list_next;
1520         }
1521
1522         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1523
1524         i = ppi_list_entries - 1;
1525         ppi_list = NULL;
1526         while (i >= 0) {
1527                 ppi = ppis[i];
1528
1529                 ppi->list_next = ppi_list;
1530                 ppi_list = ppi;
1531                 i--;
1532         }
1533
1534         free(ppis);
1535 }
1536
1537 static void show_process_stats(void)
1538 {
1539         struct per_process_info *ppi;
1540
1541         sort_process_list();
1542
1543         ppi = ppi_list;
1544         while (ppi) {
1545                 struct process_pid_map *ppm = ppi->ppm;
1546                 char name[64];
1547
1548                 if (ppi->more_than_one)
1549                         sprintf(name, "%s (%u, ...)", ppm->comm, ppm->pid);
1550                 else
1551                         sprintf(name, "%s (%u)", ppm->comm, ppm->pid);
1552
1553                 dump_io_stats(NULL, &ppi->io_stats, name);
1554                 dump_wait_stats(ppi);
1555                 ppi = ppi->list_next;
1556         }
1557
1558         fprintf(ofp, "\n");
1559 }
1560
1561 static void show_device_and_cpu_stats(void)
1562 {
1563         struct per_dev_info *pdi;
1564         struct per_cpu_info *pci;
1565         struct io_stats total, *ios;
1566         unsigned long long rrate, wrate, msec;
1567         int i, j, pci_events;
1568         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1569         char name[32];
1570
1571         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1572
1573                 memset(&total, 0, sizeof(total));
1574                 pci_events = 0;
1575
1576                 if (i > 0)
1577                         fprintf(ofp, "\n");
1578
1579                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1580                         if (!pci->nelems)
1581                                 continue;
1582
1583                         ios = &pci->io_stats;
1584                         total.qreads += ios->qreads;
1585                         total.qwrites += ios->qwrites;
1586                         total.creads += ios->creads;
1587                         total.cwrites += ios->cwrites;
1588                         total.mreads += ios->mreads;
1589                         total.mwrites += ios->mwrites;
1590                         total.ireads += ios->ireads;
1591                         total.iwrites += ios->iwrites;
1592                         total.rrqueue += ios->rrqueue;
1593                         total.wrqueue += ios->wrqueue;
1594                         total.qread_kb += ios->qread_kb;
1595                         total.qwrite_kb += ios->qwrite_kb;
1596                         total.cread_kb += ios->cread_kb;
1597                         total.cwrite_kb += ios->cwrite_kb;
1598                         total.iread_kb += ios->iread_kb;
1599                         total.iwrite_kb += ios->iwrite_kb;
1600                         total.timer_unplugs += ios->timer_unplugs;
1601                         total.io_unplugs += ios->io_unplugs;
1602
1603                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1604                                  j, get_dev_name(pdi, name, sizeof(name)));
1605                         dump_io_stats(pdi, ios, line);
1606                         pci_events++;
1607                 }
1608
1609                 if (pci_events > 1) {
1610                         fprintf(ofp, "\n");
1611                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1612                                  get_dev_name(pdi, name, sizeof(name)));
1613                         dump_io_stats(NULL, &total, line);
1614                 }
1615
1616                 wrate = rrate = 0;
1617                 msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
1618                 if (msec) {
1619                         rrate = 1000 * total.cread_kb / msec;
1620                         wrate = 1000 * total.cwrite_kb / msec;
1621                 }
1622
1623                 fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
1624                         rrate, wrate);
1625                 fprintf(ofp, "Events (%s): %'Lu entries\n",
1626                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1627
1628                 collect_pdi_skips(pdi);
1629                 fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
1630                         pdi->skips,pdi->seq_skips,
1631                         100.0 * ((double)pdi->seq_skips /
1632                                 (double)(pdi->events + pdi->seq_skips)));
1633         }
1634 }
1635
1636 static void find_genesis(void)
1637 {
1638         struct trace *t = trace_list;
1639
1640         genesis_time = -1ULL;
1641         while (t != NULL) {
1642                 if (t->bit->time < genesis_time)
1643                         genesis_time = t->bit->time;
1644
1645                 t = t->next;
1646         }
1647 }
1648
1649 static inline int check_stopwatch(struct blk_io_trace *bit)
1650 {
1651         if (bit->time < stopwatch_end &&
1652             bit->time >= stopwatch_start)
1653                 return 0;
1654
1655         return 1;
1656 }
1657
1658 /*
1659  * return youngest entry read
1660  */
1661 static int sort_entries(unsigned long long *youngest)
1662 {
1663         struct per_dev_info *pdi = NULL;
1664         struct per_cpu_info *pci = NULL;
1665         struct trace *t;
1666
1667         if (!genesis_time)
1668                 find_genesis();
1669
1670         *youngest = 0;
1671         while ((t = trace_list) != NULL) {
1672                 struct blk_io_trace *bit = t->bit;
1673
1674                 trace_list = t->next;
1675
1676                 bit->time -= genesis_time;
1677
1678                 if (bit->time < *youngest || !*youngest)
1679                         *youngest = bit->time;
1680
1681                 if (!pdi || pdi->dev != bit->device) {
1682                         pdi = get_dev_info(bit->device);
1683                         pci = NULL;
1684                 }
1685
1686                 if (!pci || pci->cpu != bit->cpu)
1687                         pci = get_cpu_info(pdi, bit->cpu);
1688
1689                 if (bit->sequence < pci->smallest_seq_read)
1690                         pci->smallest_seq_read = bit->sequence;
1691
1692                 if (check_stopwatch(bit)) {
1693                         bit_free(bit);
1694                         t_free(t);
1695                         continue;
1696                 }
1697
1698                 if (trace_rb_insert_sort(t))
1699                         return -1;
1700         }
1701
1702         return 0;
1703 }
1704
1705 /*
1706  * to continue, we must have traces from all online cpus in the tree
1707  */
1708 static int check_cpu_map(struct per_dev_info *pdi)
1709 {
1710         unsigned long *cpu_map;
1711         struct rb_node *n;
1712         struct trace *__t;
1713         unsigned int i;
1714         int ret, cpu;
1715
1716         /*
1717          * create a map of the cpus we have traces for
1718          */
1719         cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
1720         n = rb_first(&rb_sort_root);
1721         while (n) {
1722                 __t = rb_entry(n, struct trace, rb_node);
1723                 cpu = __t->bit->cpu;
1724
1725                 cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
1726                 n = rb_next(n);
1727         }
1728
1729         /*
1730          * we can't continue if pdi->cpu_map has entries set that we don't
1731          * have in the sort rbtree. the opposite is not a problem, though
1732          */
1733         ret = 0;
1734         for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
1735                 if (pdi->cpu_map[i] & ~(cpu_map[i])) {
1736                         ret = 1;
1737                         break;
1738                 }
1739         }
1740
1741         free(cpu_map);
1742         return ret;
1743 }
1744
1745 static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
1746 {
1747         struct blk_io_trace *bit = t->bit;
1748         unsigned long expected_sequence;
1749         struct per_cpu_info *pci;
1750         struct trace *__t;
1751
1752         pci = get_cpu_info(pdi, bit->cpu);
1753         expected_sequence = pci->last_sequence + 1;
1754
1755         if (!expected_sequence) {
1756                 /*
1757                  * 1 should be the first entry, just allow it
1758                  */
1759                 if (bit->sequence == 1)
1760                         return 0;
1761                 if (bit->sequence == pci->smallest_seq_read)
1762                         return 0;
1763
1764                 return check_cpu_map(pdi);
1765         }
1766
1767         if (bit->sequence == expected_sequence)
1768                 return 0;
1769
1770         /*
1771          * we may not have seen that sequence yet. if we are not doing
1772          * the final run, break and wait for more entries.
1773          */
1774         if (expected_sequence < pci->smallest_seq_read) {
1775                 __t = trace_rb_find_last(pdi, pci, expected_sequence);
1776                 if (!__t)
1777                         goto skip;
1778
1779                 __put_trace_last(pdi, __t);
1780                 return 0;
1781         } else if (!force) {
1782                 return 1;
1783         } else {
1784 skip:
1785                 if (check_current_skips(pci, bit->sequence))
1786                         return 0;
1787
1788                 if (expected_sequence < bit->sequence)
1789                         insert_skip(pci, expected_sequence, bit->sequence - 1);
1790                 return 0;
1791         }
1792 }
1793
1794 static void show_entries_rb(int force)
1795 {
1796         struct per_dev_info *pdi = NULL;
1797         struct per_cpu_info *pci = NULL;
1798         struct blk_io_trace *bit;
1799         struct rb_node *n;
1800         struct trace *t;
1801
1802         while ((n = rb_first(&rb_sort_root)) != NULL) {
1803                 if (is_done() && !force && !pipeline)
1804                         break;
1805
1806                 t = rb_entry(n, struct trace, rb_node);
1807                 bit = t->bit;
1808
1809                 if (read_sequence - t->read_sequence < 1 && !force)
1810                         break;
1811
1812                 if (!pdi || pdi->dev != bit->device) {
1813                         pdi = get_dev_info(bit->device);
1814                         pci = NULL;
1815                 }
1816
1817                 if (!pdi) {
1818                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1819                                 MAJOR(bit->device), MINOR(bit->device));
1820                         break;
1821                 }
1822
1823                 if (check_sequence(pdi, t, force))
1824                         break;
1825
1826                 if (!force && bit->time > last_allowed_time)
1827                         break;
1828
1829                 check_time(pdi, bit);
1830
1831                 if (!pci || pci->cpu != bit->cpu)
1832                         pci = get_cpu_info(pdi, bit->cpu);
1833
1834                 pci->last_sequence = bit->sequence;
1835
1836                 pci->nelems++;
1837
1838                 if (bit->action & (act_mask << BLK_TC_SHIFT))
1839                         dump_trace(bit, pci, pdi);
1840
1841                 put_trace(pdi, t);
1842         }
1843 }
1844
1845 static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
1846 {
1847         int ret, bytes_left, fl;
1848         void *p;
1849
1850         if (block != *fdblock) {
1851                 fl = fcntl(fd, F_GETFL);
1852
1853                 if (!block) {
1854                         *fdblock = 0;
1855                         fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1856                 } else {
1857                         *fdblock = 1;
1858                         fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1859                 }
1860         }
1861
1862         bytes_left = bytes;
1863         p = buffer;
1864         while (bytes_left > 0) {
1865                 ret = read(fd, p, bytes_left);
1866                 if (!ret)
1867                         return 1;
1868                 else if (ret < 0) {
1869                         if (errno != EAGAIN) {
1870                                 perror("read");
1871                                 return -1;
1872                         }
1873
1874                         /*
1875                          * never do partial reads. we can return if we
1876                          * didn't read anything and we should not block,
1877                          * otherwise wait for data
1878                          */
1879                         if ((bytes_left == bytes) && !block)
1880                                 return 1;
1881
1882                         usleep(10);
1883                         continue;
1884                 } else {
1885                         p += ret;
1886                         bytes_left -= ret;
1887                 }
1888         }
1889
1890         return 0;
1891 }
1892
1893 static inline __u16 get_pdulen(struct blk_io_trace *bit)
1894 {
1895         if (data_is_native)
1896                 return bit->pdu_len;
1897
1898         return __bswap_16(bit->pdu_len);
1899 }
1900
1901 static inline __u32 get_magic(struct blk_io_trace *bit)
1902 {
1903         if (data_is_native)
1904                 return bit->magic;
1905
1906         return __bswap_32(bit->magic);
1907 }
1908
1909 static int read_events(int fd, int always_block, int *fdblock)
1910 {
1911         struct per_dev_info *pdi = NULL;
1912         unsigned int events = 0;
1913
1914         while (!is_done() && events < rb_batch) {
1915                 struct blk_io_trace *bit;
1916                 struct trace *t;
1917                 int pdu_len, should_block, ret;
1918                 __u32 magic;
1919
1920                 bit = bit_alloc();
1921
1922                 should_block = !events || always_block;
1923
1924                 ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
1925                 if (ret) {
1926                         bit_free(bit);
1927                         if (!events && ret < 0)
1928                                 events = ret;
1929                         break;
1930                 }
1931
1932                 /*
1933                  * look at first trace to check whether we need to convert
1934                  * data in the future
1935                  */
1936                 if (data_is_native == -1 && check_data_endianness(bit->magic))
1937                         break;
1938
1939                 magic = get_magic(bit);
1940                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1941                         fprintf(stderr, "Bad magic %x\n", magic);
1942                         break;
1943                 }
1944
1945                 pdu_len = get_pdulen(bit);
1946                 if (pdu_len) {
1947                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1948
1949                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
1950                                 bit_free(ptr);
1951                                 break;
1952                         }
1953
1954                         bit = ptr;
1955                 }
1956
1957                 trace_to_cpu(bit);
1958
1959                 if (verify_trace(bit)) {
1960                         bit_free(bit);
1961                         continue;
1962                 }
1963
1964                 /*
1965                  * not a real trace, so grab and handle it here
1966                  */
1967                 if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY)) {
1968                         add_ppm_hash(bit->pid, (char *) bit + sizeof(*bit));
1969                         output_binary(bit, sizeof(*bit) + bit->pdu_len);
1970                         continue;
1971                 }
1972
1973                 t = t_alloc();
1974                 memset(t, 0, sizeof(*t));
1975                 t->bit = bit;
1976                 t->read_sequence = read_sequence;
1977
1978                 t->next = trace_list;
1979                 trace_list = t;
1980
1981                 if (!pdi || pdi->dev != bit->device)
1982                         pdi = get_dev_info(bit->device);
1983
1984                 if (bit->time > pdi->last_read_time)
1985                         pdi->last_read_time = bit->time;
1986
1987                 events++;
1988         }
1989
1990         return events;
1991 }
1992
1993 static int do_file(void)
1994 {
1995         struct per_cpu_info *pci;
1996         struct per_dev_info *pdi;
1997         int i, j, events, events_added;
1998
1999         /*
2000          * first prepare all files for reading
2001          */
2002         for (i = 0; i < ndevices; i++) {
2003                 pdi = &devices[i];
2004                 pdi->nfiles = 0;
2005
2006                 for (j = 0;; j++) {
2007                         struct stat st;
2008                         int len = 0;
2009                         char *p, *dname;
2010
2011                         pci = get_cpu_info(pdi, j);
2012                         pci->cpu = j;
2013                         pci->fd = -1;
2014                         pci->fdblock = -1;
2015         
2016                         p = strdup(pdi->name);
2017                         dname = dirname(p);
2018                         if (strcmp(dname, ".")) {
2019                                 input_dir = dname;
2020                                 p = strdup(pdi->name);
2021                                 strcpy(pdi->name, basename(p));
2022                         }
2023                         free(p);
2024
2025                         if (input_dir)
2026                                 len = sprintf(pci->fname, "%s/", input_dir);
2027
2028                         snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
2029                                  "%s.blktrace.%d", pdi->name, pci->cpu);
2030                         if (stat(pci->fname, &st) < 0)
2031                                 break;
2032                         if (st.st_size) {
2033                                 pci->fd = open(pci->fname, O_RDONLY);
2034                                 if (pci->fd < 0) {
2035                                         perror(pci->fname);
2036                                         continue;
2037                                 }
2038                         }
2039
2040                         printf("Input file %s added\n", pci->fname);
2041                         pdi->nfiles++;
2042                         cpu_mark_online(pdi, pci->cpu);
2043                 }
2044         }
2045
2046         /*
2047          * now loop over the files reading in the data
2048          */
2049         do {
2050                 unsigned long long youngest;
2051
2052                 events_added = 0;
2053                 last_allowed_time = -1ULL;
2054                 read_sequence++;
2055
2056                 for (i = 0; i < ndevices; i++) {
2057                         pdi = &devices[i];
2058                         pdi->last_read_time = -1ULL;
2059
2060                         for (j = 0; j < pdi->nfiles; j++) {
2061
2062                                 pci = get_cpu_info(pdi, j);
2063
2064                                 if (pci->fd == -1)
2065                                         continue;
2066
2067                                 pci->smallest_seq_read = -1;
2068
2069                                 events = read_events(pci->fd, 1, &pci->fdblock);
2070                                 if (events <= 0) {
2071                                         cpu_mark_offline(pdi, pci->cpu);
2072                                         close(pci->fd);
2073                                         pci->fd = -1;
2074                                         continue;
2075                                 }
2076
2077                                 if (pdi->last_read_time < last_allowed_time)
2078                                         last_allowed_time = pdi->last_read_time;
2079
2080                                 events_added += events;
2081                         }
2082                 }
2083
2084                 if (sort_entries(&youngest))
2085                         break;
2086
2087                 if (youngest > stopwatch_end)
2088                         break;
2089
2090                 show_entries_rb(0);
2091
2092         } while (events_added);
2093
2094         if (rb_sort_entries)
2095                 show_entries_rb(1);
2096
2097         return 0;
2098 }
2099
2100 static int do_stdin(void)
2101 {
2102         unsigned long long youngest;
2103         int fd, events, fdblock;
2104
2105         last_allowed_time = -1ULL;
2106         fd = dup(STDIN_FILENO);
2107         if (fd == -1) {
2108                 perror("dup stdin");
2109                 return -1;
2110         }
2111
2112         fdblock = -1;
2113         while ((events = read_events(fd, 0, &fdblock)) > 0) {
2114                 read_sequence++;
2115         
2116 #if 0
2117                 smallest_seq_read = -1U;
2118 #endif
2119
2120                 if (sort_entries(&youngest))
2121                         break;
2122
2123                 if (youngest > stopwatch_end)
2124                         break;
2125
2126                 show_entries_rb(0);
2127         }
2128
2129         if (rb_sort_entries)
2130                 show_entries_rb(1);
2131
2132         close(fd);
2133         return 0;
2134 }
2135
2136 static void show_stats(void)
2137 {
2138         if (!ofp)
2139                 return;
2140         if (stats_printed)
2141                 return;
2142
2143         stats_printed = 1;
2144
2145         if (per_process_stats)
2146                 show_process_stats();
2147
2148         if (per_device_and_cpu_stats)
2149                 show_device_and_cpu_stats();
2150
2151         fflush(ofp);
2152 }
2153
2154 static void handle_sigint(__attribute__((__unused__)) int sig)
2155 {
2156         done = 1;
2157 }
2158
2159 /*
2160  * Extract start and duration times from a string, allowing
2161  * us to specify a time interval of interest within a trace.
2162  * Format: "duration" (start is zero) or "start:duration".
2163  */
2164 static int find_stopwatch_interval(char *string)
2165 {
2166         double value;
2167         char *sp;
2168
2169         value = strtod(string, &sp);
2170         if (sp == string) {
2171                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
2172                 return 1;
2173         }
2174         if (*sp == ':') {
2175                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
2176                 string = sp + 1;
2177                 value = strtod(string, &sp);
2178                 if (sp == string || *sp != '\0') {
2179                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
2180                                 string);
2181                         return 1;
2182                 }
2183         } else if (*sp != '\0') {
2184                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
2185                 return 1;
2186         }
2187         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
2188         if (stopwatch_end <= stopwatch_start) {
2189                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
2190                         stopwatch_start, stopwatch_end);
2191                 return 1;
2192         }
2193
2194         return 0;
2195 }
2196
2197 static char usage_str[] = \
2198         "[ -i <input name> ] [-o <output name> [ -s ] [ -t ] [ -q ]\n" \
2199         "[ -w start:stop ] [ -f output format ] [ -F format spec ] [ -v] \n\n" \
2200         "\t-i Input file containing trace data, or '-' for stdin\n" \
2201         "\t-D Directory to prepend to input file names\n" \
2202         "\t-o Output file. If not given, output is stdout\n" \
2203         "\t-d Output file. If specified, binary data is written to file\n" \
2204         "\t-b stdin read batching\n" \
2205         "\t-s Show per-program io statistics\n" \
2206         "\t-h Hash processes by name, not pid\n" \
2207         "\t-t Track individual ios. Will tell you the time a request took\n" \
2208         "\t   to get queued, to get dispatched, and to get completed\n" \
2209         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
2210         "\t-w Only parse data between the given time interval in seconds.\n" \
2211         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
2212         "\t-f Output format. Customize the output format. The format field\n" \
2213         "\t   identifies can be found in the documentation\n" \
2214         "\t-F Format specification. Can be found in the documentation\n" \
2215         "\t-v More verbose for marginal errors\n" \
2216         "\t-V Print program version info\n\n";
2217
2218 static void usage(char *prog)
2219 {
2220         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
2221 }
2222
2223 int main(int argc, char *argv[])
2224 {
2225         char *ofp_buffer;
2226         int i, c, ret, mode;
2227         int act_mask_tmp = 0;
2228
2229         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
2230                 switch (c) {
2231                 case 'a':
2232                         i = find_mask_map(optarg);
2233                         if (i < 0) {
2234                                 fprintf(stderr,"Invalid action mask %s\n",
2235                                         optarg);
2236                                 return 1;
2237                         }
2238                         act_mask_tmp |= i;
2239                         break;
2240
2241                 case 'A':
2242                         if ((sscanf(optarg, "%x", &i) != 1) || 
2243                                                         !valid_act_opt(i)) {
2244                                 fprintf(stderr,
2245                                         "Invalid set action mask %s/0x%x\n",
2246                                         optarg, i);
2247                                 return 1;
2248                         }
2249                         act_mask_tmp = i;
2250                         break;
2251                 case 'i':
2252                         if (!strcmp(optarg, "-") && !pipeline)
2253                                 pipeline = 1;
2254                         else if (resize_devices(optarg) != 0)
2255                                 return 1;
2256                         break;
2257                 case 'D':
2258                         input_dir = optarg;
2259                         break;
2260                 case 'o':
2261                         output_name = optarg;
2262                         break;
2263                 case 'b':
2264                         rb_batch = atoi(optarg);
2265                         if (rb_batch <= 0)
2266                                 rb_batch = RB_BATCH_DEFAULT;
2267                         break;
2268                 case 's':
2269                         per_process_stats = 1;
2270                         break;
2271                 case 't':
2272                         track_ios = 1;
2273                         break;
2274                 case 'q':
2275                         per_device_and_cpu_stats = 0;
2276                         break;
2277                 case 'w':
2278                         if (find_stopwatch_interval(optarg) != 0)
2279                                 return 1;
2280                         break;
2281                 case 'f':
2282                         set_all_format_specs(optarg);
2283                         break;
2284                 case 'F':
2285                         if (add_format_spec(optarg) != 0)
2286                                 return 1;
2287                         break;
2288                 case 'h':
2289                         ppi_hash_by_pid = 0;
2290                         break;
2291                 case 'v':
2292                         verbose++;
2293                         break;
2294                 case 'V':
2295                         printf("%s version %s\n", argv[0], blkparse_version);
2296                         return 0;
2297                 case 'd':
2298                         dump_binary = optarg;
2299                         break;
2300                 default:
2301                         usage(argv[0]);
2302                         return 1;
2303                 }
2304         }
2305
2306         while (optind < argc) {
2307                 if (!strcmp(argv[optind], "-") && !pipeline)
2308                         pipeline = 1;
2309                 else if (resize_devices(argv[optind]) != 0)
2310                         return 1;
2311                 optind++;
2312         }
2313
2314         if (!pipeline && !ndevices) {
2315                 usage(argv[0]);
2316                 return 1;
2317         }
2318
2319         if (act_mask_tmp != 0)
2320                 act_mask = act_mask_tmp;
2321
2322         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
2323
2324         signal(SIGINT, handle_sigint);
2325         signal(SIGHUP, handle_sigint);
2326         signal(SIGTERM, handle_sigint);
2327
2328         setlocale(LC_NUMERIC, "en_US");
2329
2330         if (!output_name) {
2331                 ofp = fdopen(STDOUT_FILENO, "w");
2332                 mode = _IOLBF;
2333         } else {
2334                 char ofname[128];
2335
2336                 snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
2337                 ofp = fopen(ofname, "w");
2338                 mode = _IOFBF;
2339         }
2340
2341         if (!ofp) {
2342                 perror("fopen");
2343                 return 1;
2344         }
2345
2346         ofp_buffer = malloc(4096);      
2347         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
2348                 perror("setvbuf");
2349                 return 1;
2350         }
2351
2352         if (dump_binary) {
2353                 dump_fd = creat(dump_binary, 0666);
2354                 if (dump_fd < 0) {
2355                         perror(dump_binary);
2356                         dump_binary = NULL;
2357                         return 1;
2358                 }
2359         }
2360
2361         if (pipeline)
2362                 ret = do_stdin();
2363         else
2364                 ret = do_file();
2365
2366         show_stats();
2367         free(ofp_buffer);
2368         return ret;
2369 }