[PATCH] blkparse: improve unplug logging
[blktrace.git] / blkparse.c
index 8f79d8fab1189a03581438061c40a3f56d6f92de..b221951129d9fe6367305fb0df39d937fdb770d1 100644 (file)
 #include <errno.h>
 #include <signal.h>
 #include <locale.h>
+#include <limits.h>
 
 #include "blktrace.h"
 #include "rbtree.h"
 
-#define SECONDS(x)     ((unsigned long long)(x) / 1000000000)
-#define NANO_SECONDS(x)        ((unsigned long long)(x) % 1000000000)
+#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 int backwards;
-static unsigned long long genesis_time, last_reported_time;
+#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))
+
+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;
+};
 
 struct per_cpu_info {
        int cpu;
@@ -46,16 +59,41 @@ struct per_cpu_info {
        int fd;
        char fname[128];
 
-       FILE *ofp;
-       char ofname[128];
+       struct io_stats 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;
+struct per_dev_info {
+       dev_t id;
+       char *name;
+
+       int backwards;
+       unsigned long long events;
+       unsigned long long last_reported_time;
+       struct io_stats io_stats;
+
+       int ncpus;
+       struct per_cpu_info *cpus;
+};
+
+struct per_process_info {
+       char name[16];
+       __u32 pid;
+       struct io_stats io_stats;
+       struct per_process_info *hash_next, *list_next;
+
+       /*
+        * individual io stats
+        */
+       unsigned long long longest_allocation_wait[2];
+       unsigned long long longest_dispatch_wait[2];
+       unsigned long long longest_completion_wait[2];
 };
 
-#define S_OPTS "i:o:b:"
+#define PPI_HASH_SHIFT (8)
+static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
+static struct per_process_info *ppi_list;
+
+#define S_OPTS "i:o:b:stqw:"
 static struct option l_opts[] = {
        {
                .name = "input",
@@ -75,6 +113,30 @@ static struct option l_opts[] = {
                .flag = NULL,
                .val = 'b'
        },
+       {
+               .name = "per program stats",
+               .has_arg = 0,
+               .flag = NULL,
+               .val = 's'
+       },
+       {
+               .name = "track ios",
+               .has_arg = 0,
+               .flag = NULL,
+               .val = 't'
+       },
+       {
+               .name = "quiet",
+               .has_arg = 0,
+               .flag = NULL,
+               .val = 'q'
+       },
+       {
+               .name = "stopwatch",
+               .has_arg = 1,
+               .flag = NULL,
+               .val = 'w'
+       },
        {
                .name = NULL,
                .has_arg = 0,
@@ -83,123 +145,538 @@ static struct option l_opts[] = {
        }
 };
 
-static struct rb_root rb_root;
+static struct rb_root rb_sort_root;
+static struct rb_root rb_track_root;
 
+/*
+ * for sorting the displayed output
+ */
 struct trace {
        struct blk_io_trace *bit;
        struct rb_node rb_node;
 };
 
-static int max_cpus;
-static struct per_cpu_info *per_cpu_info;
+/*
+ * for tracking individual ios
+ */
+struct io_track {
+       struct rb_node rb_node;
 
-static unsigned long long events;
+       dev_t device;
+       __u64 sector;
+       __u32 pid;
+       unsigned long long allocation_time;
+       unsigned long long queue_time;
+       unsigned long long dispatch_time;
+       unsigned long long completion_time;
+};
+
+static int ndevices;
+static struct per_dev_info *devices;
+static char *get_dev_name(struct per_dev_info *, char *, int);
+
+static FILE *ofp;
+static char *output_name;
 
-static char *dev, *output_name;
+static unsigned long long genesis_time;
+static unsigned long long stopwatch_start;     /* start from zero by default */
+static unsigned long long stopwatch_end = ULONG_LONG_MAX;      /* "infinity" */
+
+static int per_process_stats;
+static int track_ios;
 
 #define RB_BATCH_DEFAULT       (1024)
 static int rb_batch = RB_BATCH_DEFAULT;
 
+static int pipeline;
+
 #define is_done()      (*(volatile int *)(&done))
 static volatile int done;
 
-static void resize_cpu_info(int cpuid)
+static inline unsigned long hash_long(unsigned long val)
 {
-       int new_space, new_max = cpuid + 1;
+#if __WORDSIZE == 32
+       val *= 0x9e370001UL;
+#elif __WORDSIZE == 64
+       val *= 0x9e37fffffffc0001UL;
+#else
+#error unknown word size
+#endif
+
+       return val >> (__WORDSIZE - PPI_HASH_SHIFT);
+}
+
+static inline void add_process_to_hash(struct per_process_info *ppi)
+{
+       const int hash_idx = hash_long(ppi->pid);
+
+       ppi->hash_next = ppi_hash[hash_idx];
+       ppi_hash[hash_idx] = ppi;
+}
+
+static inline void add_process_to_list(struct per_process_info *ppi)
+{
+       ppi->list_next = ppi_list;
+       ppi_list = ppi;
+}
+
+static struct per_process_info *find_process_by_pid(__u32 pid)
+{
+       const int hash_idx = hash_long(pid);
+       struct per_process_info *ppi;
+
+       ppi = ppi_hash[hash_idx];
+       while (ppi) {
+               if (ppi->pid == pid)
+                       return ppi;
+
+               ppi = ppi->hash_next;
+       }
+
+       return NULL;
+}
+
+static inline int trace_rb_insert(struct trace *t)
+{
+       struct rb_node **p = &rb_sort_root.rb_node;
+       struct rb_node *parent = NULL;
+       struct trace *__t;
+
+       if (genesis_time == 0 || t->bit->time < genesis_time)
+               genesis_time = t->bit->time;
+
+       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 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));
+                       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)
+{
+       struct rb_node **p = &rb_track_root.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->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 (%llu) on device %d,%d!\n",
+                               iot->sector,
+                               MAJOR(iot->device), MINOR(iot->device));
+                       return 1;
+               }
+       }
+
+       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)
+{
+       struct rb_node **p = &rb_track_root.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 (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;
+       }
+
+       return NULL;
+}
+
+static struct io_track *find_track(__u32 pid, dev_t device, __u64 sector)
+{
+       struct io_track *iot;
+
+       iot = __find_track(device, sector);
+       if (!iot) {
+               iot = malloc(sizeof(*iot));
+               iot->pid = pid;
+               iot->device = device;
+               iot->sector = sector;
+               track_rb_insert(iot);
+       }
+
+       return iot;
+}
+
+static void log_track_merge(struct blk_io_trace *t)
+{
+       struct io_track *iot;
+
+       if (!track_ios)
+               return;
+       if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
+               return;
+
+       iot = __find_track(t->device, t->sector - (t->bytes >> 10));
+       if (!iot) {
+               fprintf(stderr, "Trying to merge on non-existing request\n");
+               return;
+       }
+
+       rb_erase(&iot->rb_node, &rb_track_root);
+       iot->sector -= t->bytes >> 10;
+       track_rb_insert(iot);
+}
+
+static void log_track_getrq(struct blk_io_trace *t)
+{
+       struct io_track *iot;
+
+       if (!track_ios)
+               return;
+
+       iot = find_track(t->pid, t->device, t->sector);
+       iot->allocation_time = t->time;
+}
+
+
+/*
+ * return time between rq allocation and queue
+ */
+static unsigned long long log_track_queue(struct blk_io_trace *t)
+{
+       unsigned long long elapsed;
+       struct io_track *iot;
+
+       if (!track_ios)
+               return -1;
+
+       iot = find_track(t->pid, t->device, t->sector);
+       iot->queue_time = t->time;
+       elapsed = iot->queue_time - iot->allocation_time;
+
+       if (per_process_stats) {
+               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
+
+               if (ppi && elapsed > ppi->longest_allocation_wait[w])
+                       ppi->longest_allocation_wait[w] = elapsed;
+       }
+
+       return elapsed;
+}
+
+/*
+ * return time between queue and issue
+ */
+static unsigned long long log_track_issue(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);
+       if (!iot) {
+               fprintf(stderr, "Trying to issue on non-existing request\n");
+               return -1;
+       }
+
+       iot->dispatch_time = t->time;
+       elapsed = iot->dispatch_time - iot->queue_time;
+
+       if (per_process_stats) {
+               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
+
+               if (ppi && elapsed > ppi->longest_dispatch_wait[w])
+                       ppi->longest_dispatch_wait[w] = elapsed;
+       }
+
+       return elapsed;
+}
+
+/*
+ * return time between dispatch and complete
+ */
+static unsigned long long log_track_complete(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);
+       if (!iot) {
+               fprintf(stderr, "Trying to dispatch on non-existing request\n");
+               return -1;
+       }
+
+       iot->completion_time = t->time;
+       elapsed = iot->completion_time - iot->dispatch_time;
+
+       if (per_process_stats) {
+               struct per_process_info *ppi = find_process_by_pid(iot->pid);
+               int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
+
+               if (ppi && elapsed > ppi->longest_completion_wait[w])
+                       ppi->longest_completion_wait[w] = elapsed;
+       }
+
+       /*
+        * kill the trace, we don't need it after completion
+        */
+       rb_erase(&iot->rb_node, &rb_track_root);
+       free(iot);
+
+       return elapsed;
+}
+
+
+static struct io_stats *find_process_io_stats(__u32 pid, char *name)
+{
+       struct per_process_info *ppi = find_process_by_pid(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);
+       }
+
+       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;
 
