blkparse: Fix device in event tracking error messages
[blktrace.git] / blkparse.c
index d3e5a545afcacbee5ac28d01a0b83946b863cf52..0054d4f0aa2ed070da17da74b00e883fb59f98bf 100644 (file)
@@ -2,6 +2,7 @@
  * block queue tracing parse application
  *
  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
+ * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
  *
  *  This program is free software; you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
 #include <errno.h>
 #include <signal.h>
 #include <locale.h>
-#include <limits.h>
-#include <ctype.h>
+#include <libgen.h>
 
 #include "blktrace.h"
 #include "rbtree.h"
+#include "jhash.h"
 
-#define SECONDS(x)             ((unsigned long long)(x) / 1000000000)
-#define NANO_SECONDS(x)                ((unsigned long long)(x) % 1000000000)
-#define DOUBLE_TO_NANO_ULL(d)  ((unsigned long long)((d) * 1000000000))
+static char blkparse_version[] = "1.2.0";
 
-#define MINORBITS      20
-#define MINORMASK      ((1U << MINORBITS) - 1)
-#define MAJOR(dev)     ((unsigned int) ((dev) >> MINORBITS))
-#define MINOR(dev)     ((unsigned int) ((dev) & MINORMASK))
-
-#define min(a, b)      ((a) < (b) ? (a) : (b))
-
-#define HEADER         "%D %2c %8s %5T.%9t %5p %2a %3d "
-
-struct io_stats {
-       unsigned long qreads, qwrites, creads, cwrites, mreads, mwrites;
-       unsigned long ireads, iwrites;
-       unsigned long long qread_kb, qwrite_kb, cread_kb, cwrite_kb;
-       unsigned long long iread_kb, iwrite_kb;
-       unsigned long io_unplugs, timer_unplugs;
-};
-
-struct per_cpu_info {
-       int cpu;
-       int nelems;
-
-       int fd;
-       char fname[128];
-
-       struct io_stats io_stats;
+struct skip_info {
+       unsigned long start, end;
+       struct skip_info *prev, *next;
 };
 
 struct per_dev_info {
-       dev_t id;
+       dev_t dev;
        char *name;
 
        int backwards;
        unsigned long long events;
+       unsigned long long first_reported_time;
        unsigned long long last_reported_time;
+       unsigned long long last_read_time;
        struct io_stats io_stats;
-       unsigned long last_sequence;
        unsigned long skips;
+       unsigned long long seq_skips;
+       unsigned int max_depth[2];
+       unsigned int cur_depth[2];
 
+       struct rb_root rb_track;
+
+       int nfiles;
        int ncpus;
+
+       unsigned long *cpu_map;
+       unsigned int cpu_map_max;
+
        struct per_cpu_info *cpus;
 };
 
+/*
+ * some duplicated effort here, we can unify this hash and the ppi hash later
+ */
+struct process_pid_map {
+       pid_t pid;
+       char comm[16];
+       struct process_pid_map *hash_next, *list_next;
+};
+
+#define PPM_HASH_SHIFT (8)
+#define PPM_HASH_SIZE  (1 << PPM_HASH_SHIFT)
+#define PPM_HASH_MASK  (PPM_HASH_SIZE - 1)
+static struct process_pid_map *ppm_hash_table[PPM_HASH_SIZE];
+
 struct per_process_info {
-       char name[16];
-       __u32 pid;
+       struct process_pid_map *ppm;
        struct io_stats io_stats;
        struct per_process_info *hash_next, *list_next;
+       int more_than_one;
 
        /*
         * individual io stats
@@ -96,23 +98,37 @@ struct per_process_info {
 };
 
 #define PPI_HASH_SHIFT (8)
-static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
+#define PPI_HASH_SIZE  (1 << PPI_HASH_SHIFT)
+#define PPI_HASH_MASK  (PPI_HASH_SIZE - 1)
+
+enum {
+       SORT_PROG_EVENT_N,   /* Program Name */
+       SORT_PROG_EVENT_QKB, /* KB: Queued read and write */
+       SORT_PROG_EVENT_RKB, /* KB: Queued Read */
+       SORT_PROG_EVENT_WKB, /* KB: Queued Write */
+       SORT_PROG_EVENT_CKB, /* KB: Complete */
+       SORT_PROG_EVENT_QIO, /* IO: Queued read and write */
+       SORT_PROG_EVENT_RIO, /* IO: Queued Read */
+       SORT_PROG_EVENT_WIO, /* IO: Queued Write */
+       SORT_PROG_EVENT_CIO, /* IO: Complete */
+};
+
+static struct per_process_info *ppi_hash_table[PPI_HASH_SIZE];
 static struct per_process_info *ppi_list;
 static int ppi_list_entries;
 
-#define S_OPTS "i:o:b:stqw:f:F:"
 static struct option l_opts[] = {
-       {
-               .name = "input",
+       {
+               .name = "act-mask",
                .has_arg = required_argument,
                .flag = NULL,
-               .val = 'i'
+               .val = 'a'
        },
        {
-               .name = "output",
+               .name = "set-mask",
                .has_arg = required_argument,
                .flag = NULL,
-               .val = 'o'
+               .val = 'A'
        },
        {
                .name = "batch",
@@ -121,16 +137,58 @@ static struct option l_opts[] = {
                .val = 'b'
        },
        {
-               .name = "per program stats",
+               .name = "input-directory",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'D'
+       },
+       {
+               .name = "dump-binary",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'd'
+       },
+       {
+               .name = "format",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'f'
+       },
+       {
+               .name = "format-spec",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'F'
+       },
+       {
+               .name = "hash-by-name",
                .has_arg = no_argument,
                .flag = NULL,
-               .val = 's'
+               .val = 'h'
+       },
+       {
+               .name = "input",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'i'
        },
        {
-               .name = "track ios",
+               .name = "no-msgs",
                .has_arg = no_argument,
                .flag = NULL,
-               .val = 't'
+               .val = 'M'
+       },
+       {
+               .name = "output",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'o'
+       },
+       {
+               .name = "no-text-output",
+               .has_arg = no_argument,
+               .flag = NULL,
+               .val = 'O'
        },
        {
                .name = "quiet",
@@ -138,6 +196,24 @@ static struct option l_opts[] = {
                .flag = NULL,
                .val = 'q'
        },
+       {
+               .name = "per-program-stats",
+               .has_arg = no_argument,
+               .flag = NULL,
+               .val = 's'
+       },
+       {
+               .name = "sort-program-stats",
+               .has_arg = required_argument,
+               .flag = NULL,
+               .val = 'S'
+       },
+       {
+               .name = "track-ios",
+               .has_arg = no_argument,
+               .flag = NULL,
+               .val = 't'
+       },
        {
                .name = "stopwatch",
                .has_arg = required_argument,
@@ -145,17 +221,20 @@ static struct option l_opts[] = {
                .val = 'w'
        },
        {
-               .name = "format",
-               .has_arg = required_argument,
+               .name = "verbose",
+               .has_arg = no_argument,
                .flag = NULL,
-               .val = 'f'
+               .val = 'v'
        },
        {
-               .name = "format-spec",
-               .has_arg = required_argument,
+               .name = "version",
+               .has_arg = no_argument,
                .flag = NULL,
-               .val = 'F'
+               .val = 'V'
        },
+       {
+               .name = NULL,
+       }
 };
 
 /*
@@ -165,23 +244,28 @@ struct trace {
        struct blk_io_trace *bit;
        struct rb_node rb_node;
        struct trace *next;
-       int skipped;
+       unsigned long read_sequence;
 };
 
 static struct rb_root rb_sort_root;
-static struct rb_root rb_track_root;
+static unsigned long rb_sort_entries;
 
 static struct trace *trace_list;
 
+/*
+ * allocation cache
+ */
+static struct blk_io_trace *bit_alloc_list;
+static struct trace *t_alloc_list;
+
 /*
  * for tracking individual ios
  */
 struct io_track {
        struct rb_node rb_node;
 
-       dev_t device;
+       struct process_pid_map *ppm;
        __u64 sector;
-       __u32 pid;
        unsigned long long allocation_time;
        unsigned long long queue_time;
        unsigned long long dispatch_time;
@@ -191,217 +275,787 @@ struct io_track {
 static int ndevices;
 static struct per_dev_info *devices;
 static char *get_dev_name(struct per_dev_info *, char *, int);
+static int trace_rb_insert_last(struct per_dev_info *, struct trace *);
 
-static FILE *ofp;
+FILE *ofp = NULL;
 static char *output_name;
+static char *input_dir;
 
 static unsigned long long genesis_time;
+static unsigned long long last_allowed_time;
 static unsigned long long stopwatch_start;     /* start from zero by default */
-static unsigned long long stopwatch_end = ULONG_LONG_MAX;      /* "infinity" */
+static unsigned long long stopwatch_end = -1ULL;       /* "infinity" */
+static unsigned long read_sequence;
 
 static int per_process_stats;
+static int per_process_stats_event = SORT_PROG_EVENT_N;
+static int per_device_and_cpu_stats = 1;
 static int track_ios;
+static int ppi_hash_by_pid = 1;
+static int verbose;
+static unsigned int act_mask = -1U;
+static int stats_printed;
+static int bin_output_msgs = 1;
+int data_is_native = -1;
+
+static FILE *dump_fp;
+static char *dump_binary;
+
+static unsigned int t_alloc_cache;
+static unsigned int bit_alloc_cache;
 
-#define RB_BATCH_DEFAULT       (1024)
-static int rb_batch = RB_BATCH_DEFAULT;
+#define RB_BATCH_DEFAULT       (512)
+static unsigned int rb_batch = RB_BATCH_DEFAULT;
 
 static int pipeline;
+static char *pipename;
+
+static int text_output = 1;
 
 #define is_done()      (*(volatile int *)(&done))
 static volatile int done;
 
-static inline unsigned long hash_long(unsigned long val)
+struct timespec                abs_start_time;
+static unsigned long long start_timestamp;
+
+static int have_drv_data = 0;
+
+#define JHASH_RANDOM   (0x3af5f2ee)
+
+#define CPUS_PER_LONG  (8 * sizeof(unsigned long))
+#define CPU_IDX(cpu)   ((cpu) / CPUS_PER_LONG)
+#define CPU_BIT(cpu)   ((cpu) & (CPUS_PER_LONG - 1))
+
+static void output_binary(void *buf, int len)
 {
-#if __WORDSIZE == 32
-       val *= 0x9e370001UL;
-#elif __WORDSIZE == 64
-       val *= 0x9e37fffffffc0001UL;
-#else
-#error unknown word size
-#endif
+       if (dump_binary) {
+               size_t n = fwrite(buf, len, 1, dump_fp);
+               if (n != 1) {
+                       perror(dump_binary);
+                       fclose(dump_fp);
+                       dump_binary = NULL;
+               }
+       }
+}
+
+static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
+{
+       struct per_cpu_info *cpus = pdi->cpus;
+       int ncpus = pdi->ncpus;
+       int new_count = cpu + 1;
+       int new_space, size;
+       char *new_start;
+
+       size = new_count * sizeof(struct per_cpu_info);
+       cpus = realloc(cpus, size);
+       if (!cpus) {
+               char name[20];
+               fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
+                       get_dev_name(pdi, name, sizeof(name)), size);
+               exit(1);
+       }
+
+       new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
+       new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
+       memset(new_start, 0, new_space);
+
+       pdi->ncpus = new_count;
+       pdi->cpus = cpus;
+
+       for (new_count = 0; new_count < pdi->ncpus; new_count++) {
+               struct per_cpu_info *pci = &pdi->cpus[new_count];
 
-       return val >> (__WORDSIZE - PPI_HASH_SHIFT);
+               if (!pci->fd) {
+                       pci->fd = -1;
+                       memset(&pci->rb_last, 0, sizeof(pci->rb_last));
+                       pci->rb_last_entries = 0;
+                       pci->last_sequence = -1;
+               }
+       }
 }
 
-static inline void add_process_to_hash(struct per_process_info *ppi)
+static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
 {
-       const int hash_idx = hash_long(ppi->pid);
+       struct per_cpu_info *pci;
+
+       if (cpu >= pdi->ncpus)
+               resize_cpu_info(pdi, cpu);
 
-       ppi->hash_next = ppi_hash[hash_idx];
-       ppi_hash[hash_idx] = ppi;
+       pci = &pdi->cpus[cpu];
+       pci->cpu = cpu;
+       return pci;
 }
 
-static inline void add_process_to_list(struct per_process_info *ppi)
+
+static int resize_devices(char *name)
 {
-       ppi->list_next = ppi_list;
-       ppi_list = ppi;
-       ppi_list_entries++;
+       int size = (ndevices + 1) * sizeof(struct per_dev_info);
+
+       devices = realloc(devices, size);
+       if (!devices) {
+               fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
+               return 1;
+       }
+       memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
+       devices[ndevices].name = name;
+       ndevices++;
+       return 0;
 }
 
-static struct per_process_info *find_process_by_pid(__u32 pid)
+static struct per_dev_info *get_dev_info(dev_t dev)
 {
-       const int hash_idx = hash_long(pid);
-       struct per_process_info *ppi;
+       struct per_dev_info *pdi;
+       int i;
 
-       ppi = ppi_hash[hash_idx];
-       while (ppi) {
-               if (ppi->pid == pid)
-                       return ppi;
+       for (i = 0; i < ndevices; i++) {
+               if (!devices[i].dev)
+                       devices[i].dev = dev;
+               if (devices[i].dev == dev)
+                       return &devices[i];
+       }
 
-               ppi = ppi->hash_next;
+       if (resize_devices(NULL))
+               return NULL;
+
+       pdi = &devices[ndevices - 1];
+       pdi->dev = dev;
+       pdi->first_reported_time = 0;
+       pdi->last_read_time = 0;
+
+       return pdi;
+}
+
+static void insert_skip(struct per_cpu_info *pci, unsigned long start,
+                       unsigned long end)
+{
+       struct skip_info *sip;
+
+       for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
+               if (end == (sip->start - 1)) {
+                       sip->start = start;
+                       return;
+               } else if (start == (sip->end + 1)) {
+                       sip->end = end;
+                       return;
+               }
        }
 
-       return NULL;
+       sip = malloc(sizeof(struct skip_info));
+       sip->start = start;
+       sip->end = end;
+       sip->prev = sip->next = NULL;
+       if (pci->skips_tail == NULL)
+               pci->skips_head = pci->skips_tail = sip;
+       else {
+               sip->prev = pci->skips_tail;
+               pci->skips_tail->next = sip;
+               pci->skips_tail = sip;
+       }
 }
 
-static inline int trace_rb_insert(struct trace *t)
+static void remove_sip(struct per_cpu_info *pci, struct skip_info *sip)
 {
-       struct rb_node **p = &rb_sort_root.rb_node;
-       struct rb_node *parent = NULL;
-       struct trace *__t;
+       if (sip->prev == NULL) {
+               if (sip->next == NULL)
+                       pci->skips_head = pci->skips_tail = NULL;
+               else {
+                       pci->skips_head = sip->next;
+                       sip->next->prev = NULL;
+               }
+       } else if (sip->next == NULL) {
+               pci->skips_tail = sip->prev;
+               sip->prev->next = NULL;
+       } else {
+               sip->prev->next = sip->next;
+               sip->next->prev = sip->prev;
+       }
 
-       if (genesis_time == 0 || t->bit->time < genesis_time)
-               genesis_time = t->bit->time;
+       sip->prev = sip->next = NULL;
+       free(sip);
+}
 
-       while (*p) {
-               parent = *p;
-               __t = rb_entry(parent, struct trace, rb_node);
+#define IN_SKIP(sip,seq) (((sip)->start <= (seq)) && ((seq) <= sip->end))
+static int check_current_skips(struct per_cpu_info *pci, unsigned long seq)
+{
+       struct skip_info *sip;
 
-               if (t->bit->time < __t->bit->time)
-                       p = &(*p)->rb_left;
-               else if (t->bit->time > __t->bit->time)
-                       p = &(*p)->rb_right;
-               else if (t->bit->device < __t->bit->device)
-                       p = &(*p)->rb_left;
-               else if (t->bit->device > __t->bit->device)
-                       p = &(*p)->rb_right;
-               else if (t->bit->sequence < __t->bit->sequence)
-                       p = &(*p)->rb_left;
-               else if (t->bit->sequence > __t->bit->sequence)
-                       p = &(*p)->rb_right;
-               else if (t->bit->device == __t->bit->device) {
-                       fprintf(stderr,
-                               "sequence alias (%d) on device %d,%d!\n",
-                               t->bit->sequence,
-                               MAJOR(t->bit->device), MINOR(t->bit->device));
+       for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
+               if (IN_SKIP(sip, seq)) {
+                       if (sip->start == seq) {
+                               if (sip->end == seq)
+                                       remove_sip(pci, sip);
+                               else
+                                       sip->start += 1;
+                       } else if (sip->end == seq)
+                               sip->end -= 1;
+                       else {
+                               sip->end = seq - 1;
+                               insert_skip(pci, seq + 1, sip->end);
+                       }
                        return 1;
                }
        }
 
-       rb_link_node(&t->rb_node, parent, p);
-       rb_insert_color(&t->rb_node, &rb_sort_root);
        return 0;
 }
 
-static inline int track_rb_insert(struct io_track *iot)
+static void collect_pdi_skips(struct per_dev_info *pdi)
 {
-       struct rb_node **p = &rb_track_root.rb_node;
-       struct rb_node *parent = NULL;
-       struct io_track *__iot;
+       struct skip_info *sip;
+       int cpu;
 
-       while (*p) {
-               parent = *p;
+       pdi->skips = 0;
+       pdi->seq_skips = 0;
 
-               __iot = rb_entry(parent, struct io_track, rb_node);
+       for (cpu = 0; cpu < pdi->ncpus; cpu++) {
+               struct per_cpu_info *pci = &pdi->cpus[cpu];
 
-               if (iot->device < __iot->device)
-                       p = &(*p)->rb_left;
-               else if (iot->device > __iot->device)
-                       p = &(*p)->rb_right;
-               else if (iot->sector < __iot->sector)
-                       p = &(*p)->rb_left;
-               else if (iot->sector > __iot->sector)
-                       p = &(*p)->rb_right;
-               else {
-                       fprintf(stderr,
-                               "sector alias (%Lu) on device %d,%d!\n",
-                               (unsigned long long) iot->sector,
-                               MAJOR(iot->device), MINOR(iot->device));
-                       return 1;
+               for (sip = pci->skips_head; sip != NULL; sip = sip->next) {
+                       pdi->skips++;
+                       pdi->seq_skips += (sip->end - sip->start + 1);
+                       if (verbose)
+                               fprintf(stderr,"(%d,%d): skipping %lu -> %lu\n",
+                                       MAJOR(pdi->dev), MINOR(pdi->dev),
+                                       sip->start, sip->end);
                }
        }
-
-       rb_link_node(&iot->rb_node, parent, p);
-       rb_insert_color(&iot->rb_node, &rb_track_root);
-       return 0;
 }
 
-static struct io_track *__find_track(dev_t device, __u64 sector)
+static void cpu_mark_online(struct per_dev_info *pdi, unsigned int cpu)
 {
-       struct rb_node **p = &rb_track_root.rb_node;
-       struct rb_node *parent = NULL;
-       struct io_track *__iot;
+       if (cpu >= pdi->cpu_map_max || !pdi->cpu_map) {
+               int new_max = (cpu + CPUS_PER_LONG) & ~(CPUS_PER_LONG - 1);
+               unsigned long *map = malloc(new_max / sizeof(long));
 
-       while (*p) {
-               parent = *p;
-               
-               __iot = rb_entry(parent, struct io_track, rb_node);
+               memset(map, 0, new_max / sizeof(long));
 
-               if (device < __iot->device)
-                       p = &(*p)->rb_left;
-               else if (device > __iot->device)
-                       p = &(*p)->rb_right;
-               else if (sector < __iot->sector)
-                       p = &(*p)->rb_left;
-               else if (sector > __iot->sector)
-                       p = &(*p)->rb_right;
-               else
-                       return __iot;
+               if (pdi->cpu_map) {
+                       memcpy(map, pdi->cpu_map, pdi->cpu_map_max / sizeof(long));
+                       free(pdi->cpu_map);
+               }
+
+               pdi->cpu_map = map;
+               pdi->cpu_map_max = new_max;
        }
 
-       return NULL;
+       pdi->cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
 }
 
-static struct io_track *find_track(__u32 pid, dev_t device, __u64 sector)
+static inline void cpu_mark_offline(struct per_dev_info *pdi, int cpu)
 {
-       struct io_track *iot;
+       pdi->cpu_map[CPU_IDX(cpu)] &= ~(1UL << CPU_BIT(cpu));
+}
 
-       iot = __find_track(device, sector);
-       if (!iot) {
-               iot = malloc(sizeof(*iot));
-               iot->pid = pid;
-               iot->device = device;
-               iot->sector = sector;
-               track_rb_insert(iot);
-       }
+static inline int cpu_is_online(struct per_dev_info *pdi, int cpu)
+{
+       return (pdi->cpu_map[CPU_IDX(cpu)] & (1UL << CPU_BIT(cpu))) != 0;
+}
 
-       return iot;
+static inline int ppm_hash_pid(pid_t pid)
+{
+       return jhash_1word(pid, JHASH_RANDOM) & PPM_HASH_MASK;
 }
 
-static void log_track_frontmerge(struct blk_io_trace *t)
+static struct process_pid_map *find_ppm(pid_t pid)
 {
-       struct io_track *iot;
+       const int hash_idx = ppm_hash_pid(pid);
+       struct process_pid_map *ppm;
 
-       if (!track_ios)
-               return;
+       ppm = ppm_hash_table[hash_idx];
+       while (ppm) {
+               if (ppm->pid == pid)
+                       return ppm;
 
-       iot = __find_track(t->device, t->sector + (t->bytes >> 9));
-       if (!iot) {
-               fprintf(stderr, "failed to find mergeable event\n");
-               return;
+               ppm = ppm->hash_next;
        }
 
-       rb_erase(&iot->rb_node, &rb_track_root);
-       iot->sector -= t->bytes >> 9;
-       track_rb_insert(iot);
+       return NULL;
 }
 
-static void log_track_getrq(struct blk_io_trace *t)
+static struct process_pid_map *add_ppm_hash(pid_t pid, const char *name)
 {
-       struct io_track *iot;
+       const int hash_idx = ppm_hash_pid(pid);
+       struct process_pid_map *ppm;
 
-       if (!track_ios)
-               return;
+       ppm = find_ppm(pid);
+       if (!ppm) {
+               ppm = malloc(sizeof(*ppm));
+               memset(ppm, 0, sizeof(*ppm));
+               ppm->pid = pid;
+               memset(ppm->comm, 0, sizeof(ppm->comm));
+               strncpy(ppm->comm, name, sizeof(ppm->comm));
+               ppm->comm[sizeof(ppm->comm) - 1] = '\0';
+               ppm->hash_next = ppm_hash_table[hash_idx];
+               ppm_hash_table[hash_idx] = ppm;
+       }
 
-       iot = find_track(t->pid, t->device, t->sector);
-       iot->allocation_time = t->time;
+       return ppm;
 }
 
-
-/*
- * return time between rq allocation and queue
- */
-static unsigned long long log_track_queue(struct blk_io_trace *t)
+static void handle_notify(struct blk_io_trace *bit)
+{
+       void    *payload = (caddr_t) bit + sizeof(*bit);
+       __u32   two32[2];
+
+       switch (bit->action) {
+       case BLK_TN_PROCESS:
+               add_ppm_hash(bit->pid, payload);
+               break;
+
+       case BLK_TN_TIMESTAMP:
+               if (bit->pdu_len != sizeof(two32))
+                       return;
+               memcpy(two32, payload, sizeof(two32));
+               if (!data_is_native) {
+                       two32[0] = be32_to_cpu(two32[0]);
+                       two32[1] = be32_to_cpu(two32[1]);
+               }
+               start_timestamp = bit->time;
+               abs_start_time.tv_sec  = two32[0];
+               abs_start_time.tv_nsec = two32[1];
+               if (abs_start_time.tv_nsec < 0) {
+                       abs_start_time.tv_sec--;
+                       abs_start_time.tv_nsec += 1000000000;
+               }
+
+               break;
+
+       case BLK_TN_MESSAGE:
+               if (bit->pdu_len > 0) {
+                       char msg[bit->pdu_len+1];
+
+                       memcpy(msg, (char *)payload, bit->pdu_len);
+                       msg[bit->pdu_len] = '\0';
+
+                       fprintf(ofp,
+                               "%3d,%-3d %2d %8s %5d.%09lu %5u %2s %3s %s\n",
+                               MAJOR(bit->device), MINOR(bit->device),
+                               bit->cpu, "0", (int) SECONDS(bit->time),
+                               (unsigned long) NANO_SECONDS(bit->time),
+                               0, "m", "N", msg);
+               }
+               break;
+
+       default:
+               /* Ignore unknown notify events */
+               ;
+       }
+}
+
+char *find_process_name(pid_t pid)
+{
+       struct process_pid_map *ppm = find_ppm(pid);
+
+       if (ppm)
+               return ppm->comm;
+
+       return NULL;
+}
+
+static inline int ppi_hash_pid(pid_t pid)
+{
+       return jhash_1word(pid, JHASH_RANDOM) & PPI_HASH_MASK;
+}
+
+static inline int ppi_hash_name(const char *name)
+{
+       return jhash(name, 16, JHASH_RANDOM) & PPI_HASH_MASK;
+}
+
+static inline int ppi_hash(struct per_process_info *ppi)
+{
+       struct process_pid_map *ppm = ppi->ppm;
+
+       if (ppi_hash_by_pid)
+               return ppi_hash_pid(ppm->pid);
+
+       return ppi_hash_name(ppm->comm);
+}
+
+static inline void add_ppi_to_hash(struct per_process_info *ppi)
+{
+       const int hash_idx = ppi_hash(ppi);
+
+       ppi->hash_next = ppi_hash_table[hash_idx];
+       ppi_hash_table[hash_idx] = ppi;
+}
+
+static inline void add_ppi_to_list(struct per_process_info *ppi)
+{
+       ppi->list_next = ppi_list;
+       ppi_list = ppi;
+       ppi_list_entries++;
+}
+
+static struct per_process_info *find_ppi_by_name(char *name)
+{
+       const int hash_idx = ppi_hash_name(name);
+       struct per_process_info *ppi;
+
+       ppi = ppi_hash_table[hash_idx];
+       while (ppi) {
+               struct process_pid_map *ppm = ppi->ppm;
+
+               if (!strcmp(ppm->comm, name))
+                       return ppi;
+
+               ppi = ppi->hash_next;
+       }
+
+       return NULL;
+}
+
+static struct per_process_info *find_ppi_by_pid(pid_t pid)
+{
+       const int hash_idx = ppi_hash_pid(pid);
+       struct per_process_info *ppi;
+
+       ppi = ppi_hash_table[hash_idx];
+       while (ppi) {
+               struct process_pid_map *ppm = ppi->ppm;
+
+               if (ppm->pid == pid)
+                       return ppi;
+
+               ppi = ppi->hash_next;
+       }
+
+       return NULL;
+}
+
+static struct per_process_info *find_ppi(pid_t pid)
+{
+       struct per_process_info *ppi;
+       char *name;
+
+       if (ppi_hash_by_pid)
+               return find_ppi_by_pid(pid);
+
+       name = find_process_name(pid);
+       if (!name)
+               return NULL;
+
+       ppi = find_ppi_by_name(name);
+       if (ppi && ppi->ppm->pid != pid)
+               ppi->more_than_one = 1;
+
+       return ppi;
+}
+
+/*
+ * struct trace and blktrace allocation cache, we do potentially
+ * millions of mallocs for these structures while only using at most
+ * a few thousand at the time
+ */
+static inline void t_free(struct trace *t)
+{
+       if (t_alloc_cache < 1024) {
+               t->next = t_alloc_list;
+               t_alloc_list = t;
+               t_alloc_cache++;
+       } else
+               free(t);
+}
+
+static inline struct trace *t_alloc(void)
+{
+       struct trace *t = t_alloc_list;
+
+       if (t) {
+               t_alloc_list = t->next;
+               t_alloc_cache--;
+               return t;
+       }
+
+       return malloc(sizeof(*t));
+}
+
+static inline void bit_free(struct blk_io_trace *bit)
+{
+       if (bit_alloc_cache < 1024 && !bit->pdu_len) {
+               /*
+                * abuse a 64-bit field for a next pointer for the free item
+                */
+               bit->time = (__u64) (unsigned long) bit_alloc_list;
+               bit_alloc_list = (struct blk_io_trace *) bit;
+               bit_alloc_cache++;
+       } else
+               free(bit);
+}
+
+static inline struct blk_io_trace *bit_alloc(void)
+{
+       struct blk_io_trace *bit = bit_alloc_list;
+
+       if (bit) {
+               bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
+                                bit->time;
+               bit_alloc_cache--;
+               return bit;
+       }
+
+       return malloc(sizeof(*bit));
+}
+
+static inline void __put_trace_last(struct per_dev_info *pdi, struct trace *t)
+{
+       struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
+
+       rb_erase(&t->rb_node, &pci->rb_last);
+       pci->rb_last_entries--;
+
+       bit_free(t->bit);
+       t_free(t);
+}
+
+static void put_trace(struct per_dev_info *pdi, struct trace *t)
+{
+       rb_erase(&t->rb_node, &rb_sort_root);
+       rb_sort_entries--;
+
+       trace_rb_insert_last(pdi, t);
+}
+
+static inline int trace_rb_insert(struct trace *t, struct rb_root *root)
+{
+       struct rb_node **p = &root->rb_node;
+       struct rb_node *parent = NULL;
+       struct trace *__t;
+
+       while (*p) {
+               parent = *p;
+
+               __t = rb_entry(parent, struct trace, rb_node);
+
+               if (t->bit->time < __t->bit->time)
+                       p = &(*p)->rb_left;
+               else if (t->bit->time > __t->bit->time)
+                       p = &(*p)->rb_right;
+               else if (t->bit->device < __t->bit->device)
+                       p = &(*p)->rb_left;
+               else if (t->bit->device > __t->bit->device)
+                       p = &(*p)->rb_right;
+               else if (t->bit->sequence < __t->bit->sequence)
+                       p = &(*p)->rb_left;
+               else    /* >= sequence */
+                       p = &(*p)->rb_right;
+       }
+
+       rb_link_node(&t->rb_node, parent, p);
+       rb_insert_color(&t->rb_node, root);
+       return 0;
+}
+
+static inline int trace_rb_insert_sort(struct trace *t)
+{
+       if (!trace_rb_insert(t, &rb_sort_root)) {
+               rb_sort_entries++;
+               return 0;
+       }
+
+       return 1;
+}
+
+static int trace_rb_insert_last(struct per_dev_info *pdi, struct trace *t)
+{
+       struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
+
+       if (trace_rb_insert(t, &pci->rb_last))
+               return 1;
+
+       pci->rb_last_entries++;
+
+       if (pci->rb_last_entries > rb_batch * pdi->nfiles) {
+               struct rb_node *n = rb_first(&pci->rb_last);
+
+               t = rb_entry(n, struct trace, rb_node);
+               __put_trace_last(pdi, t);
+       }
+
+       return 0;
+}
+
+static struct trace *trace_rb_find(dev_t device, unsigned long sequence,
+                                  struct rb_root *root, int order)
+{
+       struct rb_node *n = root->rb_node;
+       struct rb_node *prev = NULL;
+       struct trace *__t;
+
+       while (n) {
+               __t = rb_entry(n, struct trace, rb_node);
+               prev = n;
+
+               if (device < __t->bit->device)
+                       n = n->rb_left;
+               else if (device > __t->bit->device)
+                       n = n->rb_right;
+               else if (sequence < __t->bit->sequence)
+                       n = n->rb_left;
+               else if (sequence > __t->bit->sequence)
+                       n = n->rb_right;
+               else
+                       return __t;
+       }
+
+       /*
+        * hack - the list may not be sequence ordered because some
+        * events don't have sequence and time matched. so we end up
+        * being a little off in the rb lookup here, because we don't
+        * know the time we are looking for. compensate by browsing
+        * a little ahead from the last entry to find the match
+        */
+       if (order && prev) {
+               int max = 5;
+
+               while (((n = rb_next(prev)) != NULL) && max--) {
+                       __t = rb_entry(n, struct trace, rb_node);
+
+                       if (__t->bit->device == device &&
+                           __t->bit->sequence == sequence)
+                               return __t;
+
+                       prev = n;
+               }
+       }
+
+       return NULL;
+}
+
+static inline struct trace *trace_rb_find_last(struct per_dev_info *pdi,
+                                              struct per_cpu_info *pci,
+                                              unsigned long seq)
+{
+       return trace_rb_find(pdi->dev, seq, &pci->rb_last, 0);
+}
+
+static inline int track_rb_insert(struct per_dev_info *pdi,struct io_track *iot)
+{
+       struct rb_node **p = &pdi->rb_track.rb_node;
+       struct rb_node *parent = NULL;
+       struct io_track *__iot;
+
+       while (*p) {
+               parent = *p;
+               __iot = rb_entry(parent, struct io_track, rb_node);
+
+               if (iot->sector < __iot->sector)
+                       p = &(*p)->rb_left;
+               else if (iot->sector > __iot->sector)
+                       p = &(*p)->rb_right;
+               else {
+                       fprintf(stderr,
+                               "sector alias (%Lu) on device %d,%d!\n",
+                               (unsigned long long) iot->sector,
+                               MAJOR(pdi->dev), MINOR(pdi->dev));
+                       return 1;
+               }
+       }
+
+       rb_link_node(&iot->rb_node, parent, p);
+       rb_insert_color(&iot->rb_node, &pdi->rb_track);
+       return 0;
+}
+
+static struct io_track *__find_track(struct per_dev_info *pdi, __u64 sector)
+{
+       struct rb_node *n = pdi->rb_track.rb_node;
+       struct io_track *__iot;
+
+       while (n) {
+               __iot = rb_entry(n, struct io_track, rb_node);
+
+               if (sector < __iot->sector)
+                       n = n->rb_left;
+               else if (sector > __iot->sector)
+                       n = n->rb_right;
+               else
+                       return __iot;
+       }
+
+       return NULL;
+}
+
+static struct io_track *find_track(struct per_dev_info *pdi, pid_t pid,
+                                  __u64 sector)
+{
+       struct io_track *iot;
+
+       iot = __find_track(pdi, sector);
+       if (!iot) {
+               iot = malloc(sizeof(*iot));
+               iot->ppm = find_ppm(pid);
+               if (!iot->ppm)
+                       iot->ppm = add_ppm_hash(pid, "unknown");
+               iot->sector = sector;
+               track_rb_insert(pdi, iot);
+       }
+
+       return iot;
+}
+
+static void log_track_frontmerge(struct per_dev_info *pdi,
+                                struct blk_io_trace *t)
+{
+       struct io_track *iot;
+
+       if (!track_ios)
+               return;
+
+       iot = __find_track(pdi, t->sector + t_sec(t));
+       if (!iot) {
+               if (verbose)
+                       fprintf(stderr, "merge not found for (%d,%d): %llu\n",
+                               MAJOR(t->device), MINOR(t->device),
+                               (unsigned long long) t->sector + t_sec(t));
+               return;
+       }
+
+       rb_erase(&iot->rb_node, &pdi->rb_track);
+       iot->sector -= t_sec(t);
+       track_rb_insert(pdi, iot);
+}
+
+static void log_track_getrq(struct per_dev_info *pdi, struct blk_io_trace *t)
+{
+       struct io_track *iot;
+
+       if (!track_ios)
+               return;
+
+       iot = find_track(pdi, t->pid, t->sector);
+       iot->allocation_time = t->time;
+}
+
+static inline int is_remapper(struct per_dev_info *pdi)
+{
+       int major = MAJOR(pdi->dev);
+
+       return (major == 253 || major == 9);
+}
+
+/*
+ * for md/dm setups, the interesting cycle is Q -> C. So track queueing
+ * time here, as dispatch time
+ */
+static void log_track_queue(struct per_dev_info *pdi, struct blk_io_trace *t)
+{
+       struct io_track *iot;
+
+       if (!track_ios)
+               return;
+       if (!is_remapper(pdi))
+               return;
+
+       iot = find_track(pdi, t->pid, t->sector);
+       iot->dispatch_time = t->time;
+}
+
+/*
+ * return time between rq allocation and insertion
+ */
+static unsigned long long log_track_insert(struct per_dev_info *pdi,
+                                          struct blk_io_trace *t)
 {
        unsigned long long elapsed;
        struct io_track *iot;
@@ -409,12 +1063,16 @@ static unsigned long long log_track_queue(struct blk_io_trace *t)
        if (!track_ios)
                return -1;
 
-       iot = find_track(t->pid, t->device, t->sector);
+       iot = find_track(pdi, t->pid, t->sector);
        iot->queue_time = t->time;
+
+       if (!iot->allocation_time)
+               return -1;
+
        elapsed = iot->queue_time - iot->allocation_time;
 
        if (per_process_stats) {
-               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               struct per_process_info *ppi = find_ppi(iot->ppm->pid);
                int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
 
                if (ppi && elapsed > ppi->longest_allocation_wait[w])
@@ -427,7 +1085,8 @@ static unsigned long long log_track_queue(struct blk_io_trace *t)
 /*
  * return time between queue and issue
  */
-static unsigned long long log_track_issue(struct blk_io_trace *t)
+static unsigned long long log_track_issue(struct per_dev_info *pdi,
+                                         struct blk_io_trace *t)
 {
        unsigned long long elapsed;
        struct io_track *iot;
@@ -437,9 +1096,12 @@ static unsigned long long log_track_issue(struct blk_io_trace *t)
        if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
                return -1;
 
-       iot = __find_track(t->device, t->sector);
+       iot = __find_track(pdi, t->sector);
        if (!iot) {
-               fprintf(stderr, "failed to find issue event\n");
+               if (verbose)
+                       fprintf(stderr, "issue not found for (%d,%d): %llu\n",
+                               MAJOR(t->device), MINOR(t->device),
+                               (unsigned long long) t->sector);
                return -1;
        }
 
@@ -447,7 +1109,7 @@ static unsigned long long log_track_issue(struct blk_io_trace *t)
        elapsed = iot->dispatch_time - iot->queue_time;
 
        if (per_process_stats) {
-               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               struct per_process_info *ppi = find_ppi(iot->ppm->pid);
                int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
 
                if (ppi && elapsed > ppi->longest_dispatch_wait[w])
@@ -460,19 +1122,21 @@ static unsigned long long log_track_issue(struct blk_io_trace *t)
 /*
  * return time between dispatch and complete
  */
-static unsigned long long log_track_complete(struct blk_io_trace *t)
+static unsigned long long log_track_complete(struct per_dev_info *pdi,
+                                            struct blk_io_trace *t)
 {
        unsigned long long elapsed;
        struct io_track *iot;
 
        if (!track_ios)
                return -1;
-       if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
-               return -1;
 
-       iot = __find_track(t->device, t->sector);
+       iot = __find_track(pdi, t->sector);
        if (!iot) {
-               fprintf(stderr, "failed to find complete event\n");
+               if (verbose)
+                       fprintf(stderr,"complete not found for (%d,%d): %llu\n",
+                               MAJOR(t->device), MINOR(t->device),
+                               (unsigned long long) t->sector);
                return -1;
        }
 
@@ -480,7 +1144,7 @@ static unsigned long long log_track_complete(struct blk_io_trace *t)
        elapsed = iot->completion_time - iot->dispatch_time;
 
        if (per_process_stats) {
-               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               struct per_process_info *ppi = find_ppi(iot->ppm->pid);
                int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
 
                if (ppi && elapsed > ppi->longest_completion_wait[w])
@@ -490,106 +1154,36 @@ static unsigned long long log_track_complete(struct blk_io_trace *t)
        /*
         * kill the trace, we don't need it after completion
         */
-       rb_erase(&iot->rb_node, &rb_track_root);
+       rb_erase(&iot->rb_node, &pdi->rb_track);
        free(iot);
 
        return elapsed;
 }
 
 
-static struct io_stats *find_process_io_stats(__u32 pid, char *name)
+static struct io_stats *find_process_io_stats(pid_t pid)
 {
-       struct per_process_info *ppi = find_process_by_pid(pid);
+       struct per_process_info *ppi = find_ppi(pid);
 
        if (!ppi) {
                ppi = malloc(sizeof(*ppi));
                memset(ppi, 0, sizeof(*ppi));
-               strncpy(ppi->name, name, sizeof(ppi->name));
-               ppi->pid = pid;
-               add_process_to_hash(ppi);
-               add_process_to_list(ppi);
+               ppi->ppm = find_ppm(pid);
+               if (!ppi->ppm)
+                       ppi->ppm = add_ppm_hash(pid, "unknown");
+               add_ppi_to_hash(ppi);
+               add_ppi_to_list(ppi);
        }
 
        return &ppi->io_stats;
 }
 
-
-static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
-{
-       struct per_cpu_info *cpus = pdi->cpus;
-       int ncpus = pdi->ncpus;
-       int new_count = cpu + 1;
-       int new_space, size;
-       char *new_start;
-
-       size = new_count * sizeof(struct per_cpu_info);
-       cpus = realloc(cpus, size);
-       if (!cpus) {
-               char name[20];
-               fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
-                       get_dev_name(pdi, name, sizeof(name)), size);
-               exit(1);
-       }
-
-       new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
-       new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
-       memset(new_start, 0, new_space);
-
-       pdi->ncpus = new_count;
-       pdi->cpus = cpus;
-}
-
-static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
-{
-       struct per_cpu_info *pci;
-
-       if (cpu >= pdi->ncpus)
-               resize_cpu_info(pdi, cpu);
-
-       pci = &pdi->cpus[cpu];
-       pci->cpu = cpu;
-       return pci;
-}
-
-
-static int resize_devices(char *name)
-{
-       int size = (ndevices + 1) * sizeof(struct per_dev_info);
-
-       devices = realloc(devices, size);
-       if (!devices) {
-               fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
-               return 1;
-       }
-       memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
-       devices[ndevices].name = name;
-       ndevices++;
-       return 0;
-}
-
-static struct per_dev_info *get_dev_info(dev_t id)
-{
-       struct per_dev_info *pdi;
-       int i;
-
-       for (i = 0; i < ndevices; i++)
-               if (devices[i].id == id)
-                       return &devices[i];
-
-       if (resize_devices(NULL) != 0)
-               return NULL;
-
-       pdi = &devices[ndevices - 1];
-       pdi->id = id;
-       return pdi;
-}
-
 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
 {
        if (pdi->name)
                snprintf(buffer, size, "%s", pdi->name);
        else
-               snprintf(buffer, size, "%d,%d", MAJOR(pdi->id), MINOR(pdi->id));
+               snprintf(buffer, size, "%d,%d",MAJOR(pdi->dev),MINOR(pdi->dev));
        return buffer;
 }
 
@@ -607,10 +1201,12 @@ static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
 {
        if (rw) {
                ios->mwrites++;
-               ios->qwrite_kb += t->bytes >> 10;
+               ios->mwrite_kb += t_kb(t);
+               ios->mwrite_b += t_b(t);
        } else {
                ios->mreads++;
-               ios->qread_kb += t->bytes >> 10;
+               ios->mread_kb += t_kb(t);
+               ios->mread_b += t_b(t);
        }
 }
 
@@ -620,413 +1216,262 @@ static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
        __account_m(&pci->io_stats, t, rw);
 
        if (per_process_stats) {
-               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
                __account_m(ios, t, rw);
        }
 }
 
-static inline void __account_q(struct io_stats *ios, struct blk_io_trace *t,
-                              int rw)
+static inline void __account_pc_queue(struct io_stats *ios,
+                                     struct blk_io_trace *t, int rw)
 {
        if (rw) {
-               ios->qwrites++;
-               ios->qwrite_kb += t->bytes >> 10;
+               ios->qwrites_pc++;
+               ios->qwrite_kb_pc += t_kb(t);
+               ios->qwrite_b_pc += t_b(t);
        } else {
-               ios->qreads++;
-               ios->qread_kb += t->bytes >> 10;
+               ios->qreads_pc++;
+               ios->qread_kb += t_kb(t);
+               ios->qread_b_pc += t_b(t);
        }
 }
 
-static inline void account_q(struct blk_io_trace *t, struct per_cpu_info *pci,
-                            int rw)
+static inline void account_pc_queue(struct blk_io_trace *t,
+                                   struct per_cpu_info *pci, int rw)
 {
-       __account_q(&pci->io_stats, t, rw);
+       __account_pc_queue(&pci->io_stats, t, rw);
 
        if (per_process_stats) {
-               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-               __account_q(ios, t, rw);
+               __account_pc_queue(ios, t, rw);
        }
 }
 
-static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
+static inline void __account_pc_issue(struct io_stats *ios, int rw,
+                                     unsigned int bytes)
 {
        if (rw) {
-               ios->cwrites++;
-               ios->cwrite_kb += bytes >> 10;
+               ios->iwrites_pc++;
+               ios->iwrite_kb_pc += bytes >> 10;
+               ios->iwrite_b_pc += bytes & 1023;
        } else {
-               ios->creads++;
-               ios->cread_kb += bytes >> 10;
+               ios->ireads_pc++;
+               ios->iread_kb_pc += bytes >> 10;
+               ios->iread_b_pc += bytes & 1023;
        }
 }
 
-static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
-                            int rw, int bytes)
+static inline void account_pc_issue(struct blk_io_trace *t,
+                                   struct per_cpu_info *pci, int rw)
 {
-       __account_c(&pci->io_stats, rw, bytes);
+       __account_pc_issue(&pci->io_stats, rw, t->bytes);
 
        if (per_process_stats) {
-               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-               __account_c(ios, rw, bytes);
+               __account_pc_issue(ios, rw, t->bytes);
        }
 }
 
-static inline void __account_i(struct io_stats *ios, int rw, unsigned int bytes)
+static inline void __account_pc_requeue(struct io_stats *ios,
+                                       struct blk_io_trace *t, int rw)
 {
        if (rw) {
-               ios->iwrites++;
-               ios->iwrite_kb += bytes >> 10;
+               ios->wrqueue_pc++;
+               ios->iwrite_kb_pc -= t_kb(t);
+               ios->iwrite_b_pc -= t_b(t);
        } else {
-               ios->ireads++;
-               ios->iread_kb += bytes >> 10;
+               ios->rrqueue_pc++;
+               ios->iread_kb_pc -= t_kb(t);
+               ios->iread_b_pc -= t_b(t);
        }
 }
 
-static inline void account_i(struct blk_io_trace *t, struct per_cpu_info *pci,
-                            int rw)
+static inline void account_pc_requeue(struct blk_io_trace *t,
+                                     struct per_cpu_info *pci, int rw)
 {
-       __account_i(&pci->io_stats, rw, t->bytes);
+       __account_pc_requeue(&pci->io_stats, t, rw);
 
        if (per_process_stats) {
-               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-               __account_i(ios, rw, t->bytes);
+               __account_pc_requeue(ios, t, rw);
        }
 }
 
-static inline void __account_unplug(struct io_stats *ios, int timer)
+static inline void __account_pc_c(struct io_stats *ios, int rw)
 {
-       if (timer)
-               ios->timer_unplugs++;
+       if (rw)
+               ios->cwrites_pc++;
        else
-               ios->io_unplugs++;
+               ios->creads_pc++;
 }
 
-static inline void account_unplug(struct blk_io_trace *t,
-                                 struct per_cpu_info *pci, int timer)
+static inline void account_pc_c(struct blk_io_trace *t,
+                               struct per_cpu_info *pci, int rw)
 {
-       __account_unplug(&pci->io_stats, timer);
+       __account_pc_c(&pci->io_stats, rw);
 
        if (per_process_stats) {
-               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-               __account_unplug(ios, timer);
+               __account_pc_c(ios, rw);
        }
 }
 
-#define VALID_SPECS    "BCDFGMPQRSTU"
-static char *override_format[256];
-static inline int valid_spec(int spec)
+static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
+                                  int rw)
 {
-       return strchr(VALID_SPECS, spec) != NULL;
+       if (rw) {
+               ios->qwrites++;
+               ios->qwrite_kb += t_kb(t);
+               ios->qwrite_b += t_b(t);
+       } else {
+               ios->qreads++;
+               ios->qread_kb += t_kb(t);
+               ios->qread_b += t_b(t);
+       }
 }
 
-static void set_all_format_specs(char *optarg)
+static inline void account_queue(struct blk_io_trace *t,
+                                struct per_cpu_info *pci, int rw)
 {
-       char *p;
+       __account_queue(&pci->io_stats, t, rw);
+
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-       for (p = VALID_SPECS; *p; p++)
-               if (override_format[(int)(*p)] == NULL)
-                       override_format[(int)(*p)] = strdup(optarg);
+               __account_queue(ios, t, rw);
+       }
 }
 
-static int add_format_spec(char *optarg)
+static inline void __account_c(struct io_stats *ios, int rw, int bytes)
 {
-       int spec = optarg[0];
-
-       if (!valid_spec(spec)) {
-               fprintf(stderr,"Bad format specifier %c\n", spec);
-               return 1;
-       }
-       if (optarg[1] != ',') {
-               fprintf(stderr,"Bad format specifier - need ',' %s\n", optarg);
-               return 1;
-       }
-       optarg += 2;
-       if (*optarg == '\0') {
-               fprintf(stderr,"Bad format specifier - need fmt %s\n", optarg);
-               return 1;
+       if (rw) {
+               ios->cwrites++;
+               ios->cwrite_kb += bytes >> 10;
+               ios->cwrite_b += bytes & 1023;
+       } else {
+               ios->creads++;
+               ios->cread_kb += bytes >> 10;
+               ios->cread_b += bytes & 1023;
        }
-
-       /*
-        * Set both merges (front and back)
-        */
-       if (spec == 'M') {
-               override_format['B'] = strdup(optarg);
-               override_format['M'] = strdup(optarg);
-       } else
-               override_format[spec] = strdup(optarg);
-
-       return 0;
 }
 
-static void print_field(char *act, struct per_cpu_info *pci,
-                       struct blk_io_trace *t, unsigned long long elapsed,
-                       int pdu_len, unsigned char *pdu_buf, char field,
-                       int minus, int has_w, int width)
+static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
+                            int rw, int bytes)
 {
-       char format[64];
+       __account_c(&pci->io_stats, rw, bytes);
 
-       if (has_w) {
-               if (minus)
-                       sprintf(format, "%%-%d", width);
-               else
-                       sprintf(format, "%%%d", width);
-       } else
-               sprintf(format, "%%");
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-       switch (field) {
-       case 'a':
-               fprintf(ofp, strcat(format, "s"), act);
-               break;
-       case 'c':
-               fprintf(ofp, strcat(format, "d"), pci->cpu);
-               break;
-       case 'C':
-               fprintf(ofp, strcat(format, "s"), t->comm);
-               break;
-       case 'd': {
-               char rwbs[4];
-               int i = 0;
-               int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
-               int b = t->action & BLK_TC_ACT(BLK_TC_BARRIER);
-               int s = t->action & BLK_TC_ACT(BLK_TC_SYNC);
-               if (w)
-                       rwbs[i++] = 'W';
-               else
-                       rwbs[i++] = 'R';
-               if (b)
-                       rwbs[i++] = 'B';
-               if (s)
-                       rwbs[i++] = 'S';
-               rwbs[i] = '\0';
-               fprintf(ofp, strcat(format, "s"), rwbs);
-               break;
-       }
-       case 'D':       /* format width ignored */
-               fprintf(ofp,"%3d,%-3d", MAJOR(t->device), MINOR(t->device));
-               break;
-       case 'e':
-               fprintf(ofp, strcat(format, "d"), t->error);
-               break;
-       case 'M':
-               fprintf(ofp, strcat(format, "d"), MAJOR(t->device));
-               break;
-       case 'm':
-               fprintf(ofp, strcat(format, "d"), MINOR(t->device));
-               break;
-       case 'n':
-               fprintf(ofp, strcat(format, "u"), t->bytes >> 9);
-               break;
-       case 'p':
-               fprintf(ofp, strcat(format, "u"), t->pid);
-               break;
-       case 'P':       /* format width ignored */
-               if ((pdu_len > 0) && (pdu_buf != NULL)) {
-                       int i;
-                       unsigned char *p = pdu_buf;
-                       for (i = 0; i < pdu_len; i++)
-                               fprintf(ofp, "%02x ", *p++);
-               }
-               break;
-       case 's':
-               fprintf(ofp, strcat(format, "ld"), t->sequence);
-               break;
-       case 'S':
-               fprintf(ofp, strcat(format, "lu"), t->sector);
-               break;
-       case 't':
-               sprintf(format, "%%0%dlu", has_w ? width : 9);
-               fprintf(ofp, format, NANO_SECONDS(t->time));
-               break;
-       case 'T':
-               fprintf(ofp, strcat(format, "d"), SECONDS(t->time));
-               break;
-       case 'u':
-               if (elapsed == -1ULL) {
-                       fprintf(stderr, "Expecting elapsed value\n");
-                       exit(1);
-               }
-               fprintf(ofp, strcat(format, "llu"), elapsed / 1000);
-               break;
-       case 'U': {
-               __u64 *depth = (__u64 *) ((char *) t + sizeof(*t));
-               fprintf(ofp, strcat(format, "u"),
-                                       (unsigned int) be64_to_cpu(*depth));
-               break;
-       }
-       default:
-               fprintf(ofp,strcat(format, "c"), field);
-               break;
+               __account_c(ios, rw, bytes);
        }
 }
 
-static char *parse_field(char *act, struct per_cpu_info *pci, 
-                        struct blk_io_trace *t, unsigned long long elapsed, 
-                        int pdu_len, unsigned char *pdu_buf, 
-                        char *master_format)
+static inline void __account_issue(struct io_stats *ios, int rw,
+                                  unsigned int bytes)
 {
-       int minus = 0;
-       int has_w = 0;
-       int width = 0;
-       char *p = master_format;
-
-       if (*p == '-') {
-               minus = 1;
-               p++;
-       }
-       if (isdigit(*p)) {
-               has_w = 1;
-               do {
-                       width = (width * 10) + (*p++ - '0');
-               } while ((*p) && (isdigit(*p)));
-       }
-       if (*p) {
-               print_field(act, pci, t, elapsed, pdu_len, pdu_buf, *p++,
-                           minus, has_w, width);
+       if (rw) {
+               ios->iwrites++;
+               ios->iwrite_kb += bytes >> 10;
+               ios->iwrite_b  += bytes & 1023;
+       } else {
+               ios->ireads++;
+               ios->iread_kb += bytes >> 10;
+               ios->iread_b  += bytes & 1023;
        }
-       return p;
 }
 
-static char *fmt_select(int fmt_spec, struct blk_io_trace *t,
-                       unsigned long long elapsed)
+static inline void account_issue(struct blk_io_trace *t,
+                                struct per_cpu_info *pci, int rw)
 {
-       char *fmt;
-       char scratch_format[1024];
-
-       if (override_format[fmt_spec] != NULL)
-               return override_format[fmt_spec];
-
-       switch (fmt_spec) {
-       case 'C':       /* Complete */
-               if (t->action & BLK_TC_ACT(BLK_TC_PC)) {
-                       strcpy(scratch_format, HEADER);
-                       strcat(scratch_format, "%P");
-               } else {
-                       strcpy(scratch_format, HEADER "%S + %n ");
-                       if (elapsed != -1ULL)
-                               strcat(scratch_format, "(%8u) ");
-               }
-               strcat(scratch_format, "[%e]\n");
-               fmt = scratch_format;
-               break;
-
-       case 'D':       /* Issue */
-               if (t->action & BLK_TC_ACT(BLK_TC_PC)) {
-                       strcpy(scratch_format, HEADER);
-                       strcat(scratch_format, "%P");
-               } else {
-                       strcpy(scratch_format, HEADER "%S + %n ");
-                       if (elapsed != -1ULL)
-                               strcat(scratch_format, "(%8u) ");
-               }
-               strcat(scratch_format,"[%C]\n");
-               fmt = scratch_format;
-               break;
+       __account_issue(&pci->io_stats, rw, t->bytes);
 
-       case 'Q':       /* Queue */
-               strcpy(scratch_format, HEADER "%S + %n ");
-               if (elapsed != -1ULL)
-                       strcat(scratch_format, "(%8u) ");
-               strcat(scratch_format,"[%C]\n");
-               fmt = scratch_format;
-               break;
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-       case 'B':       /* Back merge */
-       case 'F':       /* Front merge */
-       case 'M':       /* Front or back merge */
-               fmt = HEADER "%S + %n [%C]\n";
-               break;
+               __account_issue(ios, rw, t->bytes);
+       }
+}
 
-       case 'P':       /* Plug */
-               fmt = HEADER "[%C]\n";
-               break;
+static inline void __account_unplug(struct io_stats *ios, int timer)
+{
+       if (timer)
+               ios->timer_unplugs++;
+       else
+               ios->io_unplugs++;
+}
 
-       case 'G':       /* Get request */
-       case 'S':       /* Sleep request */
-               fmt = HEADER "%S + %n [%C]\n";
-               break;
+static inline void account_unplug(struct blk_io_trace *t,
+                                 struct per_cpu_info *pci, int timer)
+{
+       __account_unplug(&pci->io_stats, timer);
 
-       case 'U':       /* Unplug IO */
-       case 'T':       /* Unplug timer */
-               fmt = HEADER "[%C] %U\n";
-               break;
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid);
 
-       default:
-               fprintf(stderr,"FATAL: Invalid format spec %c\n", fmt_spec);
-               exit(1);
-               /*NOTREACHED*/
+               __account_unplug(ios, timer);
        }
+}
 
-       return fmt;
+static inline void __account_requeue(struct io_stats *ios,
+                                    struct blk_io_trace *t, int rw)
+{
+       if (rw) {
+               ios->wrqueue++;
+               ios->iwrite_kb -= t_kb(t);
+               ios->iwrite_b -= t_b(t);
+       } else {
+               ios->rrqueue++;
+               ios->iread_kb -= t_kb(t);
+               ios->iread_b -= t_b(t);
+       }
 }
 
-static void process_fmt(char *act, struct per_cpu_info *pci,
-                          struct blk_io_trace *t, unsigned long long elapsed,
-                          int pdu_len, unsigned char *pdu_buf)
+static inline void account_requeue(struct blk_io_trace *t,
+                                  struct per_cpu_info *pci, int rw)
 {
-       char *p = fmt_select(act[0], t, elapsed);
+       __account_requeue(&pci->io_stats, t, rw);
 
-       while (*p) {
-               switch (*p) {
-               case '%':       /* Field specifier */
-                       p++;
-                       if (*p == '%')
-                               fprintf(ofp, "%c", *p++);
-                       else if (!*p)
-                               fprintf(ofp, "%c", '%');
-                       else
-                               p = parse_field(act, pci, t, elapsed,
-                                               pdu_len, pdu_buf, p);
-                       break;
-               case '\\': {    /* escape */
-                       switch (p[1]) {
-                       case 'b': fprintf(ofp, "\b"); break;
-                       case 'n': fprintf(ofp, "\n"); break;
-                       case 'r': fprintf(ofp, "\r"); break;
-                       case 't': fprintf(ofp, "\t"); break;
-                       default:
-                               fprintf(stderr, 
-                                       "Invalid escape char in format %c\n",
-                                       p[1]);
-                               exit(1);
-                               /*NOTREACHED*/
-                       }
-                       p += 2;
-                       break;
-               }
-               default:
-                       fprintf(ofp, "%c", *p++);
-                       break;
-               }
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid);
+
+               __account_requeue(ios, t, rw);
        }
 }
 
-static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
-                        char *act)
+static void log_complete(struct per_dev_info *pdi, struct per_cpu_info *pci,
+                        struct blk_io_trace *t, char *act)
 {
-       process_fmt(act, pci, t, log_track_complete(t), 0, NULL);
+       process_fmt(act, pci, t, log_track_complete(pdi, t), 0, NULL);
+}
+
+static void log_insert(struct per_dev_info *pdi, struct per_cpu_info *pci,
+                      struct blk_io_trace *t, char *act)
+{
+       process_fmt(act, pci, t, log_track_insert(pdi, t), 0, NULL);
 }
 
 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
                      char *act)
 {
-       process_fmt(act, pci, t, log_track_queue(t), 0, NULL);
+       process_fmt(act, pci, t, -1, 0, NULL);
 }
 
-static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
-                     char *act)
+static void log_issue(struct per_dev_info *pdi, struct per_cpu_info *pci,
+                     struct blk_io_trace *t, char *act)
 {
-       process_fmt(act, pci, t, log_track_issue(t), 0, NULL);
+       process_fmt(act, pci, t, log_track_issue(pdi, t), 0, NULL);
 }
 
-static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
-                     char *act)
+static void log_merge(struct per_dev_info *pdi, struct per_cpu_info *pci,
+                     struct blk_io_trace *t, char *act)
 {
        if (act[0] == 'F')
-               log_track_frontmerge(t);
+               log_track_frontmerge(pdi, t);
 
        process_fmt(act, pci, t, -1ULL, 0, NULL);
 }
@@ -1049,6 +1494,12 @@ static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
        process_fmt(act, pci, t, -1ULL, 0, NULL);
 }
 
+static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
+                     char *act)
+{
+       process_fmt(act, pci, t, -1ULL, 0, NULL);
+}
+
 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
 {
        unsigned char *buf = (unsigned char *) t + sizeof(*t);
@@ -1056,13 +1507,16 @@ static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
        process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
 }
 
-static int dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
+static void dump_trace_pc(struct blk_io_trace *t, struct per_dev_info *pdi,
+                         struct per_cpu_info *pci)
 {
-       int ret = 0;
+       int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
+       int act = t->action & 0xffff;
 
-       switch (t->action & 0xffff) {
+       switch (act) {
                case __BLK_TA_QUEUE:
                        log_generic(pci, t, "Q");
+                       account_pc_queue(t, pci, w);
                        break;
                case __BLK_TA_GETRQ:
                        log_generic(pci, t, "G");
@@ -1071,59 +1525,89 @@ static int dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
                        log_generic(pci, t, "S");
                        break;
                case __BLK_TA_REQUEUE:
+                       /*
+                        * can happen if we miss traces, don't let it go
+                        * below zero
+                        */
+                       if (pdi->cur_depth[w])
+                               pdi->cur_depth[w]--;
+                       account_pc_requeue(t, pci, w);
                        log_generic(pci, t, "R");
                        break;
                case __BLK_TA_ISSUE:
+                       account_pc_issue(t, pci, w);
+                       pdi->cur_depth[w]++;
+                       if (pdi->cur_depth[w] > pdi->max_depth[w])
+                               pdi->max_depth[w] = pdi->cur_depth[w];
                        log_pc(pci, t, "D");
                        break;
                case __BLK_TA_COMPLETE:
+                       if (pdi->cur_depth[w])
+                               pdi->cur_depth[w]--;
                        log_pc(pci, t, "C");
+                       account_pc_c(t, pci, w);
+                       break;
+               case __BLK_TA_INSERT:
+                       log_pc(pci, t, "I");
                        break;
                default:
-                       fprintf(stderr, "Bad pc action %x\n", t->action);
-                       ret = 1;
+                       fprintf(stderr, "Bad pc action %x\n", act);
                        break;
        }
-       
-       return 0;
 }
 
-static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
+static void dump_trace_fs(struct blk_io_trace *t, struct per_dev_info *pdi,
+                         struct per_cpu_info *pci)
 {
-       int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
+       int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
        int act = t->action & 0xffff;
 
        switch (act) {
                case __BLK_TA_QUEUE:
-                       account_q(t, pci, w);
+                       log_track_queue(pdi, t);
+                       account_queue(t, pci, w);
                        log_queue(pci, t, "Q");
                        break;
+               case __BLK_TA_INSERT:
+                       log_insert(pdi, pci, t, "I");
+                       break;
                case __BLK_TA_BACKMERGE:
                        account_m(t, pci, w);
-                       log_merge(pci, t, "M");
+                       log_merge(pdi, pci, t, "M");
                        break;
                case __BLK_TA_FRONTMERGE:
                        account_m(t, pci, w);
-                       log_merge(pci, t, "F");
+                       log_merge(pdi, pci, t, "F");
                        break;
                case __BLK_TA_GETRQ:
-                       log_track_getrq(t);
+                       log_track_getrq(pdi, t);
                        log_generic(pci, t, "G");
                        break;
                case __BLK_TA_SLEEPRQ:
                        log_generic(pci, t, "S");
                        break;
                case __BLK_TA_REQUEUE:
-                       account_c(t, pci, w, -t->bytes);
+                       /*
+                        * can happen if we miss traces, don't let it go
+                        * below zero
+                        */
+                       if (pdi->cur_depth[w])
+                               pdi->cur_depth[w]--;
+                       account_requeue(t, pci, w);
                        log_queue(pci, t, "R");
                        break;
                case __BLK_TA_ISSUE:
-                       account_i(t, pci, w);
-                       log_issue(pci, t, "D");
+                       account_issue(t, pci, w);
+                       pdi->cur_depth[w]++;
+                       if (pdi->cur_depth[w] > pdi->max_depth[w])
+                               pdi->max_depth[w] = pdi->cur_depth[w];
+                       log_issue(pdi, pci, t, "D");
                        break;
                case __BLK_TA_COMPLETE:
+                       if (pdi->cur_depth[w])
+                               pdi->cur_depth[w]--;
                        account_c(t, pci, w, t->bytes);
-                       log_complete(pci, t, "C");
+                       log_complete(pdi, pci, t, "C");
                        break;
                case __BLK_TA_PLUG:
                        log_action(pci, t, "P");
@@ -1136,39 +1620,130 @@ static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
                        account_unplug(t, pci, 1);
                        log_unplug(pci, t, "UT");
                        break;
+               case __BLK_TA_SPLIT:
+                       log_split(pci, t, "X");
+                       break;
+               case __BLK_TA_BOUNCE:
+                       log_generic(pci, t, "B");
+                       break;
+               case __BLK_TA_REMAP:
+                       log_generic(pci, t, "A");
+                       break;
+               case __BLK_TA_DRV_DATA:
+                       have_drv_data = 1;
+                       /* dump to binary file only */
+                       break;
                default:
                        fprintf(stderr, "Bad fs action %x\n", t->action);
                        break;
        }
 }
 
-static int dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
-                       struct per_dev_info *pdi)
+static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
+                      struct per_dev_info *pdi)
 {
-       int ret = 0;
+       if (text_output) {
+               if (t->action == BLK_TN_MESSAGE)
+                       handle_notify(t);
+               else if (t->action & BLK_TC_ACT(BLK_TC_PC))
+                       dump_trace_pc(t, pdi, pci);
+               else
+                       dump_trace_fs(t, pdi, pci);
+       }
 
-       if (t->action & BLK_TC_ACT(BLK_TC_PC))
-               ret = dump_trace_pc(t, pci);
-       else
-               dump_trace_fs(t, pci);
+       if (!pdi->events)
+               pdi->first_reported_time = t->time;
+
+       pdi->events++;
+
+       if (bin_output_msgs ||
+                           !(t->action & BLK_TC_ACT(BLK_TC_NOTIFY) &&
+                             t->action == BLK_TN_MESSAGE))
+               output_binary(t, sizeof(*t) + t->pdu_len);
+}
+
+/*
+ * print in a proper way, not too small and not too big. if more than
+ * 1000,000K, turn into M and so on
+ */
+static char *size_cnv(char *dst, unsigned long long num, int in_kb)
+{
+       char suff[] = { '\0', 'K', 'M', 'G', 'P' };
+       unsigned int i = 0;
+
+       if (in_kb)
+               i++;
+
+       while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
+               i++;
+               num /= 1000;
+       }
 
-       pdi->events++;
-       return ret;
+       sprintf(dst, "%'8Lu%c", num, suff[i]);
+       return dst;
 }
 
-static void dump_io_stats(struct io_stats *ios, char *msg)
+static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
+                         char *msg)
 {
-       fprintf(ofp, "%s\n", msg);
+       static char x[256], y[256];
 
-       fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
-       fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
+       fprintf(ofp, "%s\n", msg);
 
-       fprintf(ofp, " Read Dispatches: %'8lu, %'8LuKiB\t", ios->ireads, ios->iread_kb);
-       fprintf(ofp, " Write Dispatches: %'8lu, %'8LuKiB\n", ios->iwrites,ios->iwrite_kb);
-       fprintf(ofp, " Reads Completed: %'8lu, %'8LuKiB\t", ios->creads, ios->cread_kb);
-       fprintf(ofp, " Writes Completed: %'8lu, %'8LuKiB\n", ios->cwrites,ios->cwrite_kb);
-       fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
-       fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
+       fprintf(ofp, " Reads Queued:    %s, %siB\t",
+                       size_cnv(x, ios->qreads, 0),
+                       size_cnv(y, ios->qread_kb + (ios->qread_b>>10), 1));
+       fprintf(ofp, " Writes Queued:    %s, %siB\n",
+                       size_cnv(x, ios->qwrites, 0),
+                       size_cnv(y, ios->qwrite_kb + (ios->qwrite_b>>10), 1));
+       fprintf(ofp, " Read Dispatches: %s, %siB\t",
+                       size_cnv(x, ios->ireads, 0),
+                       size_cnv(y, ios->iread_kb + (ios->iread_b>>10), 1));
+       fprintf(ofp, " Write Dispatches: %s, %siB\n",
+                       size_cnv(x, ios->iwrites, 0),
+                       size_cnv(y, ios->iwrite_kb + (ios->iwrite_b>>10), 1));
+       fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
+       fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
+       fprintf(ofp, " Reads Completed: %s, %siB\t",
+                       size_cnv(x, ios->creads, 0),
+                       size_cnv(y, ios->cread_kb + (ios->cread_b>>10), 1));
+       fprintf(ofp, " Writes Completed: %s, %siB\n",
+                       size_cnv(x, ios->cwrites, 0),
+                       size_cnv(y, ios->cwrite_kb + (ios->cwrite_b>>10), 1));
+       fprintf(ofp, " Read Merges:     %s, %siB\t",
+                       size_cnv(x, ios->mreads, 0),
+                       size_cnv(y, ios->mread_kb + (ios->mread_b>>10), 1));
+       fprintf(ofp, " Write Merges:     %s, %siB\n",
+                       size_cnv(x, ios->mwrites, 0),
+                       size_cnv(y, ios->mwrite_kb + (ios->mwrite_b>>10), 1));
+       if (pdi) {
+               fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
+               fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
+       }
+       if (ios->qreads_pc || ios->qwrites_pc || ios->ireads_pc || ios->iwrites_pc ||
+           ios->rrqueue_pc || ios->wrqueue_pc || ios->creads_pc || ios->cwrites_pc) {
+               fprintf(ofp, " PC Reads Queued: %s, %siB\t",
+                       size_cnv(x, ios->qreads_pc, 0),
+                       size_cnv(y,
+                               ios->qread_kb_pc + (ios->qread_b_pc>>10), 1));
+               fprintf(ofp, " PC Writes Queued: %s, %siB\n",
+                       size_cnv(x, ios->qwrites_pc, 0),
+                       size_cnv(y,
+                               ios->qwrite_kb_pc + (ios->qwrite_b_pc>>10), 1));
+               fprintf(ofp, " PC Read Disp.:   %s, %siB\t",
+                       size_cnv(x, ios->ireads_pc, 0),
+                       size_cnv(y,
+                               ios->iread_kb_pc + (ios->iread_b_pc>>10), 1));
+               fprintf(ofp, " PC Write Disp.:   %s, %siB\n",
+                       size_cnv(x, ios->iwrites_pc, 0),
+                       size_cnv(y,
+                               ios->iwrite_kb_pc + (ios->iwrite_b_pc>>10),
+                               1));
+               fprintf(ofp, " PC Reads Req.:   %s\t\t", size_cnv(x, ios->rrqueue_pc, 0));
+               fprintf(ofp, " PC Writes Req.:   %s\n", size_cnv(x, ios->wrqueue_pc, 0));
+               fprintf(ofp, " PC Reads Compl.: %s\t\t", size_cnv(x, ios->creads_pc, 0));
+               fprintf(ofp, " PC Writes Compl.: %s\n", size_cnv(x, ios->cwrites_pc, 0));
+       }
        fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
        fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
 }
