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