-       per_cpu_info = realloc(per_cpu_info, new_max * sizeof(*per_cpu_info));
-       if (!per_cpu_info) {
-               fprintf(stderr, "Cannot allocate CPU info -- %d x %d bytes\n",
-                       new_max, (int) sizeof(*per_cpu_info));
+       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 *)per_cpu_info + (max_cpus * sizeof(*per_cpu_info));
-       new_space = (new_max - max_cpus) * sizeof(*per_cpu_info);
+       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);
-       max_cpus = new_max;
+
+       pdi->ncpus = new_count;
+       pdi->cpus = cpus;
+}
+  
+static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
+{
+       if (cpu >= pdi->ncpus)
+               resize_cpu_info(pdi, cpu);
+       return &pdi->cpus[cpu];
 }
 
-static struct per_cpu_info *get_cpu_info(int cpu)
+
+static int resize_devices(char *name)
 {
-       struct per_cpu_info *pci;
+       int size = (ndevices + 1) * sizeof(struct per_dev_info);
 
-       if (cpu >= max_cpus)
-               resize_cpu_info(cpu);
+       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;
+}
 
-       /*
-        * ->cpu might already be set, but just set it unconditionally
-        */
-       pci = &per_cpu_info[cpu];
-       pci->cpu = cpu;
+static struct per_dev_info *get_dev_info(dev_t id, int create)
+{
+       int i;
 
-       return pci;
+       for (i = 0; i < ndevices; i++)
+               if (devices[i].id == id)
+                       return &devices[i];
+       if (!create)
+               return NULL;
+       if (resize_devices(NULL) != 0)
+               return NULL;
+       return &devices[ndevices-1];
 }
 