@@ -1196,13 +1771,95 @@ static int ppi_name_compare(const void *p1, const void *p2)
        struct per_process_info *ppi2 = *((struct per_process_info **) p2);
        int res;
 
-       res = strverscmp(ppi1->name, ppi2->name);
+       res = strverscmp(ppi1->ppm->comm, ppi2->ppm->comm);
        if (!res)
-               res = ppi1->pid < ppi2->pid;
+               res = ppi1->ppm->pid > ppi2->ppm->pid;
 
        return res;
 }
 
+static int ppi_event_compare(const void *p1, const void *p2)
+{
+       struct per_process_info *ppi1 = *((struct per_process_info **) p1);
+       struct per_process_info *ppi2 = *((struct per_process_info **) p2);
+       struct io_stats *ios1 = &ppi1->io_stats;
+       struct io_stats *ios2 = &ppi2->io_stats;
+       unsigned long io1, io2;
+       unsigned long long kb1,kb2;
+       int sort_by_kb = 1;
+
+       io1 = io2 = 0;
+       kb1 = kb2 = 0;
+
+       switch (per_process_stats_event) {
+       case SORT_PROG_EVENT_QKB: /* KB: Queued read and write */
+               kb1 = ios1->qwrite_kb + (ios1->qwrite_b>>10) +
+                       ios1->qread_kb + (ios1->qread_b>>10);
+               kb2 = ios2->qwrite_kb + (ios2->qwrite_b>>10) +
+                       ios2->qread_kb + (ios2->qread_b>>10);
+               break;
+       case SORT_PROG_EVENT_RKB: /* KB: Queued Read */
+               kb1 = ios1->qread_kb + (ios1->qread_b>>10);
+               kb2 = ios2->qread_kb + (ios2->qread_b>>10);
+               break;
+       case SORT_PROG_EVENT_WKB: /* KB: Queued Write */
+               kb1 = ios1->qwrite_kb + (ios1->qwrite_b>>10);
+               kb2 = ios2->qwrite_kb + (ios2->qwrite_b>>10);
+               break;
+       case SORT_PROG_EVENT_CKB: /* KB: Complete */
+               kb1 = ios1->cwrite_kb + (ios1->cwrite_b>>10) +
+                       ios1->cread_kb + (ios1->cread_b>>10);
+               kb2 = ios2->cwrite_kb + (ios2->cwrite_b>>10) +
+                       ios2->cread_kb + (ios2->cread_b>>10);
+               break;
+       case SORT_PROG_EVENT_QIO: /* IO: Queued read and write */
+               sort_by_kb = 0;
+               io1 = ios1->qreads + ios1->qwrites;
+               io2 = ios2->qreads + ios2->qwrites;
+               break;
+       case SORT_PROG_EVENT_RIO: /* IO: Queued Read */
+               sort_by_kb = 0;
+               io1 = ios1->qreads;
+               io2 = ios2->qreads;
+               break;
+       case SORT_PROG_EVENT_WIO: /* IO: Queued Write */
+               sort_by_kb = 0;
+               io1 = ios1->qwrites;
+               io2 = ios2->qwrites;
+               break;
+       case SORT_PROG_EVENT_CIO: /* IO: Complete */
+               sort_by_kb = 0;
+               io1 = ios1->creads + ios1->cwrites;
+               io2 = ios2->creads + ios2->cwrites;
+               break;
+       }
+
+
+       /* compare kb */
+       if (sort_by_kb) {
+               if (kb1 > kb2)
+                       return 1;
+               else if (kb1 == kb2)
+                       return 0;
+               return -1;
+       }
+
+       /* compare io */
+       if (io1 > io2)
+               return 1;
+       else if (io1 == io2)
+               return 0;
+       return -1;
+}
+
+static int ppi_compare(const void *p1, const void *p2)
+{
+       if (per_process_stats_event == SORT_PROG_EVENT_N)
+               return ppi_name_compare(p1, p2);
+
+       return ppi_event_compare(p1, p2);
+}
+
 static void sort_process_list(void)
 {
        struct per_process_info **ppis;
@@ -1213,11 +1870,11 @@ static void sort_process_list(void)
 
        ppi = ppi_list;
        while (ppi) {
-               ppis[i] = ppi;
+               ppis[i++] = ppi;
                ppi = ppi->list_next;
        }
 
-       qsort(ppis, ppi_list_entries, sizeof(*ppi), ppi_name_compare);
+       qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_compare);
 
        i = ppi_list_entries - 1;
        ppi_list = NULL;
