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