-static inline void check_time(struct blk_io_trace *bit)
+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));
+       return buffer;
+}
+
+
+static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
 {
        unsigned long long this = bit->time;
-       unsigned long long last = last_reported_time;
+       unsigned long long last = pdi->last_reported_time;
 
-       backwards = (this < last) ? 'B' : ' ';
-       last_reported_time = this;
+       pdi->backwards = (this < last) ? 'B' : ' ';
+       pdi->last_reported_time = this;
 }
 
-static inline void account_m(struct per_cpu_info *pci, int rw,
-                            unsigned int bytes)
+
+static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
+                              int rw)
 {
        if (rw) {
-               pci->mwrites++;
-               pci->qwrite_kb += bytes >> 10;
+               ios->mwrites++;
+               ios->qwrite_kb += t->bytes >> 10;
        } else {
-               pci->mreads++;
-               pci->qread_kb += bytes >> 10;
+               ios->mreads++;
+               ios->qread_kb += t->bytes >> 10;
        }
 }
 
-static inline void account_q(struct per_cpu_info *pci, int rw,
-                            unsigned int bytes)
+static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
+                            int rw)
+{
+       __account_m(&pci->io_stats, t, rw);
+
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+
+               __account_m(ios, t, rw);
+       }
+}
+
+static inline void __account_q(struct io_stats *ios, struct blk_io_trace *t,
+                              int rw)
 {
        if (rw) {
-               pci->qwrites++;
-               pci->qwrite_kb += bytes >> 10;
+               ios->qwrites++;
+               ios->qwrite_kb += t->bytes >> 10;
        } else {
-               pci->qreads++;
-               pci->qread_kb += bytes >> 10;
+               ios->qreads++;
+               ios->qread_kb += t->bytes >> 10;
+       }
+}
+
+static inline void account_q(struct blk_io_trace *t, struct per_cpu_info *pci,
+                            int rw)
+{
+       __account_q(&pci->io_stats, t, rw);
+
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+
+               __account_q(ios, t, rw);
        }
 }
 
-static inline void account_c(struct per_cpu_info *pci, int rw,
-                            unsigned int bytes)
+static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
 {
        if (rw) {
-               pci->cwrites++;
-               pci->cwrite_kb += bytes >> 10;
+               ios->cwrites++;
+               ios->cwrite_kb += bytes >> 10;
        } else {
-               pci->creads++;
-               pci->cread_kb += bytes >> 10;
+               ios->creads++;
+               ios->cread_kb += bytes >> 10;
        }
 }
 
-static inline void account_i(struct per_cpu_info *pci, int rw,
-                            unsigned int bytes)
+static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
+                            int rw, int bytes)
+{
+       __account_c(&pci->io_stats, rw, bytes);
+
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+
+               __account_c(ios, rw, bytes);
+       }
+}
+
+static inline void __account_i(struct io_stats *ios, int rw, unsigned int bytes)
 {
        if (rw) {
-               pci->iwrites++;
-               pci->iwrite_kb += bytes >> 10;
+               ios->iwrites++;
+               ios->iwrite_kb += bytes >> 10;
        } else {
-               pci->ireads++;
-               pci->iread_kb += bytes >> 10;
+               ios->ireads++;
+               ios->iread_kb += bytes >> 10;
        }
 }
 
-static void output(struct per_cpu_info *pci, char *s)
+static inline void account_i(struct blk_io_trace *t, struct per_cpu_info *pci,
+                            int rw)
 {
-       printf("%s", s);
+       __account_i(&pci->io_stats, rw, t->bytes);
+
+       if (per_process_stats) {
+               struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
+
+               __account_i(ios, rw, t->bytes);
+       }
+}
 
-       if (pci->ofp)
-               fprintf(pci->ofp, "%s", s);
+static void output(struct per_cpu_info *pci, char *s)
+{
+       fprintf(ofp, "%s", s);
 }
 
 static char hstring[256];