@@ -1228,6 +1885,8 @@ static void sort_process_list(void)
                ppi_list = ppi;
                i--;
        }
+
+       free(ppis);
 }
 
 static void show_process_stats(void)
@@ -1238,7 +1897,15 @@ static void show_process_stats(void)
 
        ppi = ppi_list;
        while (ppi) {
-               dump_io_stats(&ppi->io_stats, ppi->name);
+               struct process_pid_map *ppm = ppi->ppm;
+               char name[64];
+
+               if (ppi->more_than_one)
+                       sprintf(name, "%s (%u, ...)", ppm->comm, ppm->pid);
+               else
+                       sprintf(name, "%s (%u)", ppm->comm, ppm->pid);
+
+               dump_io_stats(NULL, &ppi->io_stats, name);
                dump_wait_stats(ppi);
                ppi = ppi->list_next;
        }
@@ -1251,9 +1918,11 @@ static void show_device_and_cpu_stats(void)
        struct per_dev_info *pdi;
        struct per_cpu_info *pci;
        struct io_stats total, *ios;
+       unsigned long long rrate, wrate, msec;
        int i, j, pci_events;
        char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
        char name[32];
+       double ratio;
 
        for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
 
@@ -1276,18 +1945,48 @@ static void show_device_and_cpu_stats(void)
                        total.mwrites += ios->mwrites;
                        total.ireads += ios->ireads;
                        total.iwrites += ios->iwrites;
