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