@@ -225,8 +702,8 @@ static inline char *setup_header(struct per_cpu_info *pci,
 
        rwbs[i] = '\0';
 
-       sprintf(hstring, "%c %3d %15ld %5Lu.%09Lu %5u %c %3s", backwards,
-               pci->cpu,
+       sprintf(hstring, "%3d,%-3d %2d %8ld %5Lu.%09Lu %5u %c %3s",
+               MAJOR(t->device), MINOR(t->device), pci->cpu,
                (unsigned long)t->sequence, SECONDS(t->time), 
                NANO_SECONDS(t->time), t->pid, act, rwbs);
 
@@ -236,31 +713,68 @@ static inline char *setup_header(struct per_cpu_info *pci,
 static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
                         char act)
 {
-       sprintf(tstring,"%s %Lu + %u [%d]\n", setup_header(pci, t, act),
-               (unsigned long long)t->sector, t->bytes >> 9, t->error);
+       unsigned long long elapsed = log_track_complete(t);
+
+       if (elapsed != -1ULL) {
+               unsigned long usec = elapsed / 1000;
+
+               sprintf(tstring,"%s %Lu + %u (%8lu) [%d]\n",
+                       setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9,
+                       usec, t->error);
+       } else {
+               sprintf(tstring,"%s %Lu + %u [%d]\n", setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9, t->error);
+       }
+       
        output(pci, tstring);
 }
 
 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
                      char act)
 {
-       sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
-               (unsigned long long)t->sector, t->bytes >> 9, t->comm);
+       unsigned long long elapsed = log_track_queue(t);
+
+       if (elapsed != -1ULL) {
+               unsigned long usec = elapsed / 1000;
+
+               sprintf(tstring,"%s %Lu + %u (%8lu) [%s]\n",
+                       setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9,
+                       usec, t->comm);
+       } else {
+               sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9, t->comm);
+       }
        output(pci, tstring);
 }
 
 static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
                      char act)
 {
-       sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
-               (unsigned long long)t->sector, t->bytes >> 9, t->comm);
+       unsigned long long elapsed = log_track_issue(t);
+
+       if (elapsed != -1ULL) {
+               double usec = (double) elapsed / 1000;
+
+               sprintf(tstring,"%s %Lu + %u (%8.2f) [%s]\n",
+                       setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9,
+                       usec, t->comm);
+       } else {
+               sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
+                       (unsigned long long)t->sector, t->bytes >> 9, t->comm);
+       }
+
        output(pci, tstring);
 }
 
 static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
                      char act)
 {
-       sprintf(tstring,"%s   %Lu + %u [%s]\n", setup_header(pci, t, act),
+       log_track_merge(t);
+
+       sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
                (unsigned long long)t->sector, t->bytes >> 9, t->comm);
        output(pci, tstring);
 }
@@ -273,6 +787,20 @@ static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
        output(pci, tstring);
 }
 