+                       total.rrqueue += ios->rrqueue;
+                       total.wrqueue += ios->wrqueue;
                        total.qread_kb += ios->qread_kb;
                        total.qwrite_kb += ios->qwrite_kb;
                        total.cread_kb += ios->cread_kb;
                        total.cwrite_kb += ios->cwrite_kb;
                        total.iread_kb += ios->iread_kb;
                        total.iwrite_kb += ios->iwrite_kb;
+                       total.mread_kb += ios->mread_kb;
+                       total.mwrite_kb += ios->mwrite_kb;
+                       total.qread_b += ios->qread_b;
+                       total.qwrite_b += ios->qwrite_b;
+                       total.cread_b += ios->cread_b;
+                       total.cwrite_b += ios->cwrite_b;
+                       total.iread_b += ios->iread_b;
+                       total.iwrite_b += ios->iwrite_b;
+                       total.mread_b += ios->mread_b;
+                       total.mwrite_b += ios->mwrite_b;
+
+                       total.qreads_pc += ios->qreads_pc;
+                       total.qwrites_pc += ios->qwrites_pc;
+                       total.creads_pc += ios->creads_pc;
+                       total.cwrites_pc += ios->cwrites_pc;
+                       total.ireads_pc += ios->ireads_pc;
+                       total.iwrites_pc += ios->iwrites_pc;
+                       total.rrqueue_pc += ios->rrqueue_pc;
+                       total.wrqueue_pc += ios->wrqueue_pc;
+                       total.qread_kb_pc += ios->qread_kb_pc;
+                       total.qwrite_kb_pc += ios->qwrite_kb_pc;
+                       total.iread_kb_pc += ios->iread_kb_pc;
+                       total.iwrite_kb_pc += ios->iwrite_kb_pc;
+                       total.qread_b_pc += ios->qread_b_pc;
+                       total.qwrite_b_pc += ios->qwrite_b_pc;
+                       total.iread_b_pc += ios->iread_b_pc;
+                       total.iwrite_b_pc += ios->iwrite_b_pc;
+
                        total.timer_unplugs += ios->timer_unplugs;
                        total.io_unplugs += ios->io_unplugs;
 
                        snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
                                 j, get_dev_name(pdi, name, sizeof(name)));
