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