+static int log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
+                     char act)
+{
+       __u64 *depth;
+       int len;
+
+       len = sprintf(tstring,"%s ", setup_header(pci, t, act));
+       depth = (__u64 *) t + sizeof(*t);
+       sprintf(tstring + len, "%u\n", (unsigned int) be64_to_cpu(*depth));
+       output(pci, tstring);
+
+       return 0;
+}
+
 static int log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char act)
 {
        unsigned char *buf;
@@ -332,146 +860,168 @@ static int dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
 static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
 {
        int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
+       int act = t->action & 0xffff;
 
-       switch (t->action & 0xffff) {
+       switch (act) {
                case __BLK_TA_QUEUE:
-                       account_q(pci, w, t->bytes);
+                       account_q(t, pci, w);
                        log_queue(pci, t, 'Q');
                        break;
                case __BLK_TA_BACKMERGE:
-                       account_m(pci, w, t->bytes);
+                       account_m(t, pci, w);
                        log_merge(pci, t, 'M');
                        break;
                case __BLK_TA_FRONTMERGE:
-                       account_m(pci, w, t->bytes);
+                       account_m(t, pci, w);
                        log_merge(pci, t, 'F');
                        break;
                case __BLK_TA_GETRQ:
+                       log_track_getrq(t);
                        log_generic(pci, t, 'G');
                        break;
                case __BLK_TA_SLEEPRQ:
                        log_generic(pci, t, 'S');
                        break;
                case __BLK_TA_REQUEUE:
-                       account_c(pci, w, -t->bytes);
+                       account_c(t, pci, w, -t->bytes);
                        log_queue(pci, t, 'R');
                        break;
                case __BLK_TA_ISSUE:
-                       account_i(pci, w, t->bytes);
+                       account_i(t, pci, w);
                        log_issue(pci, t, 'D');
                        break;
                case __BLK_TA_COMPLETE:
-                       account_c(pci, w, t->bytes);
+                       account_c(t, pci, w, t->bytes);
                        log_complete(pci, t, 'C');
                        break;
+               case __BLK_TA_PLUG:
+                       log_generic(pci, t, 'P');
+                       break;
+               case __BLK_TA_UNPLUG:
+                       log_unplug(pci, t, 'U');
+                       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)
+static int dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
+                       struct per_dev_info *pdi)
 {
        int ret = 0;
 
-       if (output_name && !pci->ofp) {
-               snprintf(pci->ofname, sizeof(pci->ofname) - 1,
-                               "%s_log.%d", output_name, pci->cpu);
-
-               pci->ofp = fopen(pci->ofname, "w");
-               if (pci->ofp == NULL) {
-                       perror(pci->ofname);
-                       return 1;
-               }
-       }
-
        if (t->action & BLK_TC_ACT(BLK_TC_PC))
                ret = dump_trace_pc(t, pci);
        else
                dump_trace_fs(t, pci);
 
-       events++;
+       pdi->events++;
        return ret;
 }
 
-static void dump_pci_stats(struct per_cpu_info *pci)
+static void dump_io_stats(struct io_stats *ios, char *msg)
 {
-       printf(" Reads Queued:    %'8lu, %'8LuKiB\t", pci->qreads, pci->qread_kb);
-       printf(" Writes Queued:    %'8lu, %'8LuKiB\n", pci->qwrites,pci->qwrite_kb);
+       fprintf(ofp, "%s\n", msg);
 
-       printf(" Read Dispatches: %'8lu, %'8LuKiB\t", pci->ireads, pci->iread_kb);
-       printf(" Write Dispatches: %'8lu, %'8LuKiB\n", pci->iwrites,pci->iwrite_kb);
-       printf(" Reads Completed: %'8lu, %'8LuKiB\t", pci->creads, pci->cread_kb);
-       printf(" Writes Completed: %'8lu, %'8LuKiB\n", pci->cwrites,pci->cwrite_kb);
-       printf(" Read Merges:     %'8lu%8c\t", pci->mreads, ' ');
+       fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
+       fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
 
-       printf(" Write Merges:     %'8lu\n", pci->mwrites);
+       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);
 }
 
-static void show_stats(void)
+static void dump_wait_stats(struct per_process_info *ppi)
 {
-       struct per_cpu_info foo, *pci;
-       int i, pci_events = 0;
-
-       memset(&foo, 0, sizeof(foo));
-
-       for (i = 0; i < max_cpus; i++) {
-               pci = &per_cpu_info[i];
-
-               if (!pci->nelems)
-                       continue;
-
-               foo.qreads += pci->qreads;
-               foo.qwrites += pci->qwrites;
-               foo.creads += pci->creads;
-               foo.cwrites += pci->cwrites;
-               foo.mreads += pci->mreads;
-               foo.mwrites += pci->mwrites;
-               foo.qread_kb += pci->qread_kb;
-               foo.qwrite_kb += pci->qwrite_kb;
-               foo.cread_kb += pci->cread_kb;
-               foo.cwrite_kb += pci->cwrite_kb;
+       unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
+       unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
+       unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
+       unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
+       unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
+       unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
+
+       fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
+       fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
+       fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
+       fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
+       fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
+       fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
+}
 
-               printf("CPU%d:\n", i);
-               dump_pci_stats(pci);
-               pci_events++;
-       }
+static void show_process_stats(void)
+{
+       struct per_process_info *ppi;
 
-       if (pci_events > 1) {
-               printf("Total:\n");
-               dump_pci_stats(&foo);
+       ppi = ppi_list;
+       while (ppi) {
+               dump_io_stats(&ppi->io_stats, ppi->name);
+               dump_wait_stats(ppi);
+               ppi = ppi->list_next;
        }
 
-       printf("Events: %'Lu\n", events);
+       fprintf(ofp, "\n");
 }
 
-static inline int trace_rb_insert(struct trace *t)
+static void show_device_and_cpu_stats(void)
 {
-       struct rb_node **p = &rb_root.rb_node;
-       struct rb_node *parent = NULL;
-       struct trace *__t;
-
-       while (*p) {
-               parent = *p;
-               __t = rb_entry(parent, struct trace, rb_node);
+       struct per_dev_info *pdi;
+       struct per_cpu_info *pci;
+       struct io_stats total, *ios;
+       int i, j, pci_events;
+       char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
+       char name[32];
+
+       for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
+
+               memset(&total, 0, sizeof(total));
+               pci_events = 0;
+
+               if (i > 0)
+                       fprintf(ofp, "\n");
+
+               for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
+                       if (!pci->nelems)
+                               continue;
+
+                       ios = &pci->io_stats;
+                       total.qreads += ios->qreads;
+                       total.qwrites += ios->qwrites;
+                       total.creads += ios->creads;
+                       total.cwrites += ios->cwrites;
+                       total.mreads += ios->mreads;
+                       total.mwrites += ios->mwrites;
+                       total.ireads += ios->ireads;
+                       total.iwrites += ios->iwrites;
+                       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;
+
+                       snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
+                                j, get_dev_name(pdi, name, sizeof(name)));
+                       dump_io_stats(ios, line);
+                       pci_events++;
+               }
 
-               if (t->bit->sequence < __t->bit->sequence)
-                       p = &(*p)->rb_left;
-               else if (t->bit->sequence > __t->bit->sequence)
-                       p = &(*p)->rb_right;
-               else {
-                       fprintf(stderr, "sequence alias!\n");
-                       return 1;
+               if (pci_events > 1) {
+                       fprintf(ofp, "\n");
+                       snprintf(line, sizeof(line) - 1, "Total (%s):",
+                                get_dev_name(pdi, name, sizeof(name)));
+                       dump_io_stats(&total, line);
                }
-       }
 
-       rb_link_node(&t->rb_node, parent, p);
-       rb_insert_color(&t->rb_node, &rb_root);
-       return 0;
+               fprintf(ofp, "Events (%s): %'Lu\n",
+                       get_dev_name(pdi, line, sizeof(line)), pdi->events);
+       }
 }
 
