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