-                       dump_io_stats(ios, line);
+                       dump_io_stats(pdi, ios, line);
                        pci_events++;
                }
 
@@ -1295,333 +1994,805 @@ static void show_device_and_cpu_stats(void)
                        fprintf(ofp, "\n");
                        snprintf(line, sizeof(line) - 1, "Total (%s):",
                                 get_dev_name(pdi, name, sizeof(name)));
-                       dump_io_stats(&total, line);
+                       dump_io_stats(NULL, &total, line);
                }
 
-               fprintf(ofp, "\nEvents (%s): %'Lu entries, %'lu skips\n",
-                       get_dev_name(pdi, line, sizeof(line)), pdi->events,
-                       pdi->skips);
+               wrate = rrate = 0;
+               msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
+               if (msec) {
+                       rrate = ((1000 * total.cread_kb) + total.cread_b) /
+                                                                       msec;
+                       wrate = ((1000 * total.cwrite_kb) + total.cwrite_b) /
+                                                                       msec;
+               }
+
+               fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
+                       rrate, wrate);
+               fprintf(ofp, "Events (%s): %'Lu entries\n",
+                       get_dev_name(pdi, line, sizeof(line)), pdi->events);
+
+               collect_pdi_skips(pdi);
+               if (!pdi->skips && !pdi->events)
+                       ratio = 0.0;
+               else
+                       ratio = 100.0 * ((double)pdi->seq_skips /
+                                       (double)(pdi->events + pdi->seq_skips));
+               fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
+                       pdi->skips, pdi->seq_skips, ratio);
+       }
+}
+
+static void correct_abs_start_time(void)
+{
+       long delta = genesis_time - start_timestamp;
+
+       abs_start_time.tv_sec  += SECONDS(delta);
+       abs_start_time.tv_nsec += NANO_SECONDS(delta);
+       if (abs_start_time.tv_nsec < 0) {
+               abs_start_time.tv_nsec += 1000000000;
+               abs_start_time.tv_sec -= 1;
+       } else
+       if (abs_start_time.tv_nsec > 1000000000) {
+               abs_start_time.tv_nsec -= 1000000000;
+               abs_start_time.tv_sec += 1;
        }
 }
 
