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