-#define min(a, b)      ((a) < (b) ? (a) : (b))
-
 static struct blk_io_trace *find_trace(void *p, unsigned long offset, int nr)
 {
        unsigned long max_offset = min(offset,nr * sizeof(struct blk_io_trace));
@@ -490,13 +1040,14 @@ static struct blk_io_trace *find_trace(void *p, unsigned long offset, int nr)
        return NULL;
 }
 
-static int sort_entries(void *traces, unsigned long offset, int nr)
+static int sort_entries(void *traces, unsigned long offset, int nr,
+                       struct per_dev_info *fpdi, struct per_cpu_info *fpci)
 {
+       struct per_dev_info *pdi;
        struct per_cpu_info *pci;
        struct blk_io_trace *bit;
        struct trace *t;
        void *start = traces;
-       int nelems = 0;
 
        while (traces - start <= offset - sizeof(*bit)) {
                if (!nr)
@@ -507,48 +1058,61 @@ static int sort_entries(void *traces, unsigned long offset, int nr)
                        break;
 
                t = malloc(sizeof(*t));
+               if (!t) {
+                       fprintf(stderr, "Out of memory, seq %d on dev %d,%d\n",
+                               bit->sequence,
+                               MAJOR(bit->device), MINOR(bit->device));
+                       return -1;
+               }
                t->bit = bit;
                memset(&t->rb_node, 0, sizeof(t->rb_node));
 
                trace_to_cpu(bit);
 
-               if (verify_trace(bit))
+               if (verify_trace(bit)) {
+                       free(t);
                        break;
+               }
 
-               pci = get_cpu_info(bit->cpu);
+               pdi = fpdi ? fpdi : get_dev_info(bit->device, 1);
+               pdi->id = bit->device;
+               pci = fpci ? fpci : get_cpu_info(pdi, bit->cpu);
+               pci->cpu = bit->cpu;
                pci->nelems++;
 
-               if (trace_rb_insert(t))
+               if (trace_rb_insert(t)) {
+                       free(t);
                        return -1;
+               }
 
                traces += sizeof(*bit) + bit->pdu_len;
-               nelems++;
                nr--;
        }
 
-       return nelems;
+       return 0;
 }
 
 static void free_entries_rb(void)
 {
        struct rb_node *n;
 
-       while ((n = rb_first(&rb_root)) != NULL) {
+       while ((n = rb_first(&rb_sort_root)) != NULL) {
                struct trace *t = rb_entry(n, struct trace, rb_node);
 
-               rb_erase(&t->rb_node, &rb_root);
+               rb_erase(&t->rb_node, &rb_sort_root);
                free(t);
        }
 }
 
 static void show_entries_rb(void)
 {
+       struct per_dev_info *pdi;
        struct blk_io_trace *bit;
        struct rb_node *n;
        struct trace *t;
        int cpu;
 
-       n = rb_first(&rb_root);
+       n = rb_first(&rb_sort_root);
        if (!n)
                return;
 
@@ -556,19 +1120,28 @@ static void show_entries_rb(void)
                t = rb_entry(n, struct trace, rb_node);
                bit = t->bit;
 
+               pdi = get_dev_info(bit->device, 0);
+               if (!pdi) {
+                       fprintf(stderr, "Unknown device ID? (%d,%d)\n",
+                               MAJOR(bit->device), MINOR(bit->device));
+                       break;
+               }
                cpu = bit->cpu;
-               if (cpu > max_cpus) {
-                       fprintf(stderr, "CPU number too large (%d)\n", cpu);
+               if (cpu > pdi->ncpus) {
+                       fprintf(stderr, "Unknown CPU ID? (%d, device %d,%d)\n",
+                               cpu, MAJOR(bit->device), MINOR(bit->device));
                        break;
                }
 
-               if (genesis_time == 0)
-                       genesis_time = bit->time;
                bit->time -= genesis_time;
+               if (bit->time < stopwatch_start)
+                       continue;
+               if (bit->time >= stopwatch_end)
+                       break;
 
-               check_time(bit);
+               check_time(pdi, bit);
 
-               if (dump_trace(bit, &per_cpu_info[cpu]))
+               if (dump_trace(bit, &pdi->cpus[cpu], pdi))
                        break;
 
        } while ((n = rb_next(n)) != NULL);
@@ -607,41 +1180,57 @@ static int read_data(int fd, void *buffer, int bytes, int block)
 
 static int do_file(void)
 {
-       int i, nfiles;
-
-       for (i = 0, nfiles = 0;; i++, nfiles++) {
-               struct per_cpu_info *pci;
-               struct stat st;
-               void *tb;
-
-               pci = get_cpu_info(i);
-               pci->ofp = NULL;
-
-               snprintf(pci->fname, sizeof(pci->fname)-1,"%s_out.%d", dev, i);
-               if (stat(pci->fname, &st) < 0)
-                       break;
-               if (!st.st_size)
-                       continue;
+       struct per_dev_info *pdi;
+       int i, j, nfiles = 0;
 
-               printf("Processing %s\n", pci->fname);
+       for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
+               for (j = 0;; j++, nfiles++) {
+                       struct per_cpu_info *pci;
+                       struct stat st;
+                       void *tb;
 
-               tb = malloc(st.st_size);
+                       pci = get_cpu_info(pdi, j);
+                       pci->cpu = j;
 
-               pci->fd = open(pci->fname, O_RDONLY);
-               if (pci->fd < 0) {
-                       perror(pci->fname);
-                       break;
+                       snprintf(pci->fname, sizeof(pci->fname)-1,
+                                "%s_out.%d", pdi->name, j);
+                       if (stat(pci->fname, &st) < 0)
+                               break;
+                       if (!st.st_size)
+                               continue;
+
+                       printf("Processing %s\n", pci->fname);
+
+                       tb = malloc(st.st_size);
+                       if (!tb) {
+                               fprintf(stderr, "Out of memory, skip file %s\n",
+                                       pci->fname);
+                               continue;
+                       }
+
+                       pci->fd = open(pci->fname, O_RDONLY);
+                       if (pci->fd < 0) {
+                               perror(pci->fname);
+                               free(tb);
+                               continue;
+                       }
+
+                       if (read_data(pci->fd, tb, st.st_size, 1)) {
+                               close(pci->fd);
+                               free(tb);
+                               continue;
+                       }
+
+                       if (sort_entries(tb, st.st_size, ~0U, pdi, pci) == -1) {
+                               close(pci->fd);
+                               free(tb);
+                               continue;
+                       }
+
+                       printf("Completed %s (CPU%d %d, entries)\n",
+                               pci->fname, j, pci->nelems);
+                       close(pci->fd);
                }
-
-               if (read_data(pci->fd, tb, st.st_size, 1))
-                       break;
-
-               if (sort_entries(tb, st.st_size, ~0U) == -1)
-                       break;
-
-               close(pci->fd);
-               printf("\t%2d %10s %15d\n", i, pci->fname, pci->nelems);
-
        }
 
        if (!nfiles) {
@@ -657,43 +1246,46 @@ static void resize_buffer(void **buffer, long *size, long offset)
 {
        long old_size = *size;
 
+       if (*size == 0)
+               *size = 64 * sizeof(struct blk_io_trace);
+
        *size *= 2;
        *buffer = realloc(*buffer, *size);
-       memset(*buffer + offset, 0, *size - old_size);
+
+       if (old_size)
+               memset(*buffer + offset, 0, *size - old_size);
 }
 
-static int read_sort_events(int fd, void **buffer)
+static int read_sort_events(int fd, void **buffer, long *max_offset)
 {
-       long offset, max_offset;
+       long offset;
        int events;
 
-       max_offset = 128 * sizeof(struct blk_io_trace);
-       *buffer = malloc(max_offset);
-       events = 0;
-       offset = 0;
-
+       events = offset = 0;
        do {
                struct blk_io_trace *t;
                int pdu_len;
+               __u32 magic;
 
-               if (max_offset - offset < sizeof(*t))
-                       resize_buffer(buffer, &max_offset, offset);
+               if (*max_offset - offset < sizeof(*t))
+                       resize_buffer(buffer, max_offset, offset);
 
-               if (read_data(fd, *buffer + offset, sizeof(*t), !events)) {
-                       if (events)
-                               break;
-
-                       usleep(1000);
-                       continue;
-               }
+               if (read_data(fd, *buffer + offset, sizeof(*t), !events))
+                       break;
 
                t = *buffer + offset;
                offset += sizeof(*t);
 
+               magic = be32_to_cpu(t->magic);
+               if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
+                       fprintf(stderr, "Bad magic %x\n", magic);
+                       break;
+               }
+
                pdu_len = be16_to_cpu(t->pdu_len);
                if (pdu_len) {
-                       if (max_offset - offset < pdu_len)
-                               resize_buffer(buffer, &max_offset, offset);
+                       if (*max_offset - offset <= pdu_len)
+                               resize_buffer(buffer, max_offset, offset);
 
                        if (read_data(fd, *buffer + offset, pdu_len, 1))
                                break;
@@ -710,41 +1302,35 @@ static int read_sort_events(int fd, void **buffer)
 static int do_stdin(void)
 {
        int fd;
-       void *ptr;
+       void *ptr = NULL;
+       long max_offset;
 
        fd = dup(STDIN_FILENO);
+       max_offset = 0;
        do {
                int events;
 
-               events = read_sort_events(fd, &ptr);
+               events = read_sort_events(fd, &ptr, &max_offset);
                if (!events)
                        break;
        
-               if (sort_entries(ptr, ~0UL, events) == -1)
+               if (sort_entries(ptr, ~0UL, events, NULL, NULL) == -1)
                        break;
 
                show_entries_rb();
                free_entries_rb();
        } while (1);
 
+       if (ptr)
+               free(ptr);
+
        close(fd);
-       free(ptr);
        return 0;
 }
 
 static void flush_output(void)
 {
-       int i;
-
-       for (i = 0; i < max_cpus; i++) {
-               struct per_cpu_info *pci = &per_cpu_info[i];
-
-               if (pci->ofp) {
-                       fflush(pci->ofp);
-                       fclose(pci->ofp);
-                       pci->ofp = NULL;
-               }
-       }
+       fflush(ofp);
 }
 
 static void handle_sigint(int sig)
@@ -753,40 +1339,101 @@ static void handle_sigint(int sig)
        flush_output();
 }
 
+/*
+ * Extract start and duration times from a string, allowing
+ * us to specify a time interval of interest within a trace.
+ * Format: "duration" (start is zero) or "start:duration".
+ */
+static int find_stopwatch_interval(char *string)
+{
+       double value;
+       char *sp;
+
+       value = strtod(string, &sp);
+       if (sp == string) {
+               fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
+               return 1;
+       }
+       if (*sp == ':') {
+               stopwatch_start = DOUBLE_TO_NANO_ULL(value);
+               string = sp + 1;
+               value = strtod(string, &sp);
+               if (sp == string || *sp != '\0') {
+                       fprintf(stderr,"Invalid stopwatch duration time: %s\n",
+                               string);
+                       return 1;
+               }
+       } else if (*sp != '\0') {
+               fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
+               return 1;
+       }
+       stopwatch_end = stopwatch_start + DOUBLE_TO_NANO_ULL(value);
+       return 0;
+}
+
 static void usage(char *prog)
 {
-       fprintf(stderr, "Usage: %s -i <name> [-o <output>]\n", prog);
+       fprintf(stderr, "Usage: %s "
+               "[-i <name>] [-o <output>] [-s] [-w N[:n]] <name>...\n",
+               prog);
 }
 
 int main(int argc, char *argv[])
 {
-       int c, ret;
+       char *ofp_buffer;
+       int c, ret, mode;
+       int per_device_and_cpu_stats = 1;
 
        while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
                switch (c) {
                case 'i':
-                       dev = strdup(optarg);
+                       if (!strcmp(optarg, "-") && !pipeline)
+                               pipeline = 1;
+                       else if (resize_devices(optarg) != 0)
+                               return 1;
                        break;
                case 'o':
-                       output_name = strdup(optarg);
+                       output_name = optarg;
                        break;
                case 'b':
                        rb_batch = atoi(optarg);
                        if (rb_batch <= 0)
                                rb_batch = RB_BATCH_DEFAULT;
                        break;
+               case 's':
+                       per_process_stats = 1;
+                       break;
+               case 't':
+                       track_ios = 1;
+                       break;
+               case 'q':
+                       per_device_and_cpu_stats = 0;
+                       break;
+               case 'w':
+                       if (find_stopwatch_interval(optarg) != 0)
+                               return 1;
+                       break;
                default:
                        usage(argv[0]);
                        return 1;
                }
        }
 
-       if (!dev) {
+       while (optind < argc) {
+               if (!strcmp(argv[optind], "-") && !pipeline)
+                       pipeline = 1;
+               else if (resize_devices(argv[optind]) != 0)
+                       return 1;
+               optind++;
+       }
+
+       if (!pipeline && !ndevices) {
                usage(argv[0]);
                return 1;
        }
 
-       memset(&rb_root, 0, sizeof(rb_root));
+       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);
@@ -794,12 +1441,39 @@ int main(int argc, char *argv[])
 
        setlocale(LC_NUMERIC, "en_US");
 
-       if (!strcmp(dev, "-"))
+       if (!output_name) {
+               ofp = fdopen(STDOUT_FILENO, "w");
+               mode = _IOLBF;
+       } else {
+               char ofname[128];
+
+               snprintf(ofname, sizeof(ofname) - 1, "%s.log", output_name);
+               ofp = fopen(ofname, "w");
+               mode = _IOFBF;
+       }
+
+       if (!ofp) {
+               perror("fopen");
+               return 1;
+       }
+
+       ofp_buffer = malloc(4096);      
+       if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
+               perror("setvbuf");
+               return 1;
+       }
+
+       if (pipeline)
                ret = do_stdin();
        else
                ret = do_file();
 
-       show_stats();
+       if (per_process_stats)
+               show_process_stats();
+
+       if (per_device_and_cpu_stats)
+               show_device_and_cpu_stats();
+
        flush_output();
        return ret;
 }