-static struct blk_io_trace *find_trace(void *p, unsigned long offset)
+static void find_genesis(void)
 {
-       unsigned long max_offset = offset;
-       unsigned long off;
-       struct blk_io_trace *bit;
-       __u32 magic;
+       struct trace *t = trace_list;
 
-       for (off = 0; off < max_offset; off++) {
-               bit = p + off;
+       genesis_time = -1ULL;
+       while (t != NULL) {
+               if (t->bit->time < genesis_time)
+                       genesis_time = t->bit->time;
 
-               magic = be32_to_cpu(bit->magic);
-               if ((magic & 0xffffff00) == BLK_IO_TRACE_MAGIC)
-                       return bit;
+               t = t->next;
        }
 
-       return NULL;
+       /* The time stamp record will usually be the first
+        * record in the trace, but not always.
+        */
+       if (start_timestamp
+        && start_timestamp != genesis_time) {
+               correct_abs_start_time();
+       }
 }
 
-static int sort_entries(void)
+static inline int check_stopwatch(struct blk_io_trace *bit)
 {
-       struct per_dev_info *pdi;
+       if (bit->time < stopwatch_end &&
+           bit->time >= stopwatch_start)
+               return 0;
+
+       return 1;
+}
+
+/*
+ * return youngest entry read
+ */
+static int sort_entries(unsigned long long *youngest)
+{
+       struct per_dev_info *pdi = NULL;
+       struct per_cpu_info *pci = NULL;
+       struct trace *t;
+
+       if (!genesis_time)
+               find_genesis();
+
+       *youngest = 0;
+       while ((t = trace_list) != NULL) {
+               struct blk_io_trace *bit = t->bit;
+
+               trace_list = t->next;
+
+               bit->time -= genesis_time;
+
+               if (bit->time < *youngest || !*youngest)
+                       *youngest = bit->time;
+
+               if (!pdi || pdi->dev != bit->device) {
+                       pdi = get_dev_info(bit->device);
+                       pci = NULL;
+               }
+
+               if (!pci || pci->cpu != bit->cpu)
+                       pci = get_cpu_info(pdi, bit->cpu);
+
+               if (bit->sequence < pci->smallest_seq_read)
+                       pci->smallest_seq_read = bit->sequence;
+
+               if (check_stopwatch(bit)) {
+                       bit_free(bit);
+                       t_free(t);
+                       continue;
+               }
+
+               if (trace_rb_insert_sort(t))
+                       return -1;
+       }
+
+       return 0;
+}
+
+/*
+ * to continue, we must have traces from all online cpus in the tree
+ */
+static int check_cpu_map(struct per_dev_info *pdi)
+{
+       unsigned long *cpu_map;
+       struct rb_node *n;
+       struct trace *__t;
+       unsigned int i;
+       int ret, cpu;
+
+       /*
+        * create a map of the cpus we have traces for
+        */
+       cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
+       memset(cpu_map, 0, sizeof(*cpu_map));
+       n = rb_first(&rb_sort_root);
+       while (n) {
+               __t = rb_entry(n, struct trace, rb_node);
+               cpu = __t->bit->cpu;
+
+               cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
+               n = rb_next(n);
+       }
+
+       /*
+        * we can't continue if pdi->cpu_map has entries set that we don't
+        * have in the sort rbtree. the opposite is not a problem, though
+        */
+       ret = 0;
+       for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
+               if (pdi->cpu_map[i] & ~(cpu_map[i])) {
+                       ret = 1;
+                       break;
+               }
+       }
+
+       free(cpu_map);
+       return ret;
+}
+
+static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
+{
+       struct blk_io_trace *bit = t->bit;
+       unsigned long expected_sequence;
        struct per_cpu_info *pci;
+       struct trace *__t;
+
+       pci = get_cpu_info(pdi, bit->cpu);
+       expected_sequence = pci->last_sequence + 1;
+
+       if (!expected_sequence) {
+               /*
+                * 1 should be the first entry, just allow it
+                */
+               if (bit->sequence == 1)
+                       return 0;
+               if (bit->sequence == pci->smallest_seq_read)
+                       return 0;
+
+               return check_cpu_map(pdi);
+       }
+
+       if (bit->sequence == expected_sequence)
+               return 0;
+
+       /*
+        * we may not have seen that sequence yet. if we are not doing
+        * the final run, break and wait for more entries.
+        */
+       if (expected_sequence < pci->smallest_seq_read) {
+               __t = trace_rb_find_last(pdi, pci, expected_sequence);
+               if (!__t)
+                       goto skip;
+
+               __put_trace_last(pdi, __t);
+               return 0;
+       } else if (!force) {
+               return 1;
+       } else {
+skip:
+               if (check_current_skips(pci, bit->sequence))
+                       return 0;
+
+               if (expected_sequence < bit->sequence)
+                       insert_skip(pci, expected_sequence, bit->sequence - 1);
+               return 0;
+       }
+}
+
+static void show_entries_rb(int force)
+{
+       struct per_dev_info *pdi = NULL;
+       struct per_cpu_info *pci = NULL;
        struct blk_io_trace *bit;
+       struct rb_node *n;
        struct trace *t;
-       int nr = 0;
 
-       while ((t = trace_list) != NULL) {
+       while ((n = rb_first(&rb_sort_root)) != NULL) {
+               if (is_done() && !force && !pipeline)
+                       break;
+
+               t = rb_entry(n, struct trace, rb_node);
+               bit = t->bit;
+
+               if (read_sequence - t->read_sequence < 1 && !force)
+                       break;
+
+               if (!pdi || pdi->dev != bit->device) {
+                       pdi = get_dev_info(bit->device);
+                       pci = NULL;
+               }
+
+               if (!pdi) {
+                       fprintf(stderr, "Unknown device ID? (%d,%d)\n",
+                               MAJOR(bit->device), MINOR(bit->device));
+                       break;
+               }
+
+               if (!(bit->action == BLK_TN_MESSAGE) &&
+                   check_sequence(pdi, t, force))
+                       break;
+
+               if (!force && bit->time > last_allowed_time)
+                       break;
+
+               check_time(pdi, bit);
+
+               if (!pci || pci->cpu != bit->cpu)
+                       pci = get_cpu_info(pdi, bit->cpu);
+
+               if (!(bit->action == BLK_TN_MESSAGE))
+                       pci->last_sequence = bit->sequence;
+
+               pci->nelems++;
+
+               if (bit->action & (act_mask << BLK_TC_SHIFT))
+                       dump_trace(bit, pci, pdi);
+
+               put_trace(pdi, t);
+       }
+}
+
+static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
+{
+       int ret, bytes_left, fl;
+       void *p;
+
+       if (block != *fdblock) {
+               fl = fcntl(fd, F_GETFL);
+
+               if (!block) {
+                       *fdblock = 0;
+                       fcntl(fd, F_SETFL, fl | O_NONBLOCK);
+               } else {
+                       *fdblock = 1;
+                       fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
+               }
+       }
+
+       bytes_left = bytes;
+       p = buffer;
+       while (bytes_left > 0) {
+               ret = read(fd, p, bytes_left);
+               if (!ret)
+                       return 1;
+               else if (ret < 0) {
+                       if (errno != EAGAIN) {
+                               perror("read");
+                               return -1;
+                       }
+
+                       /*
+                        * never do partial reads. we can return if we
+                        * didn't read anything and we should not block,
+                        * otherwise wait for data
+                        */
+                       if ((bytes_left == bytes) && !block)
+                               return 1;
+
+                       usleep(10);
+                       continue;
+               } else {
+                       p += ret;
+                       bytes_left -= ret;
+               }
+       }
+
+       return 0;
+}
+
+static inline __u16 get_pdulen(struct blk_io_trace *bit)
+{
+       if (data_is_native)
+               return bit->pdu_len;
+
+       return __bswap_16(bit->pdu_len);
+}
+
+static inline __u32 get_magic(struct blk_io_trace *bit)
+{
+       if (data_is_native)
+               return bit->magic;
+
+       return __bswap_32(bit->magic);
+}
+
+static int read_events(int fd, int always_block, int *fdblock)
+{
+       struct per_dev_info *pdi = NULL;
+       unsigned int events = 0;
+
+       while (!is_done() && events < rb_batch) {
+               struct blk_io_trace *bit;
+               struct trace *t;
+               int pdu_len, should_block, ret;
+               __u32 magic;
+
+               bit = bit_alloc();
+
+               should_block = !events || always_block;
+
+               ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
+               if (ret) {
+                       bit_free(bit);
+                       if (!events && ret < 0)
+                               events = ret;
+                       break;
+               }
+
+               /*
+                * look at first trace to check whether we need to convert
+                * data in the future
+                */
+               if (data_is_native == -1 && check_data_endianness(bit->magic))
+                       break;
+
+               magic = get_magic(bit);
+               if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
+                       fprintf(stderr, "Bad magic %x\n", magic);
+                       break;
+               }
+
+               pdu_len = get_pdulen(bit);
+               if (pdu_len) {
+                       void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
+
+                       if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
+                               bit_free(ptr);
+                               break;
+                       }
+
+                       bit = ptr;
+               }
+
+               trace_to_cpu(bit);
+
+               if (verify_trace(bit)) {
+                       bit_free(bit);
+                       continue;
+               }
+
+               /*
+                * not a real trace, so grab and handle it here
+                */
+               if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY) && bit->action != BLK_TN_MESSAGE) {
+                       handle_notify(bit);
+                       output_binary(bit, sizeof(*bit) + bit->pdu_len);
+                       continue;
+               }
+
+               t = t_alloc();
+               memset(t, 0, sizeof(*t));
+               t->bit = bit;
+               t->read_sequence = read_sequence;
+
+               t->next = trace_list;
+               trace_list = t;
+
+               if (!pdi || pdi->dev != bit->device)
+                       pdi = get_dev_info(bit->device);
+
+               if (bit->time > pdi->last_read_time)
+                       pdi->last_read_time = bit->time;
+
+               events++;
+       }
+
+       return events;
+}
+
+/*
+ * Managing input streams
+ */
+
+struct ms_stream {
+       struct ms_stream *next;
+       struct trace *first, *last;
+       struct per_dev_info *pdi;
+       unsigned int cpu;
+};
+
+#define MS_HASH(d, c) ((MAJOR(d) & 0xff) ^ (MINOR(d) & 0xff) ^ (cpu & 0xff))
+
+struct ms_stream *ms_head;
+struct ms_stream *ms_hash[256];
+
+static void ms_sort(struct ms_stream *msp);
+static int ms_prime(struct ms_stream *msp);
+
+static inline struct trace *ms_peek(struct ms_stream *msp)
+{
+       return (msp == NULL) ? NULL : msp->first;
+}
+
+static inline __u64 ms_peek_time(struct ms_stream *msp)
+{
+       return ms_peek(msp)->bit->time;
+}
 
