0d2ea1281fcbfa1c61d8c3fd065dab12b4b64aa0
[blktrace.git] / blkparse.c
1 /*
2  * block queue tracing parse application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <getopt.h>
30 #include <errno.h>
31 #include <signal.h>
32 #include <locale.h>
33 #include <libgen.h>
34
35 #include "blktrace.h"
36 #include "rbtree.h"
37 #include "jhash.h"
38
39 static char blkparse_version[] = "0.99.2";
40
41 struct skip_info {
42         unsigned long start, end;
43         struct skip_info *prev, *next;
44 };
45
46 struct per_dev_info {
47         dev_t dev;
48         char *name;
49
50         int backwards;
51         unsigned long long events;
52         unsigned long long first_reported_time;
53         unsigned long long last_reported_time;
54         unsigned long long last_read_time;
55         struct io_stats io_stats;
56         unsigned long skips;
57         unsigned long long seq_skips;
58         unsigned int max_depth[2];
59         unsigned int cur_depth[2];
60
61         struct rb_root rb_track;
62
63         int nfiles;
64         int ncpus;
65
66         unsigned long *cpu_map;
67         unsigned int cpu_map_max;
68
69         struct per_cpu_info *cpus;
70 };
71
72 /*
73  * some duplicated effort here, we can unify this hash and the ppi hash later
74  */
75 struct process_pid_map {
76         pid_t pid;
77         char comm[16];
78         struct process_pid_map *hash_next, *list_next;
79 };
80
81 #define PPM_HASH_SHIFT  (8)
82 #define PPM_HASH_SIZE   (1 << PPM_HASH_SHIFT)
83 #define PPM_HASH_MASK   (PPM_HASH_SIZE - 1)
84 static struct process_pid_map *ppm_hash_table[PPM_HASH_SIZE];
85
86 struct per_process_info {
87         struct process_pid_map *ppm;
88         struct io_stats io_stats;
89         struct per_process_info *hash_next, *list_next;
90         int more_than_one;
91
92         /*
93          * individual io stats
94          */
95         unsigned long long longest_allocation_wait[2];
96         unsigned long long longest_dispatch_wait[2];
97         unsigned long long longest_completion_wait[2];
98 };
99
100 #define PPI_HASH_SHIFT  (8)
101 #define PPI_HASH_SIZE   (1 << PPI_HASH_SHIFT)
102 #define PPI_HASH_MASK   (PPI_HASH_SIZE - 1)
103 static struct per_process_info *ppi_hash_table[PPI_HASH_SIZE];
104 static struct per_process_info *ppi_list;
105 static int ppi_list_entries;
106
107 #define S_OPTS  "a:A:b:D:d:f:F:hi:o:Oqstw:vV"
108 static struct option l_opts[] = {
109         {
110                 .name = "act-mask",
111                 .has_arg = required_argument,
112                 .flag = NULL,
113                 .val = 'a'
114         },
115         {
116                 .name = "set-mask",
117                 .has_arg = required_argument,
118                 .flag = NULL,
119                 .val = 'A'
120         },
121         {
122                 .name = "batch",
123                 .has_arg = required_argument,
124                 .flag = NULL,
125                 .val = 'b'
126         },
127         {
128                 .name = "input-directory",
129                 .has_arg = required_argument,
130                 .flag = NULL,
131                 .val = 'D'
132         },
133         {
134                 .name = "dump-binary",
135                 .has_arg = required_argument,
136                 .flag = NULL,
137                 .val = 'd'
138         },
139         {
140                 .name = "format",
141                 .has_arg = required_argument,
142                 .flag = NULL,
143                 .val = 'f'
144         },
145         {
146                 .name = "format-spec",
147                 .has_arg = required_argument,
148                 .flag = NULL,
149                 .val = 'F'
150         },
151         {
152                 .name = "hash-by-name",
153                 .has_arg = no_argument,
154                 .flag = NULL,
155                 .val = 'h'
156         },
157         {
158                 .name = "input",
159                 .has_arg = required_argument,
160                 .flag = NULL,
161                 .val = 'i'
162         },
163         {
164                 .name = "output",
165                 .has_arg = required_argument,
166                 .flag = NULL,
167                 .val = 'o'
168         },
169         {
170                 .name = "no-text-output",
171                 .has_arg = no_argument,
172                 .flag = NULL,
173                 .val = 'O'
174         },
175         {
176                 .name = "quiet",
177                 .has_arg = no_argument,
178                 .flag = NULL,
179                 .val = 'q'
180         },
181         {
182                 .name = "per-program-stats",
183                 .has_arg = no_argument,
184                 .flag = NULL,
185                 .val = 's'
186         },
187         {
188                 .name = "track-ios",
189                 .has_arg = no_argument,
190                 .flag = NULL,
191                 .val = 't'
192         },
193         {
194                 .name = "stopwatch",
195                 .has_arg = required_argument,
196                 .flag = NULL,
197                 .val = 'w'
198         },
199         {
200                 .name = "verbose",
201                 .has_arg = no_argument,
202                 .flag = NULL,
203                 .val = 'v'
204         },
205         {
206                 .name = "version",
207                 .has_arg = no_argument,
208                 .flag = NULL,
209                 .val = 'V'
210         },
211         {
212                 .name = NULL,
213         }
214 };
215
216 /*
217  * for sorting the displayed output
218  */
219 struct trace {
220         struct blk_io_trace *bit;
221         struct rb_node rb_node;
222         struct trace *next;
223         unsigned long read_sequence;
224 };
225
226 static struct rb_root rb_sort_root;
227 static unsigned long rb_sort_entries;
228
229 static struct trace *trace_list;
230
231 /*
232  * allocation cache
233  */
234 static struct blk_io_trace *bit_alloc_list;
235 static struct trace *t_alloc_list;
236
237 /*
238  * for tracking individual ios
239  */
240 struct io_track {
241         struct rb_node rb_node;
242
243         struct process_pid_map *ppm;
244         __u64 sector;
245         unsigned long long allocation_time;
246         unsigned long long queue_time;
247         unsigned long long dispatch_time;
248         unsigned long long completion_time;
249 };
250
251 static int ndevices;
252 static struct per_dev_info *devices;
253 static char *get_dev_name(struct per_dev_info *, char *, int);
254 static int trace_rb_insert_last(struct per_dev_info *, struct trace *);
255
256 FILE *ofp = NULL;
257 static char *output_name;
258 static char *input_dir;
259
260 static unsigned long long genesis_time;
261 static unsigned long long last_allowed_time;
262 static unsigned long long stopwatch_start;      /* start from zero by default */
263 static unsigned long long stopwatch_end = -1ULL;        /* "infinity" */
264 static unsigned long read_sequence;
265
266 static int per_process_stats;
267 static int per_device_and_cpu_stats = 1;
268 static int track_ios;
269 static int ppi_hash_by_pid = 1;
270 static int verbose;
271 static unsigned int act_mask = -1U;
272 static int stats_printed;
273 int data_is_native = -1;
274
275 static FILE *dump_fp;
276 static char *dump_binary;
277
278 static unsigned int t_alloc_cache;
279 static unsigned int bit_alloc_cache;
280
281 #define RB_BATCH_DEFAULT        (512)
282 static unsigned int rb_batch = RB_BATCH_DEFAULT;
283
284 static int pipeline;
285
286 static int text_output = 1;
287
288 #define is_done()       (*(volatile int *)(&done))
289 static volatile int done;
290
291 struct timespec         abs_start_time;
292 static unsigned long long start_timestamp;
293
294 #define JHASH_RANDOM    (0x3af5f2ee)
295
296 #define CPUS_PER_LONG   (8 * sizeof(unsigned long))
297 #define CPU_IDX(cpu)    ((cpu) / CPUS_PER_LONG)
298 #define CPU_BIT(cpu)    ((cpu) & (CPUS_PER_LONG - 1))
299
300 static void output_binary(void *buf, int len)
301 {
302         if (dump_binary) {
303                 size_t n = fwrite(buf, len, 1, dump_fp);
304                 if (n != 1) {
305                         perror(dump_binary);
306                         fclose(dump_fp);
307                         dump_binary = NULL;
308                 }
309         }
310 }
311
312 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
313 {
314         struct per_cpu_info *cpus = pdi->cpus;
315         int ncpus = pdi->ncpus;
316         int new_count = cpu + 1;
317         int new_space, size;
318         char *new_start;
319
320         size = new_count * sizeof(struct per_cpu_info);
321         cpus = realloc(cpus, size);
322         if (!cpus) {
323                 char name[20];
324                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
325                         get_dev_name(pdi, name, sizeof(name)), size);
326                 exit(1);
327         }
328
329         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
330         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
331         memset(new_start, 0, new_space);
332
333         pdi->ncpus = new_count;
334         pdi->cpus = cpus;
335
336         for (new_count = 0; new_count < pdi->ncpus; new_count++) {
337                 struct per_cpu_info *pci = &pdi->cpus[new_count];
338
339                 if (!pci->fd) {
340                         pci->fd = -1;
341                         memset(&pci->rb_last, 0, sizeof(pci->rb_last));
342                         pci->rb_last_entries = 0;
343                         pci->last_sequence = -1;
344                 }
345         }
346 }
347
348 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
349 {
350         struct per_cpu_info *pci;
351
352         if (cpu >= pdi->ncpus)
353                 resize_cpu_info(pdi, cpu);
354
355         pci = &pdi->cpus[cpu];
356         pci->cpu = cpu;
357         return pci;
358 }
359
360
361 static int resize_devices(char *name)
362 {
363         int size = (ndevices + 1) * sizeof(struct per_dev_info);
364
365         devices = realloc(devices, size);
366         if (!devices) {
367                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
368                 return 1;
369         }
370         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
371         devices[ndevices].name = name;
372         ndevices++;
373         return 0;
374 }
375
376 static struct per_dev_info *get_dev_info(dev_t dev)
377 {
378         struct per_dev_info *pdi;
379         int i;
380
381         for (i = 0; i < ndevices; i++) {
382                 if (!devices[i].dev)
383                         devices[i].dev = dev;
384                 if (devices[i].dev == dev)
385                         return &devices[i];
386         }
387
388         if (resize_devices(NULL))
389                 return NULL;
390
391         pdi = &devices[ndevices - 1];
392         pdi->dev = dev;
393         pdi->first_reported_time = 0;
394         pdi->last_read_time = 0;
395
396         return pdi;
397 }
398
399 static void insert_skip(struct per_cpu_info *pci, unsigned long start,
400                         unsigned long end)
401 {
402         struct skip_info *sip;
403
404         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
405                 if (end == (sip->start - 1)) {
406                         sip->start = start;
407                         return;
408                 } else if (start == (sip->end + 1)) {
409                         sip->end = end;
410                         return;
411                 }
412         }
413
414         sip = malloc(sizeof(struct skip_info));
415         sip->start = start;
416         sip->end = end;
417         sip->prev = sip->next = NULL;
418         if (pci->skips_tail == NULL)
419                 pci->skips_head = pci->skips_tail = sip;
420         else {
421                 sip->prev = pci->skips_tail;
422                 pci->skips_tail->next = sip;
423                 pci->skips_tail = sip;
424         }
425 }
426
427 static void remove_sip(struct per_cpu_info *pci, struct skip_info *sip)
428 {
429         if (sip->prev == NULL) {
430                 if (sip->next == NULL)
431                         pci->skips_head = pci->skips_tail = NULL;
432                 else {
433                         pci->skips_head = sip->next;
434                         sip->next->prev = NULL;
435                 }
436         } else if (sip->next == NULL) {
437                 pci->skips_tail = sip->prev;
438                 sip->prev->next = NULL;
439         } else {
440                 sip->prev->next = sip->next;
441                 sip->next->prev = sip->prev;
442         }
443
444         sip->prev = sip->next = NULL;
445         free(sip);
446 }
447
448 #define IN_SKIP(sip,seq) (((sip)->start <= (seq)) && ((seq) <= sip->end))
449 static int check_current_skips(struct per_cpu_info *pci, unsigned long seq)
450 {
451         struct skip_info *sip;
452
453         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
454                 if (IN_SKIP(sip, seq)) {
455                         if (sip->start == seq) {
456                                 if (sip->end == seq)
457                                         remove_sip(pci, sip);
458                                 else
459                                         sip->start += 1;
460                         } else if (sip->end == seq)
461                                 sip->end -= 1;
462                         else {
463                                 sip->end = seq - 1;
464                                 insert_skip(pci, seq + 1, sip->end);
465                         }
466                         return 1;
467                 }
468         }
469
470         return 0;
471 }
472
473 static void collect_pdi_skips(struct per_dev_info *pdi)
474 {
475         struct skip_info *sip;
476         int cpu;
477
478         pdi->skips = 0;
479         pdi->seq_skips = 0;
480
481         for (cpu = 0; cpu < pdi->ncpus; cpu++) {
482                 struct per_cpu_info *pci = &pdi->cpus[cpu];
483
484                 for (sip = pci->skips_head; sip != NULL; sip = sip->next) {
485                         pdi->skips++;
486                         pdi->seq_skips += (sip->end - sip->start + 1);
487                         if (verbose)
488                                 fprintf(stderr,"(%d,%d): skipping %lu -> %lu\n",
489                                         MAJOR(pdi->dev), MINOR(pdi->dev),
490                                         sip->start, sip->end);
491                 }
492         }
493 }
494
495 static void cpu_mark_online(struct per_dev_info *pdi, unsigned int cpu)
496 {
497         if (cpu >= pdi->cpu_map_max || !pdi->cpu_map) {
498                 int new_max = (cpu + CPUS_PER_LONG) & ~(CPUS_PER_LONG - 1);
499                 unsigned long *map = malloc(new_max / sizeof(long));
500
501                 memset(map, 0, new_max / sizeof(long));
502
503                 if (pdi->cpu_map) {
504                         memcpy(map, pdi->cpu_map, pdi->cpu_map_max / sizeof(long));
505                         free(pdi->cpu_map);
506                 }
507
508                 pdi->cpu_map = map;
509                 pdi->cpu_map_max = new_max;
510         }
511
512         pdi->cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
513 }
514
515 static inline void cpu_mark_offline(struct per_dev_info *pdi, int cpu)
516 {
517         pdi->cpu_map[CPU_IDX(cpu)] &= ~(1UL << CPU_BIT(cpu));
518 }
519
520 static inline int cpu_is_online(struct per_dev_info *pdi, int cpu)
521 {
522         return (pdi->cpu_map[CPU_IDX(cpu)] & (1UL << CPU_BIT(cpu))) != 0;
523 }
524
525 static inline int ppm_hash_pid(pid_t pid)
526 {
527         return jhash_1word(pid, JHASH_RANDOM) & PPM_HASH_MASK;
528 }
529
530 static struct process_pid_map *find_ppm(pid_t pid)
531 {
532         const int hash_idx = ppm_hash_pid(pid);
533         struct process_pid_map *ppm;
534
535         ppm = ppm_hash_table[hash_idx];
536         while (ppm) {
537                 if (ppm->pid == pid)
538                         return ppm;
539
540                 ppm = ppm->hash_next;
541         }
542
543         return NULL;
544 }
545
546 static void add_ppm_hash(pid_t pid, const char *name)
547 {
548         const int hash_idx = ppm_hash_pid(pid);
549         struct process_pid_map *ppm;
550
551         ppm = find_ppm(pid);
552         if (!ppm) {
553                 ppm = malloc(sizeof(*ppm));
554                 memset(ppm, 0, sizeof(*ppm));
555                 ppm->pid = pid;
556                 strcpy(ppm->comm, name);
557                 ppm->hash_next = ppm_hash_table[hash_idx];
558                 ppm_hash_table[hash_idx] = ppm;
559         }
560 }
561
562 static void handle_notify(struct blk_io_trace *bit)
563 {
564         void    *payload = (caddr_t) bit + sizeof(*bit);
565         __u32   two32[2];
566
567         switch (bit->action) {
568         case BLK_TN_PROCESS:
569                 add_ppm_hash(bit->pid, payload);
570                 break;
571
572         case BLK_TN_TIMESTAMP:
573                 if (bit->pdu_len != sizeof(two32))
574                         return;
575                 memcpy(two32, payload, sizeof(two32));
576                 if (!data_is_native) {
577                         two32[0] = be32_to_cpu(two32[0]);
578                         two32[1] = be32_to_cpu(two32[1]);
579                 }
580                 start_timestamp = bit->time;
581                 abs_start_time.tv_sec  = two32[0];
582                 abs_start_time.tv_nsec = two32[1];
583                 if (abs_start_time.tv_nsec < 0) {
584                         abs_start_time.tv_sec--;
585                         abs_start_time.tv_nsec += 1000000000;
586                 }
587
588                 break;
589
590         default:
591                 /* Ignore unknown notify events */
592                 ;
593         }
594 }
595
596 char *find_process_name(pid_t pid)
597 {
598         struct process_pid_map *ppm = find_ppm(pid);
599
600         if (ppm)
601                 return ppm->comm;
602
603         return NULL;
604 }
605
606 static inline int ppi_hash_pid(pid_t pid)
607 {
608         return jhash_1word(pid, JHASH_RANDOM) & PPI_HASH_MASK;
609 }
610
611 static inline int ppi_hash_name(const char *name)
612 {
613         return jhash(name, 16, JHASH_RANDOM) & PPI_HASH_MASK;
614 }
615
616 static inline int ppi_hash(struct per_process_info *ppi)
617 {
618         struct process_pid_map *ppm = ppi->ppm;
619
620         if (ppi_hash_by_pid)
621                 return ppi_hash_pid(ppm->pid);
622
623         return ppi_hash_name(ppm->comm);
624 }
625
626 static inline void add_ppi_to_hash(struct per_process_info *ppi)
627 {
628         const int hash_idx = ppi_hash(ppi);
629
630         ppi->hash_next = ppi_hash_table[hash_idx];
631         ppi_hash_table[hash_idx] = ppi;
632 }
633
634 static inline void add_ppi_to_list(struct per_process_info *ppi)
635 {
636         ppi->list_next = ppi_list;
637         ppi_list = ppi;
638         ppi_list_entries++;
639 }
640
641 static struct per_process_info *find_ppi_by_name(char *name)
642 {
643         const int hash_idx = ppi_hash_name(name);
644         struct per_process_info *ppi;
645
646         ppi = ppi_hash_table[hash_idx];
647         while (ppi) {
648                 struct process_pid_map *ppm = ppi->ppm;
649
650                 if (!strcmp(ppm->comm, name))
651                         return ppi;
652
653                 ppi = ppi->hash_next;
654         }
655
656         return NULL;
657 }
658
659 static struct per_process_info *find_ppi_by_pid(pid_t pid)
660 {
661         const int hash_idx = ppi_hash_pid(pid);
662         struct per_process_info *ppi;
663
664         ppi = ppi_hash_table[hash_idx];
665         while (ppi) {
666                 struct process_pid_map *ppm = ppi->ppm;
667
668                 if (ppm->pid == pid)
669                         return ppi;
670
671                 ppi = ppi->hash_next;
672         }
673
674         return NULL;
675 }
676
677 static struct per_process_info *find_ppi(pid_t pid)
678 {
679         struct per_process_info *ppi;
680         char *name;
681
682         if (ppi_hash_by_pid)
683                 return find_ppi_by_pid(pid);
684
685         name = find_process_name(pid);
686         if (!name)
687                 return NULL;
688
689         ppi = find_ppi_by_name(name);
690         if (ppi && ppi->ppm->pid != pid)
691                 ppi->more_than_one = 1;
692
693         return ppi;
694 }
695
696 /*
697  * struct trace and blktrace allocation cache, we do potentially
698  * millions of mallocs for these structures while only using at most
699  * a few thousand at the time
700  */
701 static inline void t_free(struct trace *t)
702 {
703         if (t_alloc_cache < 1024) {
704                 t->next = t_alloc_list;
705                 t_alloc_list = t;
706                 t_alloc_cache++;
707         } else
708                 free(t);
709 }
710
711 static inline struct trace *t_alloc(void)
712 {
713         struct trace *t = t_alloc_list;
714
715         if (t) {
716                 t_alloc_list = t->next;
717                 t_alloc_cache--;
718                 return t;
719         }
720
721         return malloc(sizeof(*t));
722 }
723
724 static inline void bit_free(struct blk_io_trace *bit)
725 {
726         if (bit_alloc_cache < 1024 && !bit->pdu_len) {
727                 /*
728                  * abuse a 64-bit field for a next pointer for the free item
729                  */
730                 bit->time = (__u64) (unsigned long) bit_alloc_list;
731                 bit_alloc_list = (struct blk_io_trace *) bit;
732                 bit_alloc_cache++;
733         } else
734                 free(bit);
735 }
736
737 static inline struct blk_io_trace *bit_alloc(void)
738 {
739         struct blk_io_trace *bit = bit_alloc_list;
740
741         if (bit) {
742                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
743                                  bit->time;
744                 bit_alloc_cache--;
745                 return bit;
746         }
747
748         return malloc(sizeof(*bit));
749 }
750
751 static inline void __put_trace_last(struct per_dev_info *pdi, struct trace *t)
752 {
753         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
754
755         rb_erase(&t->rb_node, &pci->rb_last);
756         pci->rb_last_entries--;
757
758         bit_free(t->bit);
759         t_free(t);
760 }
761
762 static void put_trace(struct per_dev_info *pdi, struct trace *t)
763 {
764         rb_erase(&t->rb_node, &rb_sort_root);
765         rb_sort_entries--;
766
767         trace_rb_insert_last(pdi, t);
768 }
769
770 static inline int trace_rb_insert(struct trace *t, struct rb_root *root)
771 {
772         struct rb_node **p = &root->rb_node;
773         struct rb_node *parent = NULL;
774         struct trace *__t;
775
776         while (*p) {
777                 parent = *p;
778
779                 __t = rb_entry(parent, struct trace, rb_node);
780
781                 if (t->bit->time < __t->bit->time)
782                         p = &(*p)->rb_left;
783                 else if (t->bit->time > __t->bit->time)
784                         p = &(*p)->rb_right;
785                 else if (t->bit->device < __t->bit->device)
786                         p = &(*p)->rb_left;
787                 else if (t->bit->device > __t->bit->device)
788                         p = &(*p)->rb_right;
789                 else if (t->bit->sequence < __t->bit->sequence)
790                         p = &(*p)->rb_left;
791                 else    /* >= sequence */
792                         p = &(*p)->rb_right;
793         }
794
795         rb_link_node(&t->rb_node, parent, p);
796         rb_insert_color(&t->rb_node, root);
797         return 0;
798 }
799
800 static inline int trace_rb_insert_sort(struct trace *t)
801 {
802         if (!trace_rb_insert(t, &rb_sort_root)) {
803                 rb_sort_entries++;
804                 return 0;
805         }
806
807         return 1;
808 }
809
810 static int trace_rb_insert_last(struct per_dev_info *pdi, struct trace *t)
811 {
812         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
813
814         if (trace_rb_insert(t, &pci->rb_last))
815                 return 1;
816
817         pci->rb_last_entries++;
818
819         if (pci->rb_last_entries > rb_batch * pdi->nfiles) {
820                 struct rb_node *n = rb_first(&pci->rb_last);
821
822                 t = rb_entry(n, struct trace, rb_node);
823                 __put_trace_last(pdi, t);
824         }
825
826         return 0;
827 }
828
829 static struct trace *trace_rb_find(dev_t device, unsigned long sequence,
830                                    struct rb_root *root, int order)
831 {
832         struct rb_node *n = root->rb_node;
833         struct rb_node *prev = NULL;
834         struct trace *__t;
835
836         while (n) {
837                 __t = rb_entry(n, struct trace, rb_node);
838                 prev = n;
839
840                 if (device < __t->bit->device)
841                         n = n->rb_left;
842                 else if (device > __t->bit->device)
843                         n = n->rb_right;
844                 else if (sequence < __t->bit->sequence)
845                         n = n->rb_left;
846                 else if (sequence > __t->bit->sequence)
847                         n = n->rb_right;
848                 else
849                         return __t;
850         }
851
852         /*
853          * hack - the list may not be sequence ordered because some
854          * events don't have sequence and time matched. so we end up
855          * being a little off in the rb lookup here, because we don't
856          * know the time we are looking for. compensate by browsing
857          * a little ahead from the last entry to find the match
858          */
859         if (order && prev) {
860                 int max = 5;
861
862                 while (((n = rb_next(prev)) != NULL) && max--) {
863                         __t = rb_entry(n, struct trace, rb_node);
864
865                         if (__t->bit->device == device &&
866                             __t->bit->sequence == sequence)
867                                 return __t;
868
869                         prev = n;
870                 }
871         }
872
873         return NULL;
874 }
875
876 static inline struct trace *trace_rb_find_last(struct per_dev_info *pdi,
877                                                struct per_cpu_info *pci,
878                                                unsigned long seq)
879 {
880         return trace_rb_find(pdi->dev, seq, &pci->rb_last, 0);
881 }
882
883 static inline int track_rb_insert(struct per_dev_info *pdi,struct io_track *iot)
884 {
885         struct rb_node **p = &pdi->rb_track.rb_node;
886         struct rb_node *parent = NULL;
887         struct io_track *__iot;
888
889         while (*p) {
890                 parent = *p;
891                 __iot = rb_entry(parent, struct io_track, rb_node);
892
893                 if (iot->sector < __iot->sector)
894                         p = &(*p)->rb_left;
895                 else if (iot->sector > __iot->sector)
896                         p = &(*p)->rb_right;
897                 else {
898                         fprintf(stderr,
899                                 "sector alias (%Lu) on device %d,%d!\n",
900                                 (unsigned long long) iot->sector,
901                                 MAJOR(pdi->dev), MINOR(pdi->dev));
902                         return 1;
903                 }
904         }
905
906         rb_link_node(&iot->rb_node, parent, p);
907         rb_insert_color(&iot->rb_node, &pdi->rb_track);
908         return 0;
909 }
910
911 static struct io_track *__find_track(struct per_dev_info *pdi, __u64 sector)
912 {
913         struct rb_node *n = pdi->rb_track.rb_node;
914         struct io_track *__iot;
915
916         while (n) {
917                 __iot = rb_entry(n, struct io_track, rb_node);
918
919                 if (sector < __iot->sector)
920                         n = n->rb_left;
921                 else if (sector > __iot->sector)
922                         n = n->rb_right;
923                 else
924                         return __iot;
925         }
926
927         return NULL;
928 }
929
930 static struct io_track *find_track(struct per_dev_info *pdi, pid_t pid,
931                                    __u64 sector)
932 {
933         struct io_track *iot;
934
935         iot = __find_track(pdi, sector);
936         if (!iot) {
937                 iot = malloc(sizeof(*iot));
938                 iot->ppm = find_ppm(pid);
939                 iot->sector = sector;
940                 track_rb_insert(pdi, iot);
941         }
942
943         return iot;
944 }
945
946 static void log_track_frontmerge(struct per_dev_info *pdi,
947                                  struct blk_io_trace *t)
948 {
949         struct io_track *iot;
950
951         if (!track_ios)
952                 return;
953
954         iot = __find_track(pdi, t->sector + t_sec(t));
955         if (!iot) {
956                 if (verbose)
957                         fprintf(stderr, "merge not found for (%d,%d): %llu\n",
958                                 MAJOR(pdi->dev), MINOR(pdi->dev),
959                                 (unsigned long long) t->sector + t_sec(t));
960                 return;
961         }
962
963         rb_erase(&iot->rb_node, &pdi->rb_track);
964         iot->sector -= t_sec(t);
965         track_rb_insert(pdi, iot);
966 }
967
968 static void log_track_getrq(struct per_dev_info *pdi, struct blk_io_trace *t)
969 {
970         struct io_track *iot;
971
972         if (!track_ios)
973                 return;
974
975         iot = find_track(pdi, t->pid, t->sector);
976         iot->allocation_time = t->time;
977 }
978
979 static inline int is_remapper(struct per_dev_info *pdi)
980 {
981         int major = MAJOR(pdi->dev);
982
983         return (major == 253 || major == 9);
984 }
985
986 /*
987  * for md/dm setups, the interesting cycle is Q -> C. So track queueing
988  * time here, as dispatch time
989  */
990 static void log_track_queue(struct per_dev_info *pdi, struct blk_io_trace *t)
991 {
992         struct io_track *iot;
993
994         if (!track_ios)
995                 return;
996         if (!is_remapper(pdi))
997                 return;
998
999         iot = find_track(pdi, t->pid, t->sector);
1000         iot->dispatch_time = t->time;
1001 }
1002
1003 /*
1004  * return time between rq allocation and insertion
1005  */
1006 static unsigned long long log_track_insert(struct per_dev_info *pdi,
1007                                            struct blk_io_trace *t)
1008 {
1009         unsigned long long elapsed;
1010         struct io_track *iot;
1011
1012         if (!track_ios)
1013                 return -1;
1014
1015         iot = find_track(pdi, t->pid, t->sector);
1016         iot->queue_time = t->time;
1017
1018         if (!iot->allocation_time)
1019                 return -1;
1020
1021         elapsed = iot->queue_time - iot->allocation_time;
1022
1023         if (per_process_stats) {
1024                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1025                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1026
1027                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
1028                         ppi->longest_allocation_wait[w] = elapsed;
1029         }
1030
1031         return elapsed;
1032 }
1033
1034 /*
1035  * return time between queue and issue
1036  */
1037 static unsigned long long log_track_issue(struct per_dev_info *pdi,
1038                                           struct blk_io_trace *t)
1039 {
1040         unsigned long long elapsed;
1041         struct io_track *iot;
1042
1043         if (!track_ios)
1044                 return -1;
1045         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
1046                 return -1;
1047
1048         iot = __find_track(pdi, t->sector);
1049         if (!iot) {
1050                 if (verbose)
1051                         fprintf(stderr, "issue not found for (%d,%d): %llu\n",
1052                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1053                                 (unsigned long long) t->sector);
1054                 return -1;
1055         }
1056
1057         iot->dispatch_time = t->time;
1058         elapsed = iot->dispatch_time - iot->queue_time;
1059
1060         if (per_process_stats) {
1061                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1062                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1063
1064                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
1065                         ppi->longest_dispatch_wait[w] = elapsed;
1066         }
1067
1068         return elapsed;
1069 }
1070
1071 /*
1072  * return time between dispatch and complete
1073  */
1074 static unsigned long long log_track_complete(struct per_dev_info *pdi,
1075                                              struct blk_io_trace *t)
1076 {
1077         unsigned long long elapsed;
1078         struct io_track *iot;
1079
1080         if (!track_ios)
1081                 return -1;
1082
1083         iot = __find_track(pdi, t->sector);
1084         if (!iot) {
1085                 if (verbose)
1086                         fprintf(stderr,"complete not found for (%d,%d): %llu\n",
1087                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1088                                 (unsigned long long) t->sector);
1089                 return -1;
1090         }
1091
1092         iot->completion_time = t->time;
1093         elapsed = iot->completion_time - iot->dispatch_time;
1094
1095         if (per_process_stats) {
1096                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1097                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1098
1099                 if (ppi && elapsed > ppi->longest_completion_wait[w])
1100                         ppi->longest_completion_wait[w] = elapsed;
1101         }
1102
1103         /*
1104          * kill the trace, we don't need it after completion
1105          */
1106         rb_erase(&iot->rb_node, &pdi->rb_track);
1107         free(iot);
1108
1109         return elapsed;
1110 }
1111
1112
1113 static struct io_stats *find_process_io_stats(pid_t pid)
1114 {
1115         struct per_process_info *ppi = find_ppi(pid);
1116
1117         if (!ppi) {
1118                 ppi = malloc(sizeof(*ppi));
1119                 memset(ppi, 0, sizeof(*ppi));
1120                 ppi->ppm = find_ppm(pid);
1121                 add_ppi_to_hash(ppi);
1122                 add_ppi_to_list(ppi);
1123         }
1124
1125         return &ppi->io_stats;
1126 }
1127
1128 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
1129 {
1130         if (pdi->name)
1131                 snprintf(buffer, size, "%s", pdi->name);
1132         else
1133                 snprintf(buffer, size, "%d,%d",MAJOR(pdi->dev),MINOR(pdi->dev));
1134         return buffer;
1135 }
1136
1137 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
1138 {
1139         unsigned long long this = bit->time;
1140         unsigned long long last = pdi->last_reported_time;
1141
1142         pdi->backwards = (this < last) ? 'B' : ' ';
1143         pdi->last_reported_time = this;
1144 }
1145
1146 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
1147                                int rw)
1148 {
1149         if (rw) {
1150                 ios->mwrites++;
1151                 ios->qwrite_kb += t_kb(t);
1152         } else {
1153                 ios->mreads++;
1154                 ios->qread_kb += t_kb(t);
1155         }
1156 }
1157
1158 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
1159                              int rw)
1160 {
1161         __account_m(&pci->io_stats, t, rw);
1162
1163         if (per_process_stats) {
1164                 struct io_stats *ios = find_process_io_stats(t->pid);
1165
1166                 __account_m(ios, t, rw);
1167         }
1168 }
1169
1170 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
1171                                    int rw)
1172 {
1173         if (rw) {
1174                 ios->qwrites++;
1175                 ios->qwrite_kb += t_kb(t);
1176         } else {
1177                 ios->qreads++;
1178                 ios->qread_kb += t_kb(t);
1179         }
1180 }
1181
1182 static inline void account_queue(struct blk_io_trace *t,
1183                                  struct per_cpu_info *pci, int rw)
1184 {
1185         __account_queue(&pci->io_stats, t, rw);
1186
1187         if (per_process_stats) {
1188                 struct io_stats *ios = find_process_io_stats(t->pid);
1189
1190                 __account_queue(ios, t, rw);
1191         }
1192 }
1193
1194 static inline void __account_c(struct io_stats *ios, int rw, int bytes)
1195 {
1196         if (rw) {
1197                 ios->cwrites++;
1198                 ios->cwrite_kb += bytes >> 10;
1199         } else {
1200                 ios->creads++;
1201                 ios->cread_kb += bytes >> 10;
1202         }
1203 }
1204
1205 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
1206                              int rw, int bytes)
1207 {
1208         __account_c(&pci->io_stats, rw, bytes);
1209
1210         if (per_process_stats) {
1211                 struct io_stats *ios = find_process_io_stats(t->pid);
1212
1213                 __account_c(ios, rw, bytes);
1214         }
1215 }
1216
1217 static inline void __account_issue(struct io_stats *ios, int rw,
1218                                    unsigned int bytes)
1219 {
1220         if (rw) {
1221                 ios->iwrites++;
1222                 ios->iwrite_kb += bytes >> 10;
1223         } else {
1224                 ios->ireads++;
1225                 ios->iread_kb += bytes >> 10;
1226         }
1227 }
1228
1229 static inline void account_issue(struct blk_io_trace *t,
1230                                  struct per_cpu_info *pci, int rw)
1231 {
1232         __account_issue(&pci->io_stats, rw, t->bytes);
1233
1234         if (per_process_stats) {
1235                 struct io_stats *ios = find_process_io_stats(t->pid);
1236
1237                 __account_issue(ios, rw, t->bytes);
1238         }
1239 }
1240
1241 static inline void __account_unplug(struct io_stats *ios, int timer)
1242 {
1243         if (timer)
1244                 ios->timer_unplugs++;
1245         else
1246                 ios->io_unplugs++;
1247 }
1248
1249 static inline void account_unplug(struct blk_io_trace *t,
1250                                   struct per_cpu_info *pci, int timer)
1251 {
1252         __account_unplug(&pci->io_stats, timer);
1253
1254         if (per_process_stats) {
1255                 struct io_stats *ios = find_process_io_stats(t->pid);
1256
1257                 __account_unplug(ios, timer);
1258         }
1259 }
1260
1261 static inline void __account_requeue(struct io_stats *ios,
1262                                      struct blk_io_trace *t, int rw)
1263 {
1264         if (rw) {
1265                 ios->wrqueue++;
1266                 ios->iwrite_kb -= t_kb(t);
1267         } else {
1268                 ios->rrqueue++;
1269                 ios->iread_kb -= t_kb(t);
1270         }
1271 }
1272
1273 static inline void account_requeue(struct blk_io_trace *t,
1274                                    struct per_cpu_info *pci, int rw)
1275 {
1276         __account_requeue(&pci->io_stats, t, rw);
1277
1278         if (per_process_stats) {
1279                 struct io_stats *ios = find_process_io_stats(t->pid);
1280
1281                 __account_requeue(ios, t, rw);
1282         }
1283 }
1284
1285 static void log_complete(struct per_dev_info *pdi, struct per_cpu_info *pci,
1286                          struct blk_io_trace *t, char *act)
1287 {
1288         process_fmt(act, pci, t, log_track_complete(pdi, t), 0, NULL);
1289 }
1290
1291 static void log_insert(struct per_dev_info *pdi, struct per_cpu_info *pci,
1292                        struct blk_io_trace *t, char *act)
1293 {
1294         process_fmt(act, pci, t, log_track_insert(pdi, t), 0, NULL);
1295 }
1296
1297 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
1298                       char *act)
1299 {
1300         process_fmt(act, pci, t, -1, 0, NULL);
1301 }
1302
1303 static void log_issue(struct per_dev_info *pdi, struct per_cpu_info *pci,
1304                       struct blk_io_trace *t, char *act)
1305 {
1306         process_fmt(act, pci, t, log_track_issue(pdi, t), 0, NULL);
1307 }
1308
1309 static void log_merge(struct per_dev_info *pdi, struct per_cpu_info *pci,
1310                       struct blk_io_trace *t, char *act)
1311 {
1312         if (act[0] == 'F')
1313                 log_track_frontmerge(pdi, t);
1314
1315         process_fmt(act, pci, t, -1ULL, 0, NULL);
1316 }
1317
1318 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
1319                         char *act)
1320 {
1321         process_fmt(act, pci, t, -1ULL, 0, NULL);
1322 }
1323
1324 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
1325                         char *act)
1326 {
1327         process_fmt(act, pci, t, -1ULL, 0, NULL);
1328 }
1329
1330 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
1331                       char *act)
1332 {
1333         process_fmt(act, pci, t, -1ULL, 0, NULL);
1334 }
1335
1336 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
1337                       char *act)
1338 {
1339         process_fmt(act, pci, t, -1ULL, 0, NULL);
1340 }
1341
1342 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
1343 {
1344         unsigned char *buf = (unsigned char *) t + sizeof(*t);
1345
1346         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
1347 }
1348
1349 static void dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
1350 {
1351         int act = t->action & 0xffff;
1352
1353         switch (act) {
1354                 case __BLK_TA_QUEUE:
1355                         log_generic(pci, t, "Q");
1356                         break;
1357                 case __BLK_TA_GETRQ:
1358                         log_generic(pci, t, "G");
1359                         break;
1360                 case __BLK_TA_SLEEPRQ:
1361                         log_generic(pci, t, "S");
1362                         break;
1363                 case __BLK_TA_REQUEUE:
1364                         log_generic(pci, t, "R");
1365                         break;
1366                 case __BLK_TA_ISSUE:
1367                         log_pc(pci, t, "D");
1368                         break;
1369                 case __BLK_TA_COMPLETE:
1370                         log_pc(pci, t, "C");
1371                         break;
1372                 case __BLK_TA_INSERT:
1373                         log_pc(pci, t, "I");
1374                         break;
1375                 default:
1376                         fprintf(stderr, "Bad pc action %x\n", act);
1377                         break;
1378         }
1379 }
1380
1381 static void dump_trace_fs(struct blk_io_trace *t, struct per_dev_info *pdi,
1382                           struct per_cpu_info *pci)
1383 {
1384         int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1385         int act = t->action & 0xffff;
1386
1387         switch (act) {
1388                 case __BLK_TA_QUEUE:
1389                         log_track_queue(pdi, t);
1390                         account_queue(t, pci, w);
1391                         log_queue(pci, t, "Q");
1392                         break;
1393                 case __BLK_TA_INSERT:
1394                         log_insert(pdi, pci, t, "I");
1395                         break;
1396                 case __BLK_TA_BACKMERGE:
1397                         account_m(t, pci, w);
1398                         log_merge(pdi, pci, t, "M");
1399                         break;
1400                 case __BLK_TA_FRONTMERGE:
1401                         account_m(t, pci, w);
1402                         log_merge(pdi, pci, t, "F");
1403                         break;
1404                 case __BLK_TA_GETRQ:
1405                         log_track_getrq(pdi, t);
1406                         log_generic(pci, t, "G");
1407                         break;
1408                 case __BLK_TA_SLEEPRQ:
1409                         log_generic(pci, t, "S");
1410                         break;
1411                 case __BLK_TA_REQUEUE:
1412                         /*
1413                          * can happen if we miss traces, don't let it go
1414                          * below zero
1415                          */
1416                         if (pdi->cur_depth[w])
1417                                 pdi->cur_depth[w]--;
1418                         account_requeue(t, pci, w);
1419                         log_queue(pci, t, "R");
1420                         break;
1421                 case __BLK_TA_ISSUE:
1422                         account_issue(t, pci, w);
1423                         pdi->cur_depth[w]++;
1424                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1425                                 pdi->max_depth[w] = pdi->cur_depth[w];
1426                         log_issue(pdi, pci, t, "D");
1427                         break;
1428                 case __BLK_TA_COMPLETE:
1429                         if (pdi->cur_depth[w])
1430                                 pdi->cur_depth[w]--;
1431                         account_c(t, pci, w, t->bytes);
1432                         log_complete(pdi, pci, t, "C");
1433                         break;
1434                 case __BLK_TA_PLUG:
1435                         log_action(pci, t, "P");
1436                         break;
1437                 case __BLK_TA_UNPLUG_IO:
1438                         account_unplug(t, pci, 0);
1439                         log_unplug(pci, t, "U");
1440                         break;
1441                 case __BLK_TA_UNPLUG_TIMER:
1442                         account_unplug(t, pci, 1);
1443                         log_unplug(pci, t, "UT");
1444                         break;
1445                 case __BLK_TA_SPLIT:
1446                         log_split(pci, t, "X");
1447                         break;
1448                 case __BLK_TA_BOUNCE:
1449                         log_generic(pci, t, "B");
1450                         break;
1451                 case __BLK_TA_REMAP:
1452                         log_generic(pci, t, "A");
1453                         break;
1454                 default:
1455                         fprintf(stderr, "Bad fs action %x\n", t->action);
1456                         break;
1457         }
1458 }
1459
1460 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1461                        struct per_dev_info *pdi)
1462 {
1463         if (text_output) {
1464                 if (t->action & BLK_TC_ACT(BLK_TC_PC))
1465                         dump_trace_pc(t, pci);
1466                 else
1467                         dump_trace_fs(t, pdi, pci);
1468         }
1469
1470         if (!pdi->events)
1471                 pdi->first_reported_time = t->time;
1472
1473         pdi->events++;
1474
1475         output_binary(t, sizeof(*t) + t->pdu_len);
1476 }
1477
1478 /*
1479  * print in a proper way, not too small and not too big. if more than
1480  * 1000,000K, turn into M and so on
1481  */
1482 static char *size_cnv(char *dst, unsigned long long num, int in_kb)
1483 {
1484         char suff[] = { '\0', 'K', 'M', 'G', 'P' };
1485         unsigned int i = 0;
1486
1487         if (in_kb)
1488                 i++;
1489
1490         while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
1491                 i++;
1492                 num /= 1000;
1493         }
1494
1495         sprintf(dst, "%'8Lu%c", num, suff[i]);
1496         return dst;
1497 }
1498
1499 static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
1500                           char *msg)
1501 {
1502         static char x[256], y[256];
1503
1504         fprintf(ofp, "%s\n", msg);
1505
1506         fprintf(ofp, " Reads Queued:    %s, %siB\t", size_cnv(x, ios->qreads, 0), size_cnv(y, ios->qread_kb, 1));
1507         fprintf(ofp, " Writes Queued:    %s, %siB\n", size_cnv(x, ios->qwrites, 0), size_cnv(y, ios->qwrite_kb, 1));
1508
1509         fprintf(ofp, " Read Dispatches: %s, %siB\t", size_cnv(x, ios->ireads, 0), size_cnv(y, ios->iread_kb, 1));
1510         fprintf(ofp, " Write Dispatches: %s, %siB\n", size_cnv(x, ios->iwrites, 0), size_cnv(y, ios->iwrite_kb, 1));
1511         fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
1512         fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
1513         fprintf(ofp, " Reads Completed: %s, %siB\t", size_cnv(x, ios->creads, 0), size_cnv(y, ios->cread_kb, 1));
1514         fprintf(ofp, " Writes Completed: %s, %siB\n", size_cnv(x, ios->cwrites, 0), size_cnv(y, ios->cwrite_kb, 1));
1515         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
1516         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
1517         if (pdi) {
1518                 fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
1519                 fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
1520         }
1521         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1522         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1523 }
1524
1525 static void dump_wait_stats(struct per_process_info *ppi)
1526 {
1527         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1528         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1529         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1530         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1531         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1532         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1533
1534         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1535         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1536         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1537         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1538         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1539         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1540 }
1541
1542 static int ppi_name_compare(const void *p1, const void *p2)
1543 {
1544         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1545         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1546         int res;
1547
1548         res = strverscmp(ppi1->ppm->comm, ppi2->ppm->comm);
1549         if (!res)
1550                 res = ppi1->ppm->pid > ppi2->ppm->pid;
1551
1552         return res;
1553 }
1554
1555 static void sort_process_list(void)
1556 {
1557         struct per_process_info **ppis;
1558         struct per_process_info *ppi;
1559         int i = 0;
1560
1561         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1562
1563         ppi = ppi_list;
1564         while (ppi) {
1565                 ppis[i++] = ppi;
1566                 ppi = ppi->list_next;
1567         }
1568
1569         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1570
1571         i = ppi_list_entries - 1;
1572         ppi_list = NULL;
1573         while (i >= 0) {
1574                 ppi = ppis[i];
1575
1576                 ppi->list_next = ppi_list;
1577                 ppi_list = ppi;
1578                 i--;
1579         }
1580
1581         free(ppis);
1582 }
1583
1584 static void show_process_stats(void)
1585 {
1586         struct per_process_info *ppi;
1587
1588         sort_process_list();
1589
1590         ppi = ppi_list;
1591         while (ppi) {
1592                 struct process_pid_map *ppm = ppi->ppm;
1593                 char name[64];
1594
1595                 if (ppi->more_than_one)
1596                         sprintf(name, "%s (%u, ...)", ppm->comm, ppm->pid);
1597                 else
1598                         sprintf(name, "%s (%u)", ppm->comm, ppm->pid);
1599
1600                 dump_io_stats(NULL, &ppi->io_stats, name);
1601                 dump_wait_stats(ppi);
1602                 ppi = ppi->list_next;
1603         }
1604
1605         fprintf(ofp, "\n");
1606 }
1607
1608 static void show_device_and_cpu_stats(void)
1609 {
1610         struct per_dev_info *pdi;
1611         struct per_cpu_info *pci;
1612         struct io_stats total, *ios;
1613         unsigned long long rrate, wrate, msec;
1614         int i, j, pci_events;
1615         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1616         char name[32];
1617
1618         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1619
1620                 memset(&total, 0, sizeof(total));
1621                 pci_events = 0;
1622
1623                 if (i > 0)
1624                         fprintf(ofp, "\n");
1625
1626                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1627                         if (!pci->nelems)
1628                                 continue;
1629
1630                         ios = &pci->io_stats;
1631                         total.qreads += ios->qreads;
1632                         total.qwrites += ios->qwrites;
1633                         total.creads += ios->creads;
1634                         total.cwrites += ios->cwrites;
1635                         total.mreads += ios->mreads;
1636                         total.mwrites += ios->mwrites;
1637                         total.ireads += ios->ireads;
1638                         total.iwrites += ios->iwrites;
1639                         total.rrqueue += ios->rrqueue;
1640                         total.wrqueue += ios->wrqueue;
1641                         total.qread_kb += ios->qread_kb;
1642                         total.qwrite_kb += ios->qwrite_kb;
1643                         total.cread_kb += ios->cread_kb;
1644                         total.cwrite_kb += ios->cwrite_kb;
1645                         total.iread_kb += ios->iread_kb;
1646                         total.iwrite_kb += ios->iwrite_kb;
1647                         total.timer_unplugs += ios->timer_unplugs;
1648                         total.io_unplugs += ios->io_unplugs;
1649
1650                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1651                                  j, get_dev_name(pdi, name, sizeof(name)));
1652                         dump_io_stats(pdi, ios, line);
1653                         pci_events++;
1654                 }
1655
1656                 if (pci_events > 1) {
1657                         fprintf(ofp, "\n");
1658                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1659                                  get_dev_name(pdi, name, sizeof(name)));
1660                         dump_io_stats(NULL, &total, line);
1661                 }
1662
1663                 wrate = rrate = 0;
1664                 msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
1665                 if (msec) {
1666                         rrate = 1000 * total.cread_kb / msec;
1667                         wrate = 1000 * total.cwrite_kb / msec;
1668                 }
1669
1670                 fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
1671                         rrate, wrate);
1672                 fprintf(ofp, "Events (%s): %'Lu entries\n",
1673                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1674
1675                 collect_pdi_skips(pdi);
1676                 fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
1677                         pdi->skips,pdi->seq_skips,
1678                         100.0 * ((double)pdi->seq_skips /
1679                                 (double)(pdi->events + pdi->seq_skips)));
1680         }
1681 }
1682
1683 static void find_genesis(void)
1684 {
1685         struct trace *t = trace_list;
1686
1687         genesis_time = -1ULL;
1688         while (t != NULL) {
1689                 if (t->bit->time < genesis_time)
1690                         genesis_time = t->bit->time;
1691
1692                 t = t->next;
1693         }
1694
1695         /* The time stamp record will usually be the first
1696          * record in the trace, but not always.
1697          */
1698         if (start_timestamp
1699          && start_timestamp != genesis_time) {
1700                 long delta = genesis_time - start_timestamp;
1701
1702                 abs_start_time.tv_sec  += SECONDS(delta);
1703                 abs_start_time.tv_nsec += NANO_SECONDS(delta);
1704                 if (abs_start_time.tv_nsec < 0) {
1705                         abs_start_time.tv_nsec += 1000000000;
1706                         abs_start_time.tv_sec -= 1;
1707                 } else
1708                 if (abs_start_time.tv_nsec > 1000000000) {
1709                         abs_start_time.tv_nsec -= 1000000000;
1710                         abs_start_time.tv_sec += 1;
1711                 }
1712         }
1713 }
1714
1715 static inline int check_stopwatch(struct blk_io_trace *bit)
1716 {
1717         if (bit->time < stopwatch_end &&
1718             bit->time >= stopwatch_start)
1719                 return 0;
1720
1721         return 1;
1722 }
1723
1724 /*
1725  * return youngest entry read
1726  */
1727 static int sort_entries(unsigned long long *youngest)
1728 {
1729         struct per_dev_info *pdi = NULL;
1730         struct per_cpu_info *pci = NULL;
1731         struct trace *t;
1732
1733         if (!genesis_time)
1734                 find_genesis();
1735
1736         *youngest = 0;
1737         while ((t = trace_list) != NULL) {
1738                 struct blk_io_trace *bit = t->bit;
1739
1740                 trace_list = t->next;
1741
1742                 bit->time -= genesis_time;
1743
1744                 if (bit->time < *youngest || !*youngest)
1745                         *youngest = bit->time;
1746
1747                 if (!pdi || pdi->dev != bit->device) {
1748                         pdi = get_dev_info(bit->device);
1749                         pci = NULL;
1750                 }
1751
1752                 if (!pci || pci->cpu != bit->cpu)
1753                         pci = get_cpu_info(pdi, bit->cpu);
1754
1755                 if (bit->sequence < pci->smallest_seq_read)
1756                         pci->smallest_seq_read = bit->sequence;
1757
1758                 if (check_stopwatch(bit)) {
1759                         bit_free(bit);
1760                         t_free(t);
1761                         continue;
1762                 }
1763
1764                 if (trace_rb_insert_sort(t))
1765                         return -1;
1766         }
1767
1768         return 0;
1769 }
1770
1771 /*
1772  * to continue, we must have traces from all online cpus in the tree
1773  */
1774 static int check_cpu_map(struct per_dev_info *pdi)
1775 {
1776         unsigned long *cpu_map;
1777         struct rb_node *n;
1778         struct trace *__t;
1779         unsigned int i;
1780         int ret, cpu;
1781
1782         /*
1783          * create a map of the cpus we have traces for
1784          */
1785         cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
1786         n = rb_first(&rb_sort_root);
1787         while (n) {
1788                 __t = rb_entry(n, struct trace, rb_node);
1789                 cpu = __t->bit->cpu;
1790
1791                 cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
1792                 n = rb_next(n);
1793         }
1794
1795         /*
1796          * we can't continue if pdi->cpu_map has entries set that we don't
1797          * have in the sort rbtree. the opposite is not a problem, though
1798          */
1799         ret = 0;
1800         for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
1801                 if (pdi->cpu_map[i] & ~(cpu_map[i])) {
1802                         ret = 1;
1803                         break;
1804                 }
1805         }
1806
1807         free(cpu_map);
1808         return ret;
1809 }
1810
1811 static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
1812 {
1813         struct blk_io_trace *bit = t->bit;
1814         unsigned long expected_sequence;
1815         struct per_cpu_info *pci;
1816         struct trace *__t;
1817
1818         pci = get_cpu_info(pdi, bit->cpu);
1819         expected_sequence = pci->last_sequence + 1;
1820
1821         if (!expected_sequence) {
1822                 /*
1823                  * 1 should be the first entry, just allow it
1824                  */
1825                 if (bit->sequence == 1)
1826                         return 0;
1827                 if (bit->sequence == pci->smallest_seq_read)
1828                         return 0;
1829
1830                 return check_cpu_map(pdi);
1831         }
1832
1833         if (bit->sequence == expected_sequence)
1834                 return 0;
1835
1836         /*
1837          * we may not have seen that sequence yet. if we are not doing
1838          * the final run, break and wait for more entries.
1839          */
1840         if (expected_sequence < pci->smallest_seq_read) {
1841                 __t = trace_rb_find_last(pdi, pci, expected_sequence);
1842                 if (!__t)
1843                         goto skip;
1844
1845                 __put_trace_last(pdi, __t);
1846                 return 0;
1847         } else if (!force) {
1848                 return 1;
1849         } else {
1850 skip:
1851                 if (check_current_skips(pci, bit->sequence))
1852                         return 0;
1853
1854                 if (expected_sequence < bit->sequence)
1855                         insert_skip(pci, expected_sequence, bit->sequence - 1);
1856                 return 0;
1857         }
1858 }
1859
1860 static void show_entries_rb(int force)
1861 {
1862         struct per_dev_info *pdi = NULL;
1863         struct per_cpu_info *pci = NULL;
1864         struct blk_io_trace *bit;
1865         struct rb_node *n;
1866         struct trace *t;
1867
1868         while ((n = rb_first(&rb_sort_root)) != NULL) {
1869                 if (is_done() && !force && !pipeline)
1870                         break;
1871
1872                 t = rb_entry(n, struct trace, rb_node);
1873                 bit = t->bit;
1874
1875                 if (read_sequence - t->read_sequence < 1 && !force)
1876                         break;
1877
1878                 if (!pdi || pdi->dev != bit->device) {
1879                         pdi = get_dev_info(bit->device);
1880                         pci = NULL;
1881                 }
1882
1883                 if (!pdi) {
1884                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1885                                 MAJOR(bit->device), MINOR(bit->device));
1886                         break;
1887                 }
1888
1889                 if (check_sequence(pdi, t, force))
1890                         break;
1891
1892                 if (!force && bit->time > last_allowed_time)
1893                         break;
1894
1895                 check_time(pdi, bit);
1896
1897                 if (!pci || pci->cpu != bit->cpu)
1898                         pci = get_cpu_info(pdi, bit->cpu);
1899
1900                 pci->last_sequence = bit->sequence;
1901
1902                 pci->nelems++;
1903
1904                 if (bit->action & (act_mask << BLK_TC_SHIFT))
1905                         dump_trace(bit, pci, pdi);
1906
1907                 put_trace(pdi, t);
1908         }
1909 }
1910
1911 static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
1912 {
1913         int ret, bytes_left, fl;
1914         void *p;
1915
1916         if (block != *fdblock) {
1917                 fl = fcntl(fd, F_GETFL);
1918
1919                 if (!block) {
1920                         *fdblock = 0;
1921                         fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1922                 } else {
1923                         *fdblock = 1;
1924                         fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1925                 }
1926         }
1927
1928         bytes_left = bytes;
1929         p = buffer;
1930         while (bytes_left > 0) {
1931                 ret = read(fd, p, bytes_left);
1932                 if (!ret)
1933                         return 1;
1934                 else if (ret < 0) {
1935                         if (errno != EAGAIN) {
1936                                 perror("read");
1937                                 return -1;
1938                         }
1939
1940                         /*
1941                          * never do partial reads. we can return if we
1942                          * didn't read anything and we should not block,
1943                          * otherwise wait for data
1944                          */
1945                         if ((bytes_left == bytes) && !block)
1946                                 return 1;
1947
1948                         usleep(10);
1949                         continue;
1950                 } else {
1951                         p += ret;
1952                         bytes_left -= ret;
1953                 }
1954         }
1955
1956         return 0;
1957 }
1958
1959 static inline __u16 get_pdulen(struct blk_io_trace *bit)
1960 {
1961         if (data_is_native)
1962                 return bit->pdu_len;
1963
1964         return __bswap_16(bit->pdu_len);
1965 }
1966
1967 static inline __u32 get_magic(struct blk_io_trace *bit)
1968 {
1969         if (data_is_native)
1970                 return bit->magic;
1971
1972         return __bswap_32(bit->magic);
1973 }
1974
1975 static int read_events(int fd, int always_block, int *fdblock)
1976 {
1977         struct per_dev_info *pdi = NULL;
1978         unsigned int events = 0;
1979
1980         while (!is_done() && events < rb_batch) {
1981                 struct blk_io_trace *bit;
1982                 struct trace *t;
1983                 int pdu_len, should_block, ret;
1984                 __u32 magic;
1985
1986                 bit = bit_alloc();
1987
1988                 should_block = !events || always_block;
1989
1990                 ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
1991                 if (ret) {
1992                         bit_free(bit);
1993                         if (!events && ret < 0)
1994                                 events = ret;
1995                         break;
1996                 }
1997
1998                 /*
1999                  * look at first trace to check whether we need to convert
2000                  * data in the future
2001                  */
2002                 if (data_is_native == -1 && check_data_endianness(bit->magic))
2003                         break;
2004
2005                 magic = get_magic(bit);
2006                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2007                         fprintf(stderr, "Bad magic %x\n", magic);
2008                         break;
2009                 }
2010
2011                 pdu_len = get_pdulen(bit);
2012                 if (pdu_len) {
2013                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
2014
2015                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
2016                                 bit_free(ptr);
2017                                 break;
2018                         }
2019
2020                         bit = ptr;
2021                 }
2022
2023                 trace_to_cpu(bit);
2024
2025                 if (verify_trace(bit)) {
2026                         bit_free(bit);
2027                         continue;
2028                 }
2029
2030                 /*
2031                  * not a real trace, so grab and handle it here
2032                  */
2033                 if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY)) {
2034                         handle_notify(bit);
2035                         output_binary(bit, sizeof(*bit) + bit->pdu_len);
2036                         continue;
2037                 }
2038
2039                 t = t_alloc();
2040                 memset(t, 0, sizeof(*t));
2041                 t->bit = bit;
2042                 t->read_sequence = read_sequence;
2043
2044                 t->next = trace_list;
2045                 trace_list = t;
2046
2047                 if (!pdi || pdi->dev != bit->device)
2048                         pdi = get_dev_info(bit->device);
2049
2050                 if (bit->time > pdi->last_read_time)
2051                         pdi->last_read_time = bit->time;
2052
2053                 events++;
2054         }
2055
2056         return events;
2057 }
2058
2059 /*
2060  * Managing input streams
2061  */
2062
2063 struct ms_stream {
2064         struct ms_stream *next;
2065         struct trace *first, *last;
2066         struct per_dev_info *pdi;
2067         unsigned int cpu;
2068 };
2069
2070 #define MS_HASH(d, c) ((MAJOR(d) & 0xff) ^ (MINOR(d) & 0xff) ^ (cpu & 0xff))
2071
2072 struct ms_stream *ms_head;
2073 struct ms_stream *ms_hash[256];
2074
2075 static void ms_sort(struct ms_stream *msp);
2076 static int ms_prime(struct ms_stream *msp);
2077
2078 static inline struct trace *ms_peek(struct ms_stream *msp)
2079 {
2080         return (msp == NULL) ? NULL : msp->first;
2081 }
2082
2083 static inline __u64 ms_peek_time(struct ms_stream *msp)
2084 {
2085         return ms_peek(msp)->bit->time;
2086 }
2087
2088 static inline void ms_resort(struct ms_stream *msp)
2089 {
2090         if (msp->next && ms_peek_time(msp) > ms_peek_time(msp->next)) {
2091                 ms_head = msp->next;
2092                 msp->next = NULL;
2093                 ms_sort(msp);
2094         }
2095 }
2096
2097 static inline void ms_deq(struct ms_stream *msp)
2098 {
2099         msp->first = msp->first->next;
2100         if (!msp->first) {
2101                 msp->last = NULL;
2102                 if (!ms_prime(msp)) {
2103                         ms_head = msp->next;
2104                         msp->next = NULL;
2105                         return;
2106                 }
2107         }
2108
2109         ms_resort(msp);
2110 }
2111
2112 static void ms_sort(struct ms_stream *msp)
2113 {
2114         __u64 msp_t = ms_peek_time(msp);
2115         struct ms_stream *this_msp = ms_head;
2116
2117         if (this_msp == NULL)
2118                 ms_head = msp;
2119         else if (msp_t < ms_peek_time(this_msp)) {
2120                 msp->next = this_msp;
2121                 ms_head = msp;
2122         }
2123         else {
2124                 while (this_msp->next && ms_peek_time(this_msp->next) < msp_t)
2125                         this_msp = this_msp->next;
2126
2127                 msp->next = this_msp->next;
2128                 this_msp->next = msp;
2129         }
2130 }
2131
2132 static int ms_prime(struct ms_stream *msp)
2133 {
2134         __u32 magic;
2135         unsigned int i;
2136         struct trace *t;
2137         struct per_dev_info *pdi = msp->pdi;
2138         struct per_cpu_info *pci = get_cpu_info(pdi, msp->cpu);
2139         struct blk_io_trace *bit = NULL;
2140         int ret, pdu_len, ndone = 0;
2141
2142         for (i = 0; !is_done() && pci->fd >= 0 && i < rb_batch; i++) {
2143                 bit = bit_alloc();
2144                 ret = read_data(pci->fd, bit, sizeof(*bit), 1, &pci->fdblock);
2145                 if (ret)
2146                         goto err;
2147
2148                 if (data_is_native == -1 && check_data_endianness(bit->magic))
2149                         goto err;
2150
2151                 magic = get_magic(bit);
2152                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2153                         fprintf(stderr, "Bad magic %x\n", magic);
2154                         goto err;
2155
2156                 }
2157
2158                 pdu_len = get_pdulen(bit);
2159                 if (pdu_len) {
2160                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
2161                         ret = read_data(pci->fd, ptr + sizeof(*bit), pdu_len,
2162                                                              1, &pci->fdblock);
2163                         if (ret) {
2164                                 free(ptr);
2165                                 goto err;
2166                         }
2167
2168                         bit = ptr;
2169                 }
2170
2171                 trace_to_cpu(bit);
2172                 if (verify_trace(bit))
2173                         goto err;
2174
2175                 if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY)) {
2176                         handle_notify(bit);
2177                         output_binary(bit, sizeof(*bit) + bit->pdu_len);
2178                         bit_free(bit);
2179
2180                         i -= 1;
2181                         continue;
2182                 }
2183
2184                 if (bit->time > pdi->last_read_time)
2185                         pdi->last_read_time = bit->time;
2186
2187                 t = t_alloc();
2188                 memset(t, 0, sizeof(*t));
2189                 t->bit = bit;
2190
2191                 if (msp->first == NULL)
2192                         msp->first = msp->last = t;
2193                 else {
2194                         msp->last->next = t;
2195                         msp->last = t;
2196                 }
2197
2198                 ndone++;
2199         }
2200
2201         return ndone;
2202
2203 err:
2204         if (bit) bit_free(bit);
2205
2206         cpu_mark_offline(pdi, pci->cpu);
2207         close(pci->fd);
2208         pci->fd = -1;
2209
2210         return ndone;
2211 }
2212
2213 static struct ms_stream *ms_alloc(struct per_dev_info *pdi, int cpu)
2214 {
2215         struct ms_stream *msp = malloc(sizeof(*msp));
2216
2217         msp->next = NULL;
2218         msp->first = msp->last = NULL;
2219         msp->pdi = pdi;
2220         msp->cpu = cpu;
2221
2222         if (ms_prime(msp))
2223                 ms_sort(msp);
2224
2225         return msp;
2226 }
2227
2228 static int setup_file(struct per_dev_info *pdi, int cpu)
2229 {
2230         int len = 0;
2231         struct stat st;
2232         char *p, *dname;
2233         struct per_cpu_info *pci = get_cpu_info(pdi, cpu);
2234
2235         pci->cpu = cpu;
2236         pci->fdblock = -1;
2237
2238         p = strdup(pdi->name);
2239         dname = dirname(p);
2240         if (strcmp(dname, ".")) {
2241                 input_dir = dname;
2242                 p = strdup(pdi->name);
2243                 strcpy(pdi->name, basename(p));
2244         }
2245         free(p);
2246
2247         if (input_dir)
2248                 len = sprintf(pci->fname, "%s/", input_dir);
2249
2250         snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
2251                  "%s.blktrace.%d", pdi->name, pci->cpu);
2252         if (stat(pci->fname, &st) < 0)
2253                 return 0;
2254         if (!st.st_size)
2255                 return 1;
2256
2257         pci->fd = open(pci->fname, O_RDONLY);
2258         if (pci->fd < 0) {
2259                 perror(pci->fname);
2260                 return 0;
2261         }
2262
2263         printf("Input file %s added\n", pci->fname);
2264         cpu_mark_online(pdi, pci->cpu);
2265
2266         pdi->nfiles++;
2267         ms_alloc(pdi, pci->cpu);
2268
2269         return 1;
2270 }
2271
2272 static int handle(struct ms_stream *msp)
2273 {
2274         struct trace *t;
2275         struct per_dev_info *pdi;
2276         struct per_cpu_info *pci;
2277         struct blk_io_trace *bit;
2278
2279         t = ms_peek(msp);
2280         if (t->bit->time > stopwatch_end)
2281                 return 0;
2282
2283         bit = t->bit;
2284         pdi = msp->pdi;
2285         pci = get_cpu_info(pdi, msp->cpu);
2286         pci->nelems++;
2287
2288         bit->time -= genesis_time;
2289         pdi->last_reported_time = bit->time;
2290         if (bit->action & (act_mask << BLK_TC_SHIFT))
2291                 dump_trace(bit, pci, pdi);
2292
2293         ms_deq(msp);
2294
2295         if (text_output)
2296                 trace_rb_insert_last(pdi, t);
2297         else {
2298                 bit_free(t->bit);
2299                 t_free(t);
2300         }
2301
2302         return 1;
2303 }
2304
2305 static int do_file(void)
2306 {
2307         int i, cpu;
2308         struct per_dev_info *pdi;
2309
2310         /*
2311          * first prepare all files for reading
2312          */
2313         for (i = 0; i < ndevices; i++) {
2314                 pdi = &devices[i];
2315                 for (cpu = 0; setup_file(pdi, cpu); cpu++)
2316                         ;
2317         }
2318
2319         /*
2320          * Get the initial time stamp
2321          */
2322         if (ms_head)
2323                 genesis_time = ms_peek_time(ms_head);
2324
2325         /*
2326          * Keep processing traces while any are left
2327          */
2328         while (!is_done() && ms_head && handle(ms_head))
2329                 ;
2330
2331         return 0;
2332 }
2333
2334 static int do_stdin(void)
2335 {
2336         unsigned long long youngest;
2337         int fd, events, fdblock;
2338
2339         last_allowed_time = -1ULL;
2340         fd = dup(STDIN_FILENO);
2341         if (fd == -1) {
2342                 perror("dup stdin");
2343                 return -1;
2344         }
2345
2346         fdblock = -1;
2347         while ((events = read_events(fd, 0, &fdblock)) > 0) {
2348                 read_sequence++;
2349         
2350 #if 0
2351                 smallest_seq_read = -1U;
2352 #endif
2353
2354                 if (sort_entries(&youngest))
2355                         break;
2356
2357                 if (youngest > stopwatch_end)
2358                         break;
2359
2360                 show_entries_rb(0);
2361         }
2362
2363         if (rb_sort_entries)
2364                 show_entries_rb(1);
2365
2366         close(fd);
2367         return 0;
2368 }
2369
2370 static void show_stats(void)
2371 {
2372         if (!ofp)
2373                 return;
2374         if (stats_printed)
2375                 return;
2376
2377         stats_printed = 1;
2378
2379         if (per_process_stats)
2380                 show_process_stats();
2381
2382         if (per_device_and_cpu_stats)
2383                 show_device_and_cpu_stats();
2384
2385         fflush(ofp);
2386 }
2387
2388 static void handle_sigint(__attribute__((__unused__)) int sig)
2389 {
2390         done = 1;
2391 }
2392
2393 /*
2394  * Extract start and duration times from a string, allowing
2395  * us to specify a time interval of interest within a trace.
2396  * Format: "duration" (start is zero) or "start:duration".
2397  */
2398 static int find_stopwatch_interval(char *string)
2399 {
2400         double value;
2401         char *sp;
2402
2403         value = strtod(string, &sp);
2404         if (sp == string) {
2405                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
2406                 return 1;
2407         }
2408         if (*sp == ':') {
2409                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
2410                 string = sp + 1;
2411                 value = strtod(string, &sp);
2412                 if (sp == string || *sp != '\0') {
2413                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
2414                                 string);
2415                         return 1;
2416                 }
2417         } else if (*sp != '\0') {
2418                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
2419                 return 1;
2420         }
2421         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
2422         if (stopwatch_end <= stopwatch_start) {
2423                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
2424                         stopwatch_start, stopwatch_end);
2425                 return 1;
2426         }
2427
2428         return 0;
2429 }
2430
2431 #define S_OPTS  "a:A:b:D:d:f:F:hi:o:Oqstw:vV"
2432 static char usage_str[] =    "\n\n" \
2433         "-i <file>           | --input=<file>\n" \
2434         "[ -a <action field> | --act-mask=<action field> ]\n" \
2435         "[ -A <action mask>  | --set-mask=<action mask> ]\n" \
2436         "[ -b <traces>       | --batch=<traces> ]\n" \
2437         "[ -d <file>         | --dump-binary=<file> ]\n" \
2438         "[ -D <dir>          | --input-directory=<dir> ]\n" \
2439         "[ -f <format>       | --format=<format> ]\n" \
2440         "[ -F <spec>         | --format-spec=<spec> ]\n" \
2441         "[ -h                | --hash-by-name ]\n" \
2442         "[ -o <file>         | --output=<file> ]\n" \
2443         "[ -O                | --no-text-output ]\n" \
2444         "[ -q                | --quiet ]\n" \
2445         "[ -s                | --per-program-stats ]\n" \
2446         "[ -t                | --track-ios ]\n" \
2447         "[ -w <time>         | --stopwatch=<time> ]\n" \
2448         "[ -v                | --verbose ]\n" \
2449         "[ -V                | --version ]\n\n" \
2450         "\t-b stdin read batching\n" \
2451         "\t-d Output file. If specified, binary data is written to file\n" \
2452         "\t-D Directory to prepend to input file names\n" \
2453         "\t-f Output format. Customize the output format. The format field\n" \
2454         "\t   identifies can be found in the documentation\n" \
2455         "\t-F Format specification. Can be found in the documentation\n" \
2456         "\t-h Hash processes by name, not pid\n" \
2457         "\t-i Input file containing trace data, or '-' for stdin\n" \
2458         "\t-o Output file. If not given, output is stdout\n" \
2459         "\t-O Do NOT output text data\n" \
2460         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
2461         "\t-s Show per-program io statistics\n" \
2462         "\t-t Track individual ios. Will tell you the time a request took\n" \
2463         "\t   to get queued, to get dispatched, and to get completed\n" \
2464         "\t-w Only parse data between the given time interval in seconds.\n" \
2465         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
2466         "\t-v More verbose for marginal errors\n" \
2467         "\t-V Print program version info\n\n";
2468
2469 static void usage(char *prog)
2470 {
2471         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
2472 }
2473
2474 int main(int argc, char *argv[])
2475 {
2476         int i, c, ret, mode;
2477         int act_mask_tmp = 0;
2478         char *ofp_buffer = NULL;
2479         char *bin_ofp_buffer = NULL;
2480
2481         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
2482                 switch (c) {
2483                 case 'a':
2484                         i = find_mask_map(optarg);
2485                         if (i < 0) {
2486                                 fprintf(stderr,"Invalid action mask %s\n",
2487                                         optarg);
2488                                 return 1;
2489                         }
2490                         act_mask_tmp |= i;
2491                         break;
2492
2493                 case 'A':
2494                         if ((sscanf(optarg, "%x", &i) != 1) || 
2495                                                         !valid_act_opt(i)) {
2496                                 fprintf(stderr,
2497                                         "Invalid set action mask %s/0x%x\n",
2498                                         optarg, i);
2499                                 return 1;
2500                         }
2501                         act_mask_tmp = i;
2502                         break;
2503                 case 'i':
2504                         if (!strcmp(optarg, "-") && !pipeline)
2505                                 pipeline = 1;
2506                         else if (resize_devices(optarg) != 0)
2507                                 return 1;
2508                         break;
2509                 case 'D':
2510                         input_dir = optarg;
2511                         break;
2512                 case 'o':
2513                         output_name = optarg;
2514                         break;
2515                 case 'O':
2516                         text_output = 0;
2517                         break;
2518                 case 'b':
2519                         rb_batch = atoi(optarg);
2520                         if (rb_batch <= 0)
2521                                 rb_batch = RB_BATCH_DEFAULT;
2522                         break;
2523                 case 's':
2524                         per_process_stats = 1;
2525                         break;
2526                 case 't':
2527                         track_ios = 1;
2528                         break;
2529                 case 'q':
2530                         per_device_and_cpu_stats = 0;
2531                         break;
2532                 case 'w':
2533                         if (find_stopwatch_interval(optarg) != 0)
2534                                 return 1;
2535                         break;
2536                 case 'f':
2537                         set_all_format_specs(optarg);
2538                         break;
2539                 case 'F':
2540                         if (add_format_spec(optarg) != 0)
2541                                 return 1;
2542                         break;
2543                 case 'h':
2544                         ppi_hash_by_pid = 0;
2545                         break;
2546                 case 'v':
2547                         verbose++;
2548                         break;
2549                 case 'V':
2550                         printf("%s version %s\n", argv[0], blkparse_version);
2551                         return 0;
2552                 case 'd':
2553                         dump_binary = optarg;
2554                         break;
2555                 default:
2556                         usage(argv[0]);
2557                         return 1;
2558                 }
2559         }
2560
2561         while (optind < argc) {
2562                 if (!strcmp(argv[optind], "-") && !pipeline)
2563                         pipeline = 1;
2564                 else if (resize_devices(argv[optind]) != 0)
2565                         return 1;
2566                 optind++;
2567         }
2568
2569         if (!pipeline && !ndevices) {
2570                 usage(argv[0]);
2571                 return 1;
2572         }
2573
2574         if (act_mask_tmp != 0)
2575                 act_mask = act_mask_tmp;
2576
2577         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
2578
2579         signal(SIGINT, handle_sigint);
2580         signal(SIGHUP, handle_sigint);
2581         signal(SIGTERM, handle_sigint);
2582
2583         setlocale(LC_NUMERIC, "en_US");
2584
2585         if (text_output) {
2586                 if (!output_name) {
2587                         ofp = fdopen(STDOUT_FILENO, "w");
2588                         mode = _IOLBF;
2589                 } else {
2590                         char ofname[128];
2591
2592                         snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
2593                         ofp = fopen(ofname, "w");
2594                         mode = _IOFBF;
2595                 }
2596
2597                 if (!ofp) {
2598                         perror("fopen");
2599                         return 1;
2600                 }
2601
2602                 ofp_buffer = malloc(4096);
2603                 if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
2604                         perror("setvbuf");
2605                         return 1;
2606                 }
2607         }
2608
2609         if (dump_binary) {
2610                 dump_fp = fopen(dump_binary, "w");
2611                 if (!dump_fp) {
2612                         perror(dump_binary);
2613                         dump_binary = NULL;
2614                         return 1;
2615                 }
2616                 bin_ofp_buffer = malloc(128 * 1024);
2617                 if (setvbuf(dump_fp, bin_ofp_buffer, _IOFBF, 128 * 1024)) {
2618                         perror("setvbuf binary");
2619                         return 1;
2620                 }
2621         }
2622
2623         if (pipeline)
2624                 ret = do_stdin();
2625         else
2626                 ret = do_file();
2627
2628         show_stats();
2629         if (ofp_buffer) {
2630                 fflush(ofp);
2631                 free(ofp_buffer);
2632         }
2633         if (bin_ofp_buffer) {
2634                 fflush(dump_fp);
2635                 free(bin_ofp_buffer);
2636         }
2637         return ret;
2638 }