[PATCH] blkparse: allow tracking of Queue -> Complete time for md/dm
[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 static inline int is_remapper(struct per_dev_info *pdi)
844 {
845         int major = MAJOR(pdi->dev);
846
847         return (major == 253 || major == 9);
848 }
849
850 /*
851  * for md/dm setups, the interesting cycle is Q -> C. So track queueing
852  * time here, as dispatch time
853  */
854 static void log_track_queue(struct per_dev_info *pdi, struct blk_io_trace *t)
855 {
856         struct io_track *iot;
857
858         if (!track_ios)
859                 return;
860         if (!is_remapper(pdi))
861                 return;
862
863         iot = find_track(pdi, t->pid, t->comm, t->sector);
864         iot->dispatch_time = t->time;
865 }
866
867 /*
868  * return time between rq allocation and insertion
869  */
870 static unsigned long long log_track_insert(struct per_dev_info *pdi,
871                                            struct blk_io_trace *t)
872 {
873         unsigned long long elapsed;
874         struct io_track *iot;
875
876         if (!track_ios)
877                 return -1;
878
879         iot = find_track(pdi, t->pid, t->comm, t->sector);
880         iot->queue_time = t->time;
881
882         if (!iot->allocation_time)
883                 return -1;
884
885         elapsed = iot->queue_time - iot->allocation_time;
886
887         if (per_process_stats) {
888                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
889                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
890
891                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
892                         ppi->longest_allocation_wait[w] = elapsed;
893         }
894
895         return elapsed;
896 }
897
898 /*
899  * return time between queue and issue
900  */
901 static unsigned long long log_track_issue(struct per_dev_info *pdi,
902                                           struct blk_io_trace *t)
903 {
904         unsigned long long elapsed;
905         struct io_track *iot;
906
907         if (!track_ios)
908                 return -1;
909         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
910                 return -1;
911
912         iot = __find_track(pdi, t->sector);
913         if (!iot) {
914                 if (verbose)
915                         fprintf(stderr, "issue not found for (%d,%d): %llu\n",
916                                 MAJOR(pdi->dev), MINOR(pdi->dev),
917                                 (unsigned long long) t->sector);
918                 return -1;
919         }
920
921         iot->dispatch_time = t->time;
922         elapsed = iot->dispatch_time - iot->queue_time;
923
924         if (per_process_stats) {
925                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
926                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
927
928                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
929                         ppi->longest_dispatch_wait[w] = elapsed;
930         }
931
932         return elapsed;
933 }
934
935 /*
936  * return time between dispatch and complete
937  */
938 static unsigned long long log_track_complete(struct per_dev_info *pdi,
939                                              struct blk_io_trace *t)
940 {
941         unsigned long long elapsed;
942         struct io_track *iot;
943
944         if (!track_ios)
945                 return -1;
946
947         iot = __find_track(pdi, t->sector);
948         if (!iot) {
949                 if (verbose)
950                         fprintf(stderr,"complete not found for (%d,%d): %llu\n",
951                                 MAJOR(pdi->dev), MINOR(pdi->dev),
952                                 (unsigned long long) t->sector);
953                 return -1;
954         }
955
956         iot->completion_time = t->time;
957         elapsed = iot->completion_time - iot->dispatch_time;
958
959         if (per_process_stats) {
960                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
961                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
962
963                 if (ppi && elapsed > ppi->longest_completion_wait[w])
964                         ppi->longest_completion_wait[w] = elapsed;
965         }
966
967         /*
968          * kill the trace, we don't need it after completion
969          */
970         rb_erase(&iot->rb_node, &pdi->rb_track);
971         free(iot);
972
973         return elapsed;
974 }
975
976
977 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
978 {
979         struct per_process_info *ppi = find_process(pid, name);
980
981         if (!ppi) {
982                 ppi = malloc(sizeof(*ppi));
983                 memset(ppi, 0, sizeof(*ppi));
984                 memcpy(ppi->name, name, 16);
985                 ppi->pid = pid;
986                 add_process_to_hash(ppi);
987                 add_process_to_list(ppi);
988         }
989
990         return &ppi->io_stats;
991 }
992
993 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
994 {
995         if (pdi->name)
996                 snprintf(buffer, size, "%s", pdi->name);
997         else
998                 snprintf(buffer, size, "%d,%d",MAJOR(pdi->dev),MINOR(pdi->dev));
999         return buffer;
1000 }
1001
1002 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
1003 {
1004         unsigned long long this = bit->time;
1005         unsigned long long last = pdi->last_reported_time;
1006
1007         pdi->backwards = (this < last) ? 'B' : ' ';
1008         pdi->last_reported_time = this;
1009 }
1010
1011 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
1012                                int rw)
1013 {
1014         if (rw) {
1015                 ios->mwrites++;
1016                 ios->qwrite_kb += t_kb(t);
1017         } else {
1018                 ios->mreads++;
1019                 ios->qread_kb += t_kb(t);
1020         }
1021 }
1022
1023 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
1024                              int rw)
1025 {
1026         __account_m(&pci->io_stats, t, rw);
1027
1028         if (per_process_stats) {
1029                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1030
1031                 __account_m(ios, t, rw);
1032         }
1033 }
1034
1035 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
1036                                    int rw)
1037 {
1038         if (rw) {
1039                 ios->qwrites++;
1040                 ios->qwrite_kb += t_kb(t);
1041         } else {
1042                 ios->qreads++;
1043                 ios->qread_kb += t_kb(t);
1044         }
1045 }
1046
1047 static inline void account_queue(struct blk_io_trace *t,
1048                                  struct per_cpu_info *pci, int rw)
1049 {
1050         __account_queue(&pci->io_stats, t, rw);
1051
1052         if (per_process_stats) {
1053                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1054
1055                 __account_queue(ios, t, rw);
1056         }
1057 }
1058
1059 static inline void __account_c(struct io_stats *ios, int rw, int bytes)
1060 {
1061         if (rw) {
1062                 ios->cwrites++;
1063                 ios->cwrite_kb += bytes >> 10;
1064         } else {
1065                 ios->creads++;
1066                 ios->cread_kb += bytes >> 10;
1067         }
1068 }
1069
1070 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
1071                              int rw, int bytes)
1072 {
1073         __account_c(&pci->io_stats, rw, bytes);
1074
1075         if (per_process_stats) {
1076                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1077
1078                 __account_c(ios, rw, bytes);
1079         }
1080 }
1081
1082 static inline void __account_issue(struct io_stats *ios, int rw,
1083                                    unsigned int bytes)
1084 {
1085         if (rw) {
1086                 ios->iwrites++;
1087                 ios->iwrite_kb += bytes >> 10;
1088         } else {
1089                 ios->ireads++;
1090                 ios->iread_kb += bytes >> 10;
1091         }
1092 }
1093
1094 static inline void account_issue(struct blk_io_trace *t,
1095                                  struct per_cpu_info *pci, int rw)
1096 {
1097         __account_issue(&pci->io_stats, rw, t->bytes);
1098
1099         if (per_process_stats) {
1100                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1101
1102                 __account_issue(ios, rw, t->bytes);
1103         }
1104 }
1105
1106 static inline void __account_unplug(struct io_stats *ios, int timer)
1107 {
1108         if (timer)
1109                 ios->timer_unplugs++;
1110         else
1111                 ios->io_unplugs++;
1112 }
1113
1114 static inline void account_unplug(struct blk_io_trace *t,
1115                                   struct per_cpu_info *pci, int timer)
1116 {
1117         __account_unplug(&pci->io_stats, timer);
1118
1119         if (per_process_stats) {
1120                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1121
1122                 __account_unplug(ios, timer);
1123         }
1124 }
1125
1126 static inline void __account_requeue(struct io_stats *ios,
1127                                      struct blk_io_trace *t, int rw)
1128 {
1129         if (rw) {
1130                 ios->wrqueue++;
1131                 ios->iwrite_kb -= t_kb(t);
1132         } else {
1133                 ios->rrqueue++;
1134                 ios->iread_kb -= t_kb(t);
1135         }
1136 }
1137
1138 static inline void account_requeue(struct blk_io_trace *t,
1139                                    struct per_cpu_info *pci, int rw)
1140 {
1141         __account_requeue(&pci->io_stats, t, rw);
1142
1143         if (per_process_stats) {
1144                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
1145
1146                 __account_requeue(ios, t, rw);
1147         }
1148 }
1149
1150 static void log_complete(struct per_dev_info *pdi, struct per_cpu_info *pci,
1151                          struct blk_io_trace *t, char *act)
1152 {
1153         process_fmt(act, pci, t, log_track_complete(pdi, t), 0, NULL);
1154 }
1155
1156 static void log_insert(struct per_dev_info *pdi, struct per_cpu_info *pci,
1157                        struct blk_io_trace *t, char *act)
1158 {
1159         process_fmt(act, pci, t, log_track_insert(pdi, t), 0, NULL);
1160 }
1161
1162 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
1163                       char *act)
1164 {
1165         process_fmt(act, pci, t, -1, 0, NULL);
1166 }
1167
1168 static void log_issue(struct per_dev_info *pdi, struct per_cpu_info *pci,
1169                       struct blk_io_trace *t, char *act)
1170 {
1171         process_fmt(act, pci, t, log_track_issue(pdi, t), 0, NULL);
1172 }
1173
1174 static void log_merge(struct per_dev_info *pdi, struct per_cpu_info *pci,
1175                       struct blk_io_trace *t, char *act)
1176 {
1177         if (act[0] == 'F')
1178                 log_track_frontmerge(pdi, t);
1179
1180         process_fmt(act, pci, t, -1ULL, 0, NULL);
1181 }
1182
1183 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
1184                         char *act)
1185 {
1186         process_fmt(act, pci, t, -1ULL, 0, NULL);
1187 }
1188
1189 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
1190                         char *act)
1191 {
1192         process_fmt(act, pci, t, -1ULL, 0, NULL);
1193 }
1194
1195 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
1196                       char *act)
1197 {
1198         process_fmt(act, pci, t, -1ULL, 0, NULL);
1199 }
1200
1201 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
1202                       char *act)
1203 {
1204         process_fmt(act, pci, t, -1ULL, 0, NULL);
1205 }
1206
1207 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
1208 {
1209         unsigned char *buf = (unsigned char *) t + sizeof(*t);
1210
1211         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
1212 }
1213
1214 static void dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
1215 {
1216         int act = t->action & 0xffff;
1217
1218         switch (act) {
1219                 case __BLK_TA_QUEUE:
1220                         log_generic(pci, t, "Q");
1221                         break;
1222                 case __BLK_TA_GETRQ:
1223                         log_generic(pci, t, "G");
1224                         break;
1225                 case __BLK_TA_SLEEPRQ:
1226                         log_generic(pci, t, "S");
1227                         break;
1228                 case __BLK_TA_REQUEUE:
1229                         log_generic(pci, t, "R");
1230                         break;
1231                 case __BLK_TA_ISSUE:
1232                         log_pc(pci, t, "D");
1233                         break;
1234                 case __BLK_TA_COMPLETE:
1235                         log_pc(pci, t, "C");
1236                         break;
1237                 case __BLK_TA_INSERT:
1238                         log_pc(pci, t, "I");
1239                         break;
1240                 default:
1241                         fprintf(stderr, "Bad pc action %x\n", act);
1242                         break;
1243         }
1244 }
1245
1246 static void dump_trace_fs(struct blk_io_trace *t, struct per_dev_info *pdi,
1247                           struct per_cpu_info *pci)
1248 {
1249         int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1250         int act = t->action & 0xffff;
1251
1252         switch (act) {
1253                 case __BLK_TA_QUEUE:
1254                         log_track_queue(pdi, t);
1255                         account_queue(t, pci, w);
1256                         log_queue(pci, t, "Q");
1257                         break;
1258                 case __BLK_TA_INSERT:
1259                         log_insert(pdi, pci, t, "I");
1260                         break;
1261                 case __BLK_TA_BACKMERGE:
1262                         account_m(t, pci, w);
1263                         log_merge(pdi, pci, t, "M");
1264                         break;
1265                 case __BLK_TA_FRONTMERGE:
1266                         account_m(t, pci, w);
1267                         log_merge(pdi, pci, t, "F");
1268                         break;
1269                 case __BLK_TA_GETRQ:
1270                         log_track_getrq(pdi, t);
1271                         log_generic(pci, t, "G");
1272                         break;
1273                 case __BLK_TA_SLEEPRQ:
1274                         log_generic(pci, t, "S");
1275                         break;
1276                 case __BLK_TA_REQUEUE:
1277                         /*
1278                          * can happen if we miss traces, don't let it go
1279                          * below zero
1280                          */
1281                         if (pdi->cur_depth[w])
1282                                 pdi->cur_depth[w]--;
1283                         account_requeue(t, pci, w);
1284                         log_queue(pci, t, "R");
1285                         break;
1286                 case __BLK_TA_ISSUE:
1287                         account_issue(t, pci, w);
1288                         pdi->cur_depth[w]++;
1289                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1290                                 pdi->max_depth[w] = pdi->cur_depth[w];
1291                         log_issue(pdi, pci, t, "D");
1292                         break;
1293                 case __BLK_TA_COMPLETE:
1294                         if (pdi->cur_depth[w])
1295                                 pdi->cur_depth[w]--;
1296                         account_c(t, pci, w, t->bytes);
1297                         log_complete(pdi, pci, t, "C");
1298                         break;
1299                 case __BLK_TA_PLUG:
1300                         log_action(pci, t, "P");
1301                         break;
1302                 case __BLK_TA_UNPLUG_IO:
1303                         account_unplug(t, pci, 0);
1304                         log_unplug(pci, t, "U");
1305                         break;
1306                 case __BLK_TA_UNPLUG_TIMER:
1307                         account_unplug(t, pci, 1);
1308                         log_unplug(pci, t, "UT");
1309                         break;
1310                 case __BLK_TA_SPLIT:
1311                         log_split(pci, t, "X");
1312                         break;
1313                 case __BLK_TA_BOUNCE:
1314                         log_generic(pci, t, "B");
1315                         break;
1316                 case __BLK_TA_REMAP:
1317                         log_generic(pci, t, "A");
1318                         break;
1319                 default:
1320                         fprintf(stderr, "Bad fs action %x\n", t->action);
1321                         break;
1322         }
1323 }
1324
1325 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1326                        struct per_dev_info *pdi)
1327 {
1328         if (t->action & BLK_TC_ACT(BLK_TC_PC))
1329                 dump_trace_pc(t, pci);
1330         else
1331                 dump_trace_fs(t, pdi, pci);
1332
1333         if (!pdi->events)
1334                 pdi->first_reported_time = t->time;
1335
1336         pdi->events++;
1337 }
1338
1339 /*
1340  * print in a proper way, not too small and not too big. if more than
1341  * 1000,000K, turn into M and so on
1342  */
1343 static char *size_cnv(char *dst, unsigned long long num, int in_kb)
1344 {
1345         char suff[] = { '\0', 'K', 'M', 'G', 'P' };
1346         unsigned int i = 0;
1347
1348         if (in_kb)
1349                 i++;
1350
1351         while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
1352                 i++;
1353                 num /= 1000;
1354         }
1355
1356         sprintf(dst, "%'8Lu%c", num, suff[i]);
1357         return dst;
1358 }
1359
1360 static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
1361                           char *msg)
1362 {
1363         static char x[256], y[256];
1364
1365         fprintf(ofp, "%s\n", msg);
1366
1367         fprintf(ofp, " Reads Queued:    %s, %siB\t", size_cnv(x, ios->qreads, 0), size_cnv(y, ios->qread_kb, 1));
1368         fprintf(ofp, " Writes Queued:    %s, %siB\n", size_cnv(x, ios->qwrites, 0), size_cnv(y, ios->qwrite_kb, 1));
1369
1370         fprintf(ofp, " Read Dispatches: %s, %siB\t", size_cnv(x, ios->ireads, 0), size_cnv(y, ios->iread_kb, 1));
1371         fprintf(ofp, " Write Dispatches: %s, %siB\n", size_cnv(x, ios->iwrites, 0), size_cnv(y, ios->iwrite_kb, 1));
1372         fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
1373         fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
1374         fprintf(ofp, " Reads Completed: %s, %siB\t", size_cnv(x, ios->creads, 0), size_cnv(y, ios->cread_kb, 1));
1375         fprintf(ofp, " Writes Completed: %s, %siB\n", size_cnv(x, ios->cwrites, 0), size_cnv(y, ios->cwrite_kb, 1));
1376         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
1377         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
1378         if (pdi) {
1379                 fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
1380                 fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
1381         }
1382         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1383         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1384 }
1385
1386 static void dump_wait_stats(struct per_process_info *ppi)
1387 {
1388         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1389         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1390         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1391         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1392         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1393         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1394
1395         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1396         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1397         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1398         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1399         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1400         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1401 }
1402
1403 static int ppi_name_compare(const void *p1, const void *p2)
1404 {
1405         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1406         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1407         int res;
1408
1409         res = strverscmp(ppi1->name, ppi2->name);
1410         if (!res)
1411                 res = ppi1->pid > ppi2->pid;
1412
1413         return res;
1414 }
1415
1416 static void sort_process_list(void)
1417 {
1418         struct per_process_info **ppis;
1419         struct per_process_info *ppi;
1420         int i = 0;
1421
1422         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1423
1424         ppi = ppi_list;
1425         while (ppi) {
1426                 ppis[i++] = ppi;
1427                 ppi = ppi->list_next;
1428         }
1429
1430         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1431
1432         i = ppi_list_entries - 1;
1433         ppi_list = NULL;
1434         while (i >= 0) {
1435                 ppi = ppis[i];
1436
1437                 ppi->list_next = ppi_list;
1438                 ppi_list = ppi;
1439                 i--;
1440         }
1441
1442         free(ppis);
1443 }
1444
1445 static void show_process_stats(void)
1446 {
1447         struct per_process_info *ppi;
1448
1449         sort_process_list();
1450
1451         ppi = ppi_list;
1452         while (ppi) {
1453                 char name[64];
1454
1455                 if (ppi->more_than_one)
1456                         sprintf(name, "%s (%u, ...)", ppi->name, ppi->pid);
1457                 else
1458                         sprintf(name, "%s (%u)", ppi->name, ppi->pid);
1459
1460                 dump_io_stats(NULL, &ppi->io_stats, name);
1461                 dump_wait_stats(ppi);
1462                 ppi = ppi->list_next;
1463         }
1464
1465         fprintf(ofp, "\n");
1466 }
1467
1468 static void show_device_and_cpu_stats(void)
1469 {
1470         struct per_dev_info *pdi;
1471         struct per_cpu_info *pci;
1472         struct io_stats total, *ios;
1473         unsigned long long rrate, wrate, msec;
1474         int i, j, pci_events;
1475         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1476         char name[32];
1477
1478         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1479
1480                 memset(&total, 0, sizeof(total));
1481                 pci_events = 0;
1482
1483                 if (i > 0)
1484                         fprintf(ofp, "\n");
1485
1486                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1487                         if (!pci->nelems)
1488                                 continue;
1489
1490                         ios = &pci->io_stats;
1491                         total.qreads += ios->qreads;
1492                         total.qwrites += ios->qwrites;
1493                         total.creads += ios->creads;
1494                         total.cwrites += ios->cwrites;
1495                         total.mreads += ios->mreads;
1496                         total.mwrites += ios->mwrites;
1497                         total.ireads += ios->ireads;
1498                         total.iwrites += ios->iwrites;
1499                         total.rrqueue += ios->rrqueue;
1500                         total.wrqueue += ios->wrqueue;
1501                         total.qread_kb += ios->qread_kb;
1502                         total.qwrite_kb += ios->qwrite_kb;
1503                         total.cread_kb += ios->cread_kb;
1504                         total.cwrite_kb += ios->cwrite_kb;
1505                         total.iread_kb += ios->iread_kb;
1506                         total.iwrite_kb += ios->iwrite_kb;
1507                         total.timer_unplugs += ios->timer_unplugs;
1508                         total.io_unplugs += ios->io_unplugs;
1509
1510                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1511                                  j, get_dev_name(pdi, name, sizeof(name)));
1512                         dump_io_stats(pdi, ios, line);
1513                         pci_events++;
1514                 }
1515
1516                 if (pci_events > 1) {
1517                         fprintf(ofp, "\n");
1518                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1519                                  get_dev_name(pdi, name, sizeof(name)));
1520                         dump_io_stats(NULL, &total, line);
1521                 }
1522
1523                 wrate = rrate = 0;
1524                 msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
1525                 if (msec) {
1526                         rrate = 1000 * total.cread_kb / msec;
1527                         wrate = 1000 * total.cwrite_kb / msec;
1528                 }
1529
1530                 fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
1531                         rrate, wrate);
1532                 fprintf(ofp, "Events (%s): %'Lu entries\n",
1533                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1534
1535                 collect_pdi_skips(pdi);
1536                 fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
1537                         pdi->skips,pdi->seq_skips,
1538                         100.0 * ((double)pdi->seq_skips /
1539                                 (double)(pdi->events + pdi->seq_skips)));
1540         }
1541 }
1542
1543 static void find_genesis(void)
1544 {
1545         struct trace *t = trace_list;
1546
1547         genesis_time = -1ULL;
1548         while (t != NULL) {
1549                 if (t->bit->time < genesis_time)
1550                         genesis_time = t->bit->time;
1551
1552                 t = t->next;
1553         }
1554 }
1555
1556 static inline int check_stopwatch(struct blk_io_trace *bit)
1557 {
1558         if (bit->time < stopwatch_end &&
1559             bit->time >= stopwatch_start)
1560                 return 0;
1561
1562         return 1;
1563 }
1564
1565 /*
1566  * return youngest entry read
1567  */
1568 static int sort_entries(unsigned long long *youngest)
1569 {
1570         struct per_dev_info *pdi = NULL;
1571         struct per_cpu_info *pci = NULL;
1572         struct trace *t;
1573
1574         if (!genesis_time)
1575                 find_genesis();
1576
1577         *youngest = 0;
1578         while ((t = trace_list) != NULL) {
1579                 struct blk_io_trace *bit = t->bit;
1580
1581                 trace_list = t->next;
1582
1583                 bit->time -= genesis_time;
1584
1585                 if (bit->time < *youngest || !*youngest)
1586                         *youngest = bit->time;
1587
1588                 if (!pdi || pdi->dev != bit->device) {
1589                         pdi = get_dev_info(bit->device);
1590                         pci = NULL;
1591                 }
1592
1593                 if (!pci || pci->cpu != bit->cpu)
1594                         pci = get_cpu_info(pdi, bit->cpu);
1595
1596                 if (bit->sequence < pci->smallest_seq_read)
1597                         pci->smallest_seq_read = bit->sequence;
1598
1599                 if (check_stopwatch(bit)) {
1600                         bit_free(bit);
1601                         t_free(t);
1602                         continue;
1603                 }
1604
1605                 if (trace_rb_insert_sort(t))
1606                         return -1;
1607         }
1608
1609         return 0;
1610 }
1611
1612 /*
1613  * to continue, we must have traces from all online cpus in the tree
1614  */
1615 static int check_cpu_map(struct per_dev_info *pdi)
1616 {
1617         unsigned long *cpu_map;
1618         struct rb_node *n;
1619         struct trace *__t;
1620         unsigned int i;
1621         int ret, cpu;
1622
1623         /*
1624          * create a map of the cpus we have traces for
1625          */
1626         cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
1627         n = rb_first(&rb_sort_root);
1628         while (n) {
1629                 __t = rb_entry(n, struct trace, rb_node);
1630                 cpu = __t->bit->cpu;
1631
1632                 cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
1633                 n = rb_next(n);
1634         }
1635
1636         /*
1637          * we can't continue if pdi->cpu_map has entries set that we don't
1638          * have in the sort rbtree. the opposite is not a problem, though
1639          */
1640         ret = 0;
1641         for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
1642                 if (pdi->cpu_map[i] & ~(cpu_map[i])) {
1643                         ret = 1;
1644                         break;
1645                 }
1646         }
1647
1648         free(cpu_map);
1649         return ret;
1650 }
1651
1652 static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
1653 {
1654         struct blk_io_trace *bit = t->bit;
1655         unsigned long expected_sequence;
1656         struct per_cpu_info *pci;
1657         struct trace *__t;
1658
1659         pci = get_cpu_info(pdi, bit->cpu);
1660         expected_sequence = pci->last_sequence + 1;
1661
1662         if (!expected_sequence) {
1663                 /*
1664                  * 1 should be the first entry, just allow it
1665                  */
1666                 if (bit->sequence == 1)
1667                         return 0;
1668                 if (bit->sequence == pci->smallest_seq_read)
1669                         return 0;
1670
1671                 return check_cpu_map(pdi);
1672         }
1673
1674         if (bit->sequence == expected_sequence)
1675                 return 0;
1676
1677         /*
1678          * we may not have seen that sequence yet. if we are not doing
1679          * the final run, break and wait for more entries.
1680          */
1681         if (expected_sequence < pci->smallest_seq_read) {
1682                 __t = trace_rb_find_last(pdi, pci, expected_sequence);
1683                 if (!__t)
1684                         goto skip;
1685
1686                 __put_trace_last(pdi, __t);
1687                 return 0;
1688         } else if (!force) {
1689                 return 1;
1690         } else {
1691 skip:
1692                 if (check_current_skips(pci, bit->sequence))
1693                         return 0;
1694
1695                 if (expected_sequence < bit->sequence)
1696                         insert_skip(pci, expected_sequence, bit->sequence - 1);
1697                 return 0;
1698         }
1699 }
1700
1701 static void show_entries_rb(int force)
1702 {
1703         struct per_dev_info *pdi = NULL;
1704         struct per_cpu_info *pci = NULL;
1705         struct blk_io_trace *bit;
1706         struct rb_node *n;
1707         struct trace *t;
1708
1709         while ((n = rb_first(&rb_sort_root)) != NULL) {
1710                 if (is_done() && !force && !pipeline)
1711                         break;
1712
1713                 t = rb_entry(n, struct trace, rb_node);
1714                 bit = t->bit;
1715
1716                 if (read_sequence - t->read_sequence < 1 && !force)
1717                         break;
1718
1719                 if (!pdi || pdi->dev != bit->device) {
1720                         pdi = get_dev_info(bit->device);
1721                         pci = NULL;
1722                 }
1723
1724                 if (!pdi) {
1725                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1726                                 MAJOR(bit->device), MINOR(bit->device));
1727                         break;
1728                 }
1729
1730                 if (check_sequence(pdi, t, force))
1731                         break;
1732
1733                 if (!force && bit->time > last_allowed_time)
1734                         break;
1735
1736                 check_time(pdi, bit);
1737
1738                 if (!pci || pci->cpu != bit->cpu)
1739                         pci = get_cpu_info(pdi, bit->cpu);
1740
1741                 pci->last_sequence = bit->sequence;
1742
1743                 pci->nelems++;
1744
1745                 if (bit->action & (act_mask << BLK_TC_SHIFT))
1746                         dump_trace(bit, pci, pdi);
1747
1748                 put_trace(pdi, t);
1749         }
1750 }
1751
1752 static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
1753 {
1754         int ret, bytes_left, fl;
1755         void *p;
1756
1757         if (block != *fdblock) {
1758                 fl = fcntl(fd, F_GETFL);
1759
1760                 if (!block) {
1761                         *fdblock = 0;
1762                         fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1763                 } else {
1764                         *fdblock = 1;
1765                         fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1766                 }
1767         }
1768
1769         bytes_left = bytes;
1770         p = buffer;
1771         while (bytes_left > 0) {
1772                 ret = read(fd, p, bytes_left);
1773                 if (!ret)
1774                         return 1;
1775                 else if (ret < 0) {
1776                         if (errno != EAGAIN) {
1777                                 perror("read");
1778                                 return -1;
1779                         }
1780
1781                         /*
1782                          * never do partial reads. we can return if we
1783                          * didn't read anything and we should not block,
1784                          * otherwise wait for data
1785                          */
1786                         if ((bytes_left == bytes) && !block)
1787                                 return 1;
1788
1789                         usleep(10);
1790                         continue;
1791                 } else {
1792                         p += ret;
1793                         bytes_left -= ret;
1794                 }
1795         }
1796
1797         return 0;
1798 }
1799
1800 static inline __u16 get_pdulen(struct blk_io_trace *bit)
1801 {
1802         if (data_is_native)
1803                 return bit->pdu_len;
1804
1805         return __bswap_16(bit->pdu_len);
1806 }
1807
1808 static inline __u32 get_magic(struct blk_io_trace *bit)
1809 {
1810         if (data_is_native)
1811                 return bit->magic;
1812
1813         return __bswap_32(bit->magic);
1814 }
1815
1816 static int read_events(int fd, int always_block, int *fdblock)
1817 {
1818         struct per_dev_info *pdi = NULL;
1819         unsigned int events = 0;
1820
1821         while (!is_done() && events < rb_batch) {
1822                 struct blk_io_trace *bit;
1823                 struct trace *t;
1824                 int pdu_len, should_block, ret;
1825                 __u32 magic;
1826
1827                 bit = bit_alloc();
1828
1829                 should_block = !events || always_block;
1830
1831                 ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
1832                 if (ret) {
1833                         bit_free(bit);
1834                         if (!events && ret < 0)
1835                                 events = ret;
1836                         break;
1837                 }
1838
1839                 /*
1840                  * look at first trace to check whether we need to convert
1841                  * data in the future
1842                  */
1843                 if (data_is_native == -1 && check_data_endianness(bit))
1844                         break;
1845
1846                 magic = get_magic(bit);
1847                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1848                         fprintf(stderr, "Bad magic %x\n", magic);
1849                         break;
1850                 }
1851
1852                 pdu_len = get_pdulen(bit);
1853                 if (pdu_len) {
1854                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1855
1856                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
1857                                 bit_free(ptr);
1858                                 break;
1859                         }
1860
1861                         bit = ptr;
1862                 }
1863
1864                 trace_to_cpu(bit);
1865
1866                 if (verify_trace(bit)) {
1867                         bit_free(bit);
1868                         continue;
1869                 }
1870
1871                 t = t_alloc();
1872                 memset(t, 0, sizeof(*t));
1873                 t->bit = bit;
1874                 t->read_sequence = read_sequence;
1875
1876                 t->next = trace_list;
1877                 trace_list = t;
1878
1879                 if (!pdi || pdi->dev != bit->device)
1880                         pdi = get_dev_info(bit->device);
1881
1882                 if (bit->time > pdi->last_read_time)
1883                         pdi->last_read_time = bit->time;
1884
1885                 events++;
1886         }
1887
1888         return events;
1889 }
1890
1891 static int do_file(void)
1892 {
1893         struct per_cpu_info *pci;
1894         struct per_dev_info *pdi;
1895         int i, j, events, events_added;
1896
1897         /*
1898          * first prepare all files for reading
1899          */
1900         for (i = 0; i < ndevices; i++) {
1901                 pdi = &devices[i];
1902                 pdi->nfiles = 0;
1903
1904                 for (j = 0;; j++) {
1905                         struct stat st;
1906                         int len = 0;
1907                         char *p, *dname;
1908
1909                         pci = get_cpu_info(pdi, j);
1910                         pci->cpu = j;
1911                         pci->fd = -1;
1912                         pci->fdblock = -1;
1913         
1914                         p = strdup(pdi->name);
1915                         dname = dirname(p);
1916                         if (strcmp(dname, ".")) {
1917                                 input_dir = dname;
1918                                 p = strdup(pdi->name);
1919                                 strcpy(pdi->name, basename(p));
1920                         }
1921                         free(p);
1922
1923                         if (input_dir)
1924                                 len = sprintf(pci->fname, "%s/", input_dir);
1925
1926                         snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
1927                                  "%s.blktrace.%d", pdi->name, pci->cpu);
1928                         if (stat(pci->fname, &st) < 0)
1929                                 break;
1930                         if (st.st_size) {
1931                                 pci->fd = open(pci->fname, O_RDONLY);
1932                                 if (pci->fd < 0) {
1933                                         perror(pci->fname);
1934                                         continue;
1935                                 }
1936                         }
1937
1938                         printf("Input file %s added\n", pci->fname);
1939                         pdi->nfiles++;
1940                         cpu_mark_online(pdi, pci->cpu);
1941                 }
1942         }
1943
1944         /*
1945          * now loop over the files reading in the data
1946          */
1947         do {
1948                 unsigned long long youngest;
1949
1950                 events_added = 0;
1951                 last_allowed_time = -1ULL;
1952                 read_sequence++;
1953
1954                 for (i = 0; i < ndevices; i++) {
1955                         pdi = &devices[i];
1956                         pdi->last_read_time = -1ULL;
1957
1958                         for (j = 0; j < pdi->nfiles; j++) {
1959
1960                                 pci = get_cpu_info(pdi, j);
1961
1962                                 if (pci->fd == -1)
1963                                         continue;
1964
1965                                 pci->smallest_seq_read = -1;
1966
1967                                 events = read_events(pci->fd, 1, &pci->fdblock);
1968                                 if (events <= 0) {
1969                                         cpu_mark_offline(pdi, pci->cpu);
1970                                         close(pci->fd);
1971                                         pci->fd = -1;
1972                                         continue;
1973                                 }
1974
1975                                 if (pdi->last_read_time < last_allowed_time)
1976                                         last_allowed_time = pdi->last_read_time;
1977
1978                                 events_added += events;
1979                         }
1980                 }
1981
1982                 if (sort_entries(&youngest))
1983                         break;
1984
1985                 if (youngest > stopwatch_end)
1986                         break;
1987
1988                 show_entries_rb(0);
1989
1990         } while (events_added);
1991
1992         if (rb_sort_entries)
1993                 show_entries_rb(1);
1994
1995         return 0;
1996 }
1997
1998 static int do_stdin(void)
1999 {
2000         unsigned long long youngest;
2001         int fd, events, fdblock;
2002
2003         last_allowed_time = -1ULL;
2004         fd = dup(STDIN_FILENO);
2005         if (fd == -1) {
2006                 perror("dup stdin");
2007                 return -1;
2008         }
2009
2010         fdblock = -1;
2011         while ((events = read_events(fd, 0, &fdblock)) > 0) {
2012                 read_sequence++;
2013         
2014 #if 0
2015                 smallest_seq_read = -1U;
2016 #endif
2017
2018                 if (sort_entries(&youngest))
2019                         break;
2020
2021                 if (youngest > stopwatch_end)
2022                         break;
2023
2024                 show_entries_rb(0);
2025         }
2026
2027         if (rb_sort_entries)
2028                 show_entries_rb(1);
2029
2030         close(fd);
2031         return 0;
2032 }
2033
2034 static void show_stats(void)
2035 {
2036         if (!ofp)
2037                 return;
2038         if (stats_printed)
2039                 return;
2040
2041         stats_printed = 1;
2042
2043         if (per_process_stats)
2044                 show_process_stats();
2045
2046         if (per_device_and_cpu_stats)
2047                 show_device_and_cpu_stats();
2048
2049         fflush(ofp);
2050 }
2051
2052 static void handle_sigint(__attribute__((__unused__)) int sig)
2053 {
2054         done = 1;
2055 }
2056
2057 /*
2058  * Extract start and duration times from a string, allowing
2059  * us to specify a time interval of interest within a trace.
2060  * Format: "duration" (start is zero) or "start:duration".
2061  */
2062 static int find_stopwatch_interval(char *string)
2063 {
2064         double value;
2065         char *sp;
2066
2067         value = strtod(string, &sp);
2068         if (sp == string) {
2069                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
2070                 return 1;
2071         }
2072         if (*sp == ':') {
2073                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
2074                 string = sp + 1;
2075                 value = strtod(string, &sp);
2076                 if (sp == string || *sp != '\0') {
2077                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
2078                                 string);
2079                         return 1;
2080                 }
2081         } else if (*sp != '\0') {
2082                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
2083                 return 1;
2084         }
2085         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
2086         if (stopwatch_end <= stopwatch_start) {
2087                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
2088                         stopwatch_start, stopwatch_end);
2089                 return 1;
2090         }
2091
2092         return 0;
2093 }
2094
2095 static char usage_str[] = \
2096         "[ -i <input name> ] [-o <output name> [ -s ] [ -t ] [ -q ]\n" \
2097         "[ -w start:stop ] [ -f output format ] [ -F format spec ] [ -v] \n\n" \
2098         "\t-i Input file containing trace data, or '-' for stdin\n" \
2099         "\t-D Directory to prepend to input file names\n" \
2100         "\t-o Output file. If not given, output is stdout\n" \
2101         "\t-b stdin read batching\n" \
2102         "\t-s Show per-program io statistics\n" \
2103         "\t-h Hash processes by name, not pid\n" \
2104         "\t-t Track individual ios. Will tell you the time a request took\n" \
2105         "\t   to get queued, to get dispatched, and to get completed\n" \
2106         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
2107         "\t-w Only parse data between the given time interval in seconds.\n" \
2108         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
2109         "\t-f Output format. Customize the output format. The format field\n" \
2110         "\t   identifies can be found in the documentation\n" \
2111         "\t-F Format specification. Can be found in the documentation\n" \
2112         "\t-v More verbose for marginal errors\n" \
2113         "\t-V Print program version info\n\n";
2114
2115 static void usage(char *prog)
2116 {
2117         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
2118 }
2119
2120 int main(int argc, char *argv[])
2121 {
2122         char *ofp_buffer;
2123         int i, c, ret, mode;
2124         int act_mask_tmp = 0;
2125
2126         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
2127                 switch (c) {
2128                 case 'a':
2129                         i = find_mask_map(optarg);
2130                         if (i < 0) {
2131                                 fprintf(stderr,"Invalid action mask %s\n",
2132                                         optarg);
2133                                 return 1;
2134                         }
2135                         act_mask_tmp |= i;
2136                         break;
2137
2138                 case 'A':
2139                         if ((sscanf(optarg, "%x", &i) != 1) || 
2140                                                         !valid_act_opt(i)) {
2141                                 fprintf(stderr,
2142                                         "Invalid set action mask %s/0x%x\n",
2143                                         optarg, i);
2144                                 return 1;
2145                         }
2146                         act_mask_tmp = i;
2147                         break;
2148                 case 'i':
2149                         if (!strcmp(optarg, "-") && !pipeline)
2150                                 pipeline = 1;
2151                         else if (resize_devices(optarg) != 0)
2152                                 return 1;
2153                         break;
2154                 case 'D':
2155                         input_dir = optarg;
2156                         break;
2157                 case 'o':
2158                         output_name = optarg;
2159                         break;
2160                 case 'b':
2161                         rb_batch = atoi(optarg);
2162                         if (rb_batch <= 0)
2163                                 rb_batch = RB_BATCH_DEFAULT;
2164                         break;
2165                 case 's':
2166                         per_process_stats = 1;
2167                         break;
2168                 case 't':
2169                         track_ios = 1;
2170                         break;
2171                 case 'q':
2172                         per_device_and_cpu_stats = 0;
2173                         break;
2174                 case 'w':
2175                         if (find_stopwatch_interval(optarg) != 0)
2176                                 return 1;
2177                         break;
2178                 case 'f':
2179                         set_all_format_specs(optarg);
2180                         break;
2181                 case 'F':
2182                         if (add_format_spec(optarg) != 0)
2183                                 return 1;
2184                         break;
2185                 case 'h':
2186                         ppi_hash_by_pid = 0;
2187                         break;
2188                 case 'v':
2189                         verbose++;
2190                         break;
2191                 case 'V':
2192                         printf("%s version %s\n", argv[0], blkparse_version);
2193                         return 0;
2194                 default:
2195                         usage(argv[0]);
2196                         return 1;
2197                 }
2198         }
2199
2200         while (optind < argc) {
2201                 if (!strcmp(argv[optind], "-") && !pipeline)
2202                         pipeline = 1;
2203                 else if (resize_devices(argv[optind]) != 0)
2204                         return 1;
2205                 optind++;
2206         }
2207
2208         if (!pipeline && !ndevices) {
2209                 usage(argv[0]);
2210                 return 1;
2211         }
2212
2213         if (act_mask_tmp != 0)
2214                 act_mask = act_mask_tmp;
2215
2216         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
2217
2218         signal(SIGINT, handle_sigint);
2219         signal(SIGHUP, handle_sigint);
2220         signal(SIGTERM, handle_sigint);
2221
2222         setlocale(LC_NUMERIC, "en_US");
2223
2224         if (!output_name) {
2225                 ofp = fdopen(STDOUT_FILENO, "w");
2226                 mode = _IOLBF;
2227         } else {
2228                 char ofname[128];
2229
2230                 snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
2231                 ofp = fopen(ofname, "w");
2232                 mode = _IOFBF;
2233         }
2234
2235         if (!ofp) {
2236                 perror("fopen");
2237                 return 1;
2238         }
2239
2240         ofp_buffer = malloc(4096);      
2241         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
2242                 perror("setvbuf");
2243                 return 1;
2244         }
2245
2246         if (pipeline)
2247                 ret = do_stdin();
2248         else
2249                 ret = do_file();
2250
2251         show_stats();
2252         free(ofp_buffer);
2253         return ret;
2254 }