-               trace_list = t->next;
-               bit = t->bit;
+static inline void ms_resort(struct ms_stream *msp)
+{
+       if (msp->next && ms_peek_time(msp) > ms_peek_time(msp->next)) {
+               ms_head = msp->next;
+               msp->next = NULL;
+               ms_sort(msp);
+       }
+}
 
-               memset(&t->rb_node, 0, sizeof(t->rb_node));
+static inline void ms_deq(struct ms_stream *msp)
+{
+       msp->first = msp->first->next;
+       if (!msp->first) {
+               msp->last = NULL;
+               if (!ms_prime(msp)) {
+                       ms_head = msp->next;
+                       msp->next = NULL;
+                       return;
+               }
+       }
 
-               if (verify_trace(bit))
-                       break;
-               if (trace_rb_insert(t))
-                       return -1;
+       ms_resort(msp);
+}
 
-               pdi = get_dev_info(bit->device);
-               pci = get_cpu_info(pdi, bit->cpu);
-               pci->nelems++;
+static void ms_sort(struct ms_stream *msp)
+{
+       __u64 msp_t = ms_peek_time(msp);
+       struct ms_stream *this_msp = ms_head;
 
-               nr++;
+       if (this_msp == NULL)
+               ms_head = msp;
+       else if (msp_t < ms_peek_time(this_msp)) {
+               msp->next = this_msp;
+               ms_head = msp;
        }
+       else {
+               while (this_msp->next && ms_peek_time(this_msp->next) < msp_t)
+                       this_msp = this_msp->next;
 
-       return nr;
+               msp->next = this_msp->next;
+               this_msp->next = msp;
+       }
 }
 
