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