-static void show_entries_rb(int piped)
+static int ms_prime(struct ms_stream *msp)
 {
-       struct per_dev_info *pdi;
-       struct blk_io_trace *bit;
-       struct rb_node *n;
+       __u32 magic;
+       unsigned int i;
        struct trace *t;
-       int cpu;
+       struct per_dev_info *pdi = msp->pdi;
+       struct per_cpu_info *pci = get_cpu_info(pdi, msp->cpu);
+       struct blk_io_trace *bit = NULL;
+       int ret, pdu_len, ndone = 0;
 
-       while ((n = rb_first(&rb_sort_root)) != NULL) {
+       for (i = 0; !is_done() && pci->fd >= 0 && i < rb_batch; i++) {
+               bit = bit_alloc();
+               ret = read_data(pci->fd, bit, sizeof(*bit), 1, &pci->fdblock);
+               if (ret)
+                       goto err;
 
-               t = rb_entry(n, struct trace, rb_node);
-               bit = t->bit;
+               if (data_is_native == -1 && check_data_endianness(bit->magic))
+                       goto err;
+
+               magic = get_magic(bit);
+               if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
+                       fprintf(stderr, "Bad magic %x\n", magic);
+                       goto err;
 
-               pdi = get_dev_info(bit->device);
-               if (!pdi) {
-                       fprintf(stderr, "Unknown device ID? (%d,%d)\n",
-                               MAJOR(bit->device), MINOR(bit->device));
-                       break;
-               }
-               cpu = bit->cpu;
-               if (cpu > pdi->ncpus) {
-                       fprintf(stderr, "Unknown CPU ID? (%d, device %d,%d)\n",
-                               cpu, MAJOR(bit->device), MINOR(bit->device));
-                       break;
                }
 
-               /*
-                * back off displaying more info if we are out of sync
-                * on SMP systems. to prevent stalling on lost events,
-                * only allow an event to us a few times
-                */
-               if (bit->sequence != (pdi->last_sequence + 1)) {
-                       if (piped && t->skipped < 5) {
-                               t->skipped++;
-                               break;
-                       } else {
-                               fprintf(stderr, "skipping from %lu to %u\n", pdi->last_sequence, bit->sequence);
-                               pdi->skips++;
+               pdu_len = get_pdulen(bit);
+               if (pdu_len) {
+                       void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
+                       ret = read_data(pci->fd, ptr + sizeof(*bit), pdu_len,
+                                                            1, &pci->fdblock);
+                       if (ret) {
+                               free(ptr);
+                               bit = NULL;
+                               goto err;
                        }
+
+                       bit = ptr;
                }
 
-               pdi->last_sequence = bit->sequence;
+               trace_to_cpu(bit);
+               if (verify_trace(bit))
+                       goto err;
 
-               bit->time -= genesis_time;
-               if (bit->time < stopwatch_start)
+               if (bit->cpu != pci->cpu) {
+                       fprintf(stderr, "cpu %d trace info has error cpu %d\n",
+                               pci->cpu, bit->cpu);
                        continue;
-               if (bit->time >= stopwatch_end)
-                       break;
+               }
 
-               check_time(pdi, bit);
+               if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY) && bit->action != BLK_TN_MESSAGE) {
+                       handle_notify(bit);
+                       output_binary(bit, sizeof(*bit) + bit->pdu_len);
+                       bit_free(bit);
 
-               if (dump_trace(bit, &pdi->cpus[cpu], pdi))
-                       break;
+                       i -= 1;
+                       continue;
+               }
 
-               rb_erase(&t->rb_node, &rb_sort_root);
+               if (bit->time > pdi->last_read_time)
+                       pdi->last_read_time = bit->time;
+
+               t = t_alloc();
+               memset(t, 0, sizeof(*t));
+               t->bit = bit;
 
-               if (piped) {
-                       free(bit);
-                       free(t);
+               if (msp->first == NULL)
+                       msp->first = msp->last = t;
+               else {
+                       msp->last->next = t;
+                       msp->last = t;
                }
+
+               ndone++;
        }
+
+       return ndone;
+
+err:
+       if (bit) bit_free(bit);
+
+       cpu_mark_offline(pdi, pci->cpu);
+       close(pci->fd);
+       pci->fd = -1;
+
+       return ndone;
 }
 
-static int read_data(int fd, void *buffer, int bytes, int block)
+static struct ms_stream *ms_alloc(struct per_dev_info *pdi, int cpu)
 {
-       int ret, bytes_left, fl;
-       void *p;
-
-       fl = fcntl(fd, F_GETFL);
+       struct ms_stream *msp = malloc(sizeof(*msp));
 
-       if (!block)
-               fcntl(fd, F_SETFL, fl | O_NONBLOCK);
-       else
-               fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
+       msp->next = NULL;
+       msp->first = msp->last = NULL;
+       msp->pdi = pdi;
+       msp->cpu = cpu;
 
-       bytes_left = bytes;
-       p = buffer;
-       while (bytes_left > 0) {
-               ret = read(fd, p, bytes_left);
-               if (!ret)
-                       return 1;
-               else if (ret < 0) {
-                       if (errno != EAGAIN)
-                               perror("read");
-                       return -1;
-               } else {
-                       p += ret;
-                       bytes_left -= ret;
-               }
-       }
+       if (ms_prime(msp))
+               ms_sort(msp);
 
-       return 0;
+       return msp;
 }
 
-/*
- * Find the traces in 'tb' and add them to the list for sorting and
- * displaying
- */
-static int find_entries(void *tb, unsigned long size)
+static int setup_file(struct per_dev_info *pdi, int cpu)
 {
-       struct blk_io_trace *bit;
-       struct trace *t;
-       void *start = tb;
+       int len = 0;
+       struct stat st;
+       char *p, *dname;
+       struct per_cpu_info *pci = get_cpu_info(pdi, cpu);
 
-       while (tb - start <= size - sizeof(*bit)) {
-               bit = find_trace(tb, size - (tb - start));
-               if (!bit)
-                       break;
+       pci->cpu = cpu;
+       pci->fdblock = -1;
+
+       p = strdup(pdi->name);
+       dname = dirname(p);
+       if (strcmp(dname, ".")) {
+               input_dir = dname;
+               p = strdup(pdi->name);
+               strcpy(pdi->name, basename(p));
+       }
+       free(p);
 
-               t = malloc(sizeof(*t));
-               memset(t, 0, sizeof(*t));
-               t->bit = bit;
+       if (input_dir)
+               len = sprintf(pci->fname, "%s/", input_dir);
 
-               trace_to_cpu(bit);
-               t->next = trace_list;
-               trace_list = t;
+       snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
+                "%s.blktrace.%d", pdi->name, pci->cpu);
+       if (stat(pci->fname, &st) < 0)
+               return 0;
+       if (!st.st_size)
+               return 1;
 
-               tb += sizeof(*bit) + bit->pdu_len;
+       pci->fd = open(pci->fname, O_RDONLY);
+       if (pci->fd < 0) {
+               perror(pci->fname);
+               return 0;
        }
 
-       return 0;
-}
-
-static int do_file(void)
-{
-       int i, j, nfiles = 0, nelems;
+       printf("Input file %s added\n", pci->fname);
+       cpu_mark_online(pdi, pci->cpu);
 
-       for (i = 0; i < ndevices; i++) {
-               for (j = 0;; j++, nfiles++) {
-                       struct per_dev_info *pdi;
-                       struct per_cpu_info *pci;
-                       struct stat st;
-                       void *tb;
-
-                       pdi = &devices[i];
-                       pci = get_cpu_info(pdi, j);
-                       pci->cpu = j;
-
-                       snprintf(pci->fname, sizeof(pci->fname)-1,
-                                "%s.%d", pdi->name, j);
-                       if (stat(pci->fname, &st) < 0)
-                               break;
-                       if (!st.st_size)
-                               continue;
+       pdi->nfiles++;
+       ms_alloc(pdi, pci->cpu);
 
-                       printf("Processing %s\n", pci->fname);
+       return 1;
+}
 
-                       tb = malloc(st.st_size);
-                       if (!tb) {
-                               fprintf(stderr, "Out of memory, skip file %s\n",
-                                       pci->fname);
-                               continue;
-                       }
+static int handle(struct ms_stream *msp)
+{
+       struct trace *t;
+       struct per_dev_info *pdi;
+       struct per_cpu_info *pci;
+       struct blk_io_trace *bit;
 
-                       pci->fd = open(pci->fname, O_RDONLY);
-                       if (pci->fd < 0) {
-                               perror(pci->fname);
-                               free(tb);
-                               continue;
-                       }
+       t = ms_peek(msp);
 
-                       if (read_data(pci->fd, tb, st.st_size, 1)) {
-                               close(pci->fd);
-                               free(tb);
-                               continue;
-                       }
+       bit = t->bit;
+       pdi = msp->pdi;
+       pci = get_cpu_info(pdi, msp->cpu);
+       pci->nelems++;
+       bit->time -= genesis_time;
 
-                       if (find_entries(tb, st.st_size)) {
-                               close(pci->fd);
-                               free(tb);
-                       }
+       if (t->bit->time > stopwatch_end)
+               return 0;
 
-                       nelems = sort_entries();
-                       if (nelems == -1) {
-                               close(pci->fd);
-                               free(tb);
-                               continue;
-                       }
+       pdi->last_reported_time = bit->time;
+       if ((bit->action & (act_mask << BLK_TC_SHIFT))&&
+           t->bit->time >= stopwatch_start)
+               dump_trace(bit, pci, pdi);
 
-                       printf("Completed %s (CPU%d %d, entries)\n",
-                               pci->fname, j, nelems);
-                       close(pci->fd);
-               }
-       }
+       ms_deq(msp);
 
-       if (!nfiles) {
-               fprintf(stderr, "No files found\n");
-               return 1;
+       if (text_output)
+               trace_rb_insert_last(pdi, t);
+       else {
+               bit_free(t->bit);
+               t_free(t);
        }
 
-       show_entries_rb(0);
-       return 0;
+       return 1;
 }
 
-static int read_sort_events(int fd)
+/*
+ * Check if we need to sanitize the name. We allow 'foo', or if foo.blktrace.X
+ * is given, then strip back down to 'foo' to avoid missing files.
+ */
+static int name_fixup(char *name)
 {
-       int events = 0;
+       char *b;
 
-       do {
-               struct blk_io_trace *bit;
-               struct trace *t;
-               int pdu_len;
-               __u32 magic;
+       if (!name)
+               return 1;
 
-               bit = malloc(sizeof(*bit));
+       b = strstr(name, ".blktrace.");
+       if (b)
+               *b = '\0';
 
-               if (read_data(fd, bit, sizeof(*bit), !events))
-                       break;
+       return 0;
+}
 
-               magic = be32_to_cpu(bit->magic);
-               if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
-                       fprintf(stderr, "Bad magic %x\n", magic);
-                       break;
-               }
+static int do_file(void)
+{
+       int i, cpu, ret;
+       struct per_dev_info *pdi;
 
-               pdu_len = be16_to_cpu(bit->pdu_len);
-               if (pdu_len) {
-                       void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
+       /*
+        * first prepare all files for reading
+        */
+       for (i = 0; i < ndevices; i++) {
+               pdi = &devices[i];
+               ret = name_fixup(pdi->name);
+               if (ret)
+                       return ret;
 
-                       if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1))
-                               break;
+               for (cpu = 0; setup_file(pdi, cpu); cpu++)
+                       ;
 
-                       bit = ptr;
+               if (!cpu) {
+                       fprintf(stderr,"No input files found for %s\n",
+                               pdi->name);
+                       return 1;
                }
+       }
 
-               t = malloc(sizeof(*t));
-               memset(t, 0, sizeof(*t));
-               t->bit = bit;
+       /*
+        * Get the initial time stamp
+        */
+       if (ms_head)
+               genesis_time = ms_peek_time(ms_head);
 
-               trace_to_cpu(bit);
-               t->next = trace_list;
-               trace_list = t;
+       /*
+        * Correct abs_start_time if necessary
+        */
+       if (start_timestamp
+        && start_timestamp != genesis_time) {
+               correct_abs_start_time();
+       }
 
-               events++;
-       } while (!is_done() && events < rb_batch);
+       /*
+        * Keep processing traces while any are left
+        */
+       while (!is_done() && ms_head && handle(ms_head))
+               ;
 
-       return events;
+       return 0;
 }
 
-static int do_stdin(void)
+static void do_pipe(int fd)
 {
-       int fd;
+       unsigned long long youngest;
+       int events, fdblock;
 
-       fd = dup(STDIN_FILENO);
-       do {
-               int events;
+       last_allowed_time = -1ULL;
+       fdblock = -1;
+       while ((events = read_events(fd, 0, &fdblock)) > 0) {
+               read_sequence++;
+       
+#if 0
+               smallest_seq_read = -1U;
+#endif
 
-               events = read_sort_events(fd);
-               if (!events)
+               if (sort_entries(&youngest))
                        break;
-       
-               if (sort_entries() == -1)
+
+               if (youngest > stopwatch_end)
                        break;
 
+               show_entries_rb(0);
+       }
+
+       if (rb_sort_entries)
                show_entries_rb(1);
-       } while (1);
+}
+
+static int do_fifo(void)
+{
+       int fd;
+
+       if (!strcmp(pipename, "-"))
+               fd = dup(STDIN_FILENO);
+       else
+               fd = open(pipename, O_RDONLY);
+
+       if (fd == -1) {
+               perror("dup stdin");
+               return -1;
+       }
 
+       do_pipe(fd);
        close(fd);
        return 0;
 }
 
-static void flush_output(void)
+static void show_stats(void)
 {
+       if (!ofp)
+               return;
+       if (stats_printed)
+               return;
+
+       stats_printed = 1;
+
+       if (per_process_stats)
+               show_process_stats();
+
+       if (per_device_and_cpu_stats)
+               show_device_and_cpu_stats();
+
        fflush(ofp);
 }
 
-static void handle_sigint(int sig)
+static void handle_sigint(__attribute__((__unused__)) int sig)
 {
        done = 1;
-       flush_output();
 }
 
 /*
@@ -1652,34 +2823,165 @@ static int find_stopwatch_interval(char *string)
                fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
                return 1;
        }
-       stopwatch_end = stopwatch_start + DOUBLE_TO_NANO_ULL(value);
+       stopwatch_end = DOUBLE_TO_NANO_ULL(value);
+       if (stopwatch_end <= stopwatch_start) {
+               fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
+                       stopwatch_start, stopwatch_end);
+               return 1;
+       }
+
+       return 0;
+}
+
+static int is_pipe(const char *str)
+{
+       struct stat st;
+
+       if (!strcmp(str, "-"))
+               return 1;
+       if (!stat(str, &st) && S_ISFIFO(st.st_mode))
+               return 1;
+
+       return 0;
+}
+
+static int get_program_sort_event(const char *str)
+{
+       char evt = str[0];
+
+       switch (evt) {
+       case 'N':
+               per_process_stats_event = SORT_PROG_EVENT_N;
+               break;
+       case 'Q':
+               per_process_stats_event = SORT_PROG_EVENT_QKB;
+               break;
+       case 'q':
+               per_process_stats_event = SORT_PROG_EVENT_QIO;
+               break;
+       case 'R':
+               per_process_stats_event = SORT_PROG_EVENT_RKB;
+               break;
+       case 'r':
+               per_process_stats_event = SORT_PROG_EVENT_RIO;
+               break;
+       case 'W':
+               per_process_stats_event = SORT_PROG_EVENT_WKB;
+               break;
+       case 'w':
+               per_process_stats_event = SORT_PROG_EVENT_WIO;
+               break;
+       case 'C':
+               per_process_stats_event = SORT_PROG_EVENT_CKB;
+               break;
+       case 'c':
+               per_process_stats_event = SORT_PROG_EVENT_CIO;
+               break;
+       default:
+               return 1;
+       }
+
        return 0;
 }
 
+#define S_OPTS  "a:A:b:D:d:f:F:hi:o:OqsS:tw:vVM"
+static char usage_str[] =    "\n\n" \
+       "-i <file>           | --input=<file>\n" \
+       "[ -a <action field> | --act-mask=<action field> ]\n" \
+       "[ -A <action mask>  | --set-mask=<action mask> ]\n" \
+       "[ -b <traces>       | --batch=<traces> ]\n" \
+       "[ -d <file>         | --dump-binary=<file> ]\n" \
+       "[ -D <dir>          | --input-directory=<dir> ]\n" \
+       "[ -f <format>       | --format=<format> ]\n" \
+       "[ -F <spec>         | --format-spec=<spec> ]\n" \
+       "[ -h                | --hash-by-name ]\n" \
+       "[ -o <file>         | --output=<file> ]\n" \
+       "[ -O                | --no-text-output ]\n" \
+       "[ -q                | --quiet ]\n" \
+       "[ -s                | --per-program-stats ]\n" \
+       "[ -S <event>        | --sort-program-stats=<event> ]\n" \
+       "[ -t                | --track-ios ]\n" \
+       "[ -w <time>         | --stopwatch=<time> ]\n" \
+       "[ -M                | --no-msgs\n" \
+       "[ -v                | --verbose ]\n" \
+       "[ -V                | --version ]\n\n" \
+       "\t-a Only trace specified actions. See documentation\n" \
+       "\t-A Give trace mask as a single value. See documentation\n" \
+       "\t-b stdin read batching\n" \
+       "\t-d Output file. If specified, binary data is written to file\n" \
+       "\t-D Directory to prepend to input file names\n" \
+       "\t-f Output format. Customize the output format. The format field\n" \
+       "\t   identifies can be found in the documentation\n" \
+       "\t-F Format specification. Can be found in the documentation\n" \
+       "\t-h Hash processes by name, not pid\n" \
+       "\t-i Input file containing trace data, or '-' for stdin\n" \
+       "\t-o Output file. If not given, output is stdout\n" \
+       "\t-O Do NOT output text data\n" \
+       "\t-q Quiet. Don't display any stats at the end of the trace\n" \
+       "\t-s Show per-program io statistics\n" \
+       "\t-S Show per-program io statistics sorted by N/Q/q/R/r/W/w/C/c\n" \
+       "\t   N:Name, Q/q:Queued(read & write), R/r:Queued Read, W/w:Queued Write, C/c:Complete.\n" \
+       "\t   Sort programs by how much data(KB): Q,R,W,C.\n" \
+       "\t   Sort programs by how many IO operations: q,r,w,c.\n" \
+       "\t   if -S was used, the -s parameter will be ignored.\n" \
+       "\t-t Track individual ios. Will tell you the time a request took\n" \
+       "\t   to get queued, to get dispatched, and to get completed\n" \
+       "\t-w Only parse data between the given time interval in seconds.\n" \
+       "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
+       "\t-M Do not output messages to binary file\n" \
+       "\t-v More verbose for marginal errors\n" \
+       "\t-V Print program version info\n\n";
+
 static void usage(char *prog)
 {
-       fprintf(stderr, "Usage: %s "
-               "[-i <name>] [-o <output>] [-s] [-w N[:n]] <name>...\n",
-               prog);
+       fprintf(stderr, "Usage: %s %s", prog, usage_str);
 }
 
 int main(int argc, char *argv[])
 {
-       char *ofp_buffer;
-       int c, ret, mode;
-       int per_device_and_cpu_stats = 1;
+       int i, c, ret, mode;
+       int act_mask_tmp = 0;
+       char *ofp_buffer = NULL;
+       char *bin_ofp_buffer = NULL;
 
        while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
                switch (c) {
+               case 'a':
+                       i = find_mask_map(optarg);
+                       if (i < 0) {
+                               fprintf(stderr,"Invalid action mask %s\n",
+                                       optarg);
+                               return 1;
+                       }
+                       act_mask_tmp |= i;
+                       break;
+
+               case 'A':
+                       if ((sscanf(optarg, "%x", &i) != 1) || 
+                                                       !valid_act_opt(i)) {
+                               fprintf(stderr,
+                                       "Invalid set action mask %s/0x%x\n",
+                                       optarg, i);
+                               return 1;
+                       }
+                       act_mask_tmp = i;
+                       break;
                case 'i':
-                       if (!strcmp(optarg, "-") && !pipeline)
+                       if (is_pipe(optarg) && !pipeline) {
                                pipeline = 1;
-                       else if (resize_devices(optarg) != 0)
+                               pipename = strdup(optarg);
+                       } else if (resize_devices(optarg) != 0)
                                return 1;
                        break;
+               case 'D':
+                       input_dir = optarg;
+                       break;
                case 'o':
                        output_name = optarg;
                        break;
+               case 'O':
+                       text_output = 0;
+                       break;
                case 'b':
                        rb_batch = atoi(optarg);
                        if (rb_batch <= 0)
@@ -1688,6 +2990,11 @@ int main(int argc, char *argv[])
                case 's':
                        per_process_stats = 1;
                        break;
+               case 'S':
+                       per_process_stats = 1;
+                       if (get_program_sort_event(optarg))
+                               return 1;
+                       break;
                case 't':
                        track_ios = 1;
                        break;
@@ -1705,6 +3012,21 @@ int main(int argc, char *argv[])
                        if (add_format_spec(optarg) != 0)
                                return 1;
                        break;
+               case 'h':
+                       ppi_hash_by_pid = 0;
+                       break;
+               case 'v':
+                       verbose++;
+                       break;
+               case 'V':
+                       printf("%s version %s\n", argv[0], blkparse_version);
+                       return 0;
+               case 'd':
+                       dump_binary = optarg;
+                       break;
+               case 'M':
+                       bin_output_msgs = 0;
+                       break;
                default:
                        usage(argv[0]);
                        return 1;
@@ -1712,9 +3034,10 @@ int main(int argc, char *argv[])
        }
 
        while (optind < argc) {
-               if (!strcmp(argv[optind], "-") && !pipeline)
+               if (is_pipe(argv[optind]) && !pipeline) {
                        pipeline = 1;
-               else if (resize_devices(argv[optind]) != 0)
+                       pipename = strdup(argv[optind]);
+               } else if (resize_devices(argv[optind]) != 0)
                        return 1;
                optind++;
        }
@@ -1724,8 +3047,10 @@ int main(int argc, char *argv[])
                return 1;
        }
 
+       if (act_mask_tmp != 0)
+               act_mask = act_mask_tmp;
+
        memset(&rb_sort_root, 0, sizeof(rb_sort_root));
-       memset(&rb_track_root, 0, sizeof(rb_track_root));
 
        signal(SIGINT, handle_sigint);
        signal(SIGHUP, handle_sigint);
@@ -1733,39 +3058,67 @@ int main(int argc, char *argv[])
 
        setlocale(LC_NUMERIC, "en_US");
 
-       if (!output_name) {
-               ofp = fdopen(STDOUT_FILENO, "w");
-               mode = _IOLBF;
-       } else {
-               char ofname[128];
+       if (text_output) {
+               if (!output_name) {
+                       ofp = fdopen(STDOUT_FILENO, "w");
+                       mode = _IOLBF;
+               } else {
+                       char ofname[PATH_MAX];
 
-               snprintf(ofname, sizeof(ofname) - 1, "%s.log", output_name);
-               ofp = fopen(ofname, "w");
-               mode = _IOFBF;
-       }
+                       snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
+                       ofp = fopen(ofname, "w");
+                       mode = _IOFBF;
+               }
 
-       if (!ofp) {
-               perror("fopen");
-               return 1;
+               if (!ofp) {
+                       perror("fopen");
+                       return 1;
+               }
+
+               ofp_buffer = malloc(4096);
+               if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
+                       perror("setvbuf");
+                       return 1;
+               }
        }
 
-       ofp_buffer = malloc(4096);      
-       if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
-               perror("setvbuf");
-               return 1;
+       if (dump_binary) {
+               if (!strcmp(dump_binary, "-"))
+                       dump_fp = stdout;
+               else {
+                       dump_fp = fopen(dump_binary, "w");
+                       if (!dump_fp) {
+                               perror(dump_binary);
+                               dump_binary = NULL;
+                               return 1;
+                       }
+               }
+               bin_ofp_buffer = malloc(128 * 1024);
+               if (setvbuf(dump_fp, bin_ofp_buffer, _IOFBF, 128 * 1024)) {
+                       perror("setvbuf binary");
+                       return 1;
+               }
        }
 
        if (pipeline)
-               ret = do_stdin();
+               ret = do_fifo();
        else
                ret = do_file();
 
-       if (per_process_stats)
-               show_process_stats();
+       if (!ret)
+               show_stats();
 
-       if (per_device_and_cpu_stats)
-               show_device_and_cpu_stats();
+       if (have_drv_data && !dump_binary)
+               printf("\ndiscarded traces containing low-level device driver "
+                      "specific data (only available in binary output)\n");
 
-       flush_output();
+       if (ofp_buffer) {
+               fflush(ofp);
+               free(ofp_buffer);
+       }
+       if (bin_ofp_buffer) {
+               fflush(dump_fp);
+               free(bin_ofp_buffer);
+       }
        return ret;
 }