[PATCH] blktrace: remove check_time, we always need to check it
[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 {
470         struct rb_node **p = &root->rb_node;
471         struct rb_node *parent = NULL;
472         struct trace *__t;
473
474         while (*p) {
475                 parent = *p;
476
477                 __t = rb_entry(parent, struct trace, rb_node);
478
479                 if (t->bit->time < __t->bit->time)
480                         p = &(*p)->rb_left;
481                 else if (t->bit->time > __t->bit->time)
482                         p = &(*p)->rb_right;
483                 else if (t->bit->device < __t->bit->device)
484                         p = &(*p)->rb_left;
485                 else if (t->bit->device > __t->bit->device)
486                         p = &(*p)->rb_right;
487                 else if (t->bit->sequence < __t->bit->sequence)
488                         p = &(*p)->rb_left;
489                 else    /* >= sequence */
490                         p = &(*p)->rb_right;
491         }
492
493         rb_link_node(&t->rb_node, parent, p);
494         rb_insert_color(&t->rb_node, root);
495         return 0;
496 }
497
498 static inline int trace_rb_insert_sort(struct trace *t)
499 {
500         if (!trace_rb_insert(t, &rb_sort_root)) {
501                 rb_sort_entries++;
502                 return 0;
503         }
504
505         return 1;
506 }
507
508 static inline int trace_rb_insert_last(struct per_dev_info *pdi,struct trace *t)
509 {
510         if (!trace_rb_insert(t, &pdi->rb_last)) {
511                 pdi->rb_last_entries++;
512                 return 0;
513         }
514
515         return 1;
516 }
517
518 static struct trace *trace_rb_find(dev_t device, unsigned long sequence,
519                                    struct rb_root *root, int order)
520 {
521         struct rb_node *n = root->rb_node;
522         struct rb_node *prev = NULL;
523         struct trace *__t;
524
525         while (n) {
526                 __t = rb_entry(n, struct trace, rb_node);
527                 prev = n;
528
529                 if (device < __t->bit->device)
530                         n = n->rb_left;
531                 else if (device > __t->bit->device)
532                         n = n->rb_right;
533                 else if (sequence < __t->bit->sequence)
534                         n = n->rb_left;
535                 else if (sequence > __t->bit->sequence)
536                         n = n->rb_right;
537                 else
538                         return __t;
539         }
540
541         /*
542          * hack - the list may not be sequence ordered because some
543          * events don't have sequence and time matched. so we end up
544          * being a little off in the rb lookup here, because we don't
545          * know the time we are looking for. compensate by browsing
546          * a little ahead from the last entry to find the match
547          */
548         if (order && prev) {
549                 int max = 5;
550
551                 while (((n = rb_next(prev)) != NULL) && max--) {
552                         __t = rb_entry(n, struct trace, rb_node);
553
554                         if (__t->bit->device == device &&
555                             __t->bit->sequence == sequence)
556                                 return __t;
557
558                         prev = n;
559                 }
560         }
561
562         return NULL;
563 }
564
565 static inline struct trace *trace_rb_find_sort(dev_t dev, unsigned long seq)
566 {
567         return trace_rb_find(dev, seq, &rb_sort_root, 1);
568 }
569
570 static inline struct trace *trace_rb_find_last(struct per_dev_info *pdi,
571                                                unsigned long seq)
572 {
573         return trace_rb_find(pdi->dev, seq, &pdi->rb_last, 0);
574 }
575
576 static inline int track_rb_insert(struct per_dev_info *pdi,struct io_track *iot)
577 {
578         struct rb_node **p = &pdi->rb_track.rb_node;
579         struct rb_node *parent = NULL;
580         struct io_track *__iot;
581
582         while (*p) {
583                 parent = *p;
584                 __iot = rb_entry(parent, struct io_track, rb_node);
585
586                 if (iot->sector < __iot->sector)
587                         p = &(*p)->rb_left;
588                 else if (iot->sector > __iot->sector)
589                         p = &(*p)->rb_right;
590                 else {
591                         fprintf(stderr,
592                                 "sector alias (%Lu) on device %d,%d!\n",
593                                 (unsigned long long) iot->sector,
594                                 MAJOR(pdi->dev), MINOR(pdi->dev));
595                         return 1;
596                 }
597         }
598
599         rb_link_node(&iot->rb_node, parent, p);
600         rb_insert_color(&iot->rb_node, &pdi->rb_track);
601         return 0;
602 }
603
604 static struct io_track *__find_track(struct per_dev_info *pdi, __u64 sector)
605 {
606         struct rb_node *n = pdi->rb_track.rb_node;
607         struct io_track *__iot;
608
609         while (n) {
610                 __iot = rb_entry(n, struct io_track, rb_node);
611
612                 if (sector < __iot->sector)
613                         n = n->rb_left;
614                 else if (sector > __iot->sector)
615                         n = n->rb_right;
616                 else
617                         return __iot;
618         }
619
620         return NULL;
621 }
622
623 static struct io_track *find_track(struct per_dev_info *pdi, __u32 pid,
624                                    char *comm, __u64 sector)
625 {
626         struct io_track *iot;
627
628         iot = __find_track(pdi, sector);
629         if (!iot) {
630                 iot = malloc(sizeof(*iot));
631                 iot->pid = pid;
632                 memcpy(iot->comm, comm, sizeof(iot->comm));
633                 iot->sector = sector;
634                 track_rb_insert(pdi, iot);
635         }
636
637         return iot;
638 }
639
640 static void log_track_frontmerge(struct per_dev_info *pdi,
641                                  struct blk_io_trace *t)
642 {
643         struct io_track *iot;
644
645         if (!track_ios)
646                 return;
647
648         iot = __find_track(pdi, t->sector + t_sec(t));
649         if (!iot) {
650                 if (verbose)
651                         fprintf(stderr, "merge not found for (%d,%d): %llu\n",
652                                 MAJOR(pdi->dev), MINOR(pdi->dev),
653                                 (unsigned long long) t->sector + t_sec(t));
654                 return;
655         }
656
657         rb_erase(&iot->rb_node, &pdi->rb_track);
658         iot->sector -= t_sec(t);
659         track_rb_insert(pdi, iot);
660 }
661
662 static void log_track_getrq(struct per_dev_info *pdi, struct blk_io_trace *t)
663 {
664         struct io_track *iot;
665
666         if (!track_ios)
667                 return;
668
669         iot = find_track(pdi, t->pid, t->comm, t->sector);
670         iot->allocation_time = t->time;
671 }
672
673 /*
674  * return time between rq allocation and insertion
675  */
676 static unsigned long long log_track_insert(struct per_dev_info *pdi,
677                                            struct blk_io_trace *t)
678 {
679         unsigned long long elapsed;
680         struct io_track *iot;
681
682         if (!track_ios)
683                 return -1;
684
685         iot = find_track(pdi, t->pid, t->comm, t->sector);
686         iot->queue_time = t->time;
687
688         if (!iot->allocation_time)
689                 return -1;
690
691         elapsed = iot->queue_time - iot->allocation_time;
692
693         if (per_process_stats) {
694                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
695                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
696
697                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
698                         ppi->longest_allocation_wait[w] = elapsed;
699         }
700
701         return elapsed;
702 }
703
704 /*
705  * return time between queue and issue
706  */
707 static unsigned long long log_track_issue(struct per_dev_info *pdi,
708                                           struct blk_io_trace *t)
709 {
710         unsigned long long elapsed;
711         struct io_track *iot;
712
713         if (!track_ios)
714                 return -1;
715         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
716                 return -1;
717
718         iot = __find_track(pdi, t->sector);
719         if (!iot) {
720                 if (verbose)
721                         fprintf(stderr, "issue not found for (%d,%d): %llu\n",
722                                 MAJOR(pdi->dev), MINOR(pdi->dev),
723                                 (unsigned long long) t->sector);
724                 return -1;
725         }
726
727         iot->dispatch_time = t->time;
728         elapsed = iot->dispatch_time - iot->queue_time;
729
730         if (per_process_stats) {
731                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
732                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
733
734                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
735                         ppi->longest_dispatch_wait[w] = elapsed;
736         }
737
738         return elapsed;
739 }
740
741 /*
742  * return time between dispatch and complete
743  */
744 static unsigned long long log_track_complete(struct per_dev_info *pdi,
745                                              struct blk_io_trace *t)
746 {
747         unsigned long long elapsed;
748         struct io_track *iot;
749
750         if (!track_ios)
751                 return -1;
752         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
753                 return -1;
754
755         iot = __find_track(pdi, t->sector);
756         if (!iot) {
757                 if (verbose)
758                         fprintf(stderr,"complete not found for (%d,%d): %llu\n",
759                                 MAJOR(pdi->dev), MINOR(pdi->dev),
760                                 (unsigned long long) t->sector);
761                 return -1;
762         }
763
764         iot->completion_time = t->time;
765         elapsed = iot->completion_time - iot->dispatch_time;
766
767         if (per_process_stats) {
768                 struct per_process_info *ppi = find_process(iot->pid,iot->comm);
769                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
770
771                 if (ppi && elapsed > ppi->longest_completion_wait[w])
772                         ppi->longest_completion_wait[w] = elapsed;
773         }
774
775         /*
776          * kill the trace, we don't need it after completion
777          */
778         rb_erase(&iot->rb_node, &pdi->rb_track);
779         free(iot);
780
781         return elapsed;
782 }
783
784
785 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
786 {
787         struct per_process_info *ppi = find_process(pid, name);
788
789         if (!ppi) {
790                 ppi = malloc(sizeof(*ppi));
791                 memset(ppi, 0, sizeof(*ppi));
792                 memcpy(ppi->name, name, 16);
793                 ppi->pid = pid;
794                 add_process_to_hash(ppi);
795                 add_process_to_list(ppi);
796         }
797
798         return &ppi->io_stats;
799 }
800
801 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
802 {
803         struct per_cpu_info *cpus = pdi->cpus;
804         int ncpus = pdi->ncpus;
805         int new_count = cpu + 1;
806         int new_space, size;
807         char *new_start;
808
809         size = new_count * sizeof(struct per_cpu_info);
810         cpus = realloc(cpus, size);
811         if (!cpus) {
812                 char name[20];
813                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
814                         get_dev_name(pdi, name, sizeof(name)), size);
815                 exit(1);
816         }
817
818         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
819         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
820         memset(new_start, 0, new_space);
821
822         pdi->ncpus = new_count;
823         pdi->cpus = cpus;
824
825         for (new_count = 0; new_count < pdi->ncpus; new_count++)
826                 if (!pdi->cpus[new_count].fd)
827                         pdi->cpus[new_count].fd = -1;
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)) != 0;
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                         pdi->cur_depth[w]--;
1170                         account_requeue(t, pci, w);
1171                         log_queue(pci, t, "R");
1172                         break;
1173                 case __BLK_TA_ISSUE:
1174                         account_issue(t, pci, w);
1175                         pdi->cur_depth[w]++;
1176                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1177                                 pdi->max_depth[w] = pdi->cur_depth[w];
1178                         log_issue(pdi, pci, t, "D");
1179                         break;
1180                 case __BLK_TA_COMPLETE:
1181                         pdi->cur_depth[w]--;
1182                         account_c(t, pci, w, t->bytes);
1183                         log_complete(pdi, pci, t, "C");
1184                         break;
1185                 case __BLK_TA_PLUG:
1186                         log_action(pci, t, "P");
1187                         break;
1188                 case __BLK_TA_UNPLUG_IO:
1189                         account_unplug(t, pci, 0);
1190                         log_unplug(pci, t, "U");
1191                         break;
1192                 case __BLK_TA_UNPLUG_TIMER:
1193                         account_unplug(t, pci, 1);
1194                         log_unplug(pci, t, "UT");
1195                         break;
1196                 case __BLK_TA_SPLIT:
1197                         log_split(pci, t, "X");
1198                         break;
1199                 case __BLK_TA_BOUNCE:
1200                         log_generic(pci, t, "B");
1201                         break;
1202                 case __BLK_TA_REMAP:
1203                         log_generic(pci, t, "A");
1204                         break;
1205                 default:
1206                         fprintf(stderr, "Bad fs action %x\n", t->action);
1207                         break;
1208         }
1209 }
1210
1211 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1212                        struct per_dev_info *pdi)
1213 {
1214         if (t->action & BLK_TC_ACT(BLK_TC_PC))
1215                 dump_trace_pc(t, pci);
1216         else
1217                 dump_trace_fs(t, pdi, pci);
1218
1219         if (!pdi->events)
1220                 pdi->first_reported_time = t->time;
1221
1222         pdi->events++;
1223 }
1224
1225 /*
1226  * print in a proper way, not too small and not too big. if more than
1227  * 1000,000K, turn into M and so on
1228  */
1229 static char *size_cnv(char *dst, unsigned long long num, int in_kb)
1230 {
1231         char suff[] = { '\0', 'K', 'M', 'G', 'P' };
1232         unsigned int i = 0;
1233
1234         if (in_kb)
1235                 i++;
1236
1237         while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
1238                 i++;
1239                 num /= 1000;
1240         }
1241
1242         sprintf(dst, "%'8Lu%c", num, suff[i]);
1243         return dst;
1244 }
1245
1246 static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
1247                           char *msg)
1248 {
1249         static char x[256], y[256];
1250
1251         fprintf(ofp, "%s\n", msg);
1252
1253         fprintf(ofp, " Reads Queued:    %s, %siB\t", size_cnv(x, ios->qreads, 0), size_cnv(y, ios->qread_kb, 1));
1254         fprintf(ofp, " Writes Queued:    %s, %siB\n", size_cnv(x, ios->qwrites, 0), size_cnv(y, ios->qwrite_kb, 1));
1255
1256         fprintf(ofp, " Read Dispatches: %s, %siB\t", size_cnv(x, ios->ireads, 0), size_cnv(y, ios->iread_kb, 1));
1257         fprintf(ofp, " Write Dispatches: %s, %siB\n", size_cnv(x, ios->iwrites, 0), size_cnv(y, ios->iwrite_kb, 1));
1258         fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
1259         fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
1260         fprintf(ofp, " Reads Completed: %s, %siB\t", size_cnv(x, ios->creads, 0), size_cnv(y, ios->cread_kb, 1));
1261         fprintf(ofp, " Writes Completed: %s, %siB\n", size_cnv(x, ios->cwrites, 0), size_cnv(y, ios->cwrite_kb, 1));
1262         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
1263         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
1264         if (pdi) {
1265                 fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
1266                 fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
1267         }
1268         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1269         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1270 }
1271
1272 static void dump_wait_stats(struct per_process_info *ppi)
1273 {
1274         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1275         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1276         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1277         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1278         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1279         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1280
1281         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1282         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1283         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1284         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1285         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1286         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1287 }
1288
1289 static int ppi_name_compare(const void *p1, const void *p2)
1290 {
1291         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1292         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1293         int res;
1294
1295         res = strverscmp(ppi1->name, ppi2->name);
1296         if (!res)
1297                 res = ppi1->pid > ppi2->pid;
1298
1299         return res;
1300 }
1301
1302 static void sort_process_list(void)
1303 {
1304         struct per_process_info **ppis;
1305         struct per_process_info *ppi;
1306         int i = 0;
1307
1308         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1309
1310         ppi = ppi_list;
1311         while (ppi) {
1312                 ppis[i++] = ppi;
1313                 ppi = ppi->list_next;
1314         }
1315
1316         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1317
1318         i = ppi_list_entries - 1;
1319         ppi_list = NULL;
1320         while (i >= 0) {
1321                 ppi = ppis[i];
1322
1323                 ppi->list_next = ppi_list;
1324                 ppi_list = ppi;
1325                 i--;
1326         }
1327
1328         free(ppis);
1329 }
1330
1331 static void show_process_stats(void)
1332 {
1333         struct per_process_info *ppi;
1334
1335         sort_process_list();
1336
1337         ppi = ppi_list;
1338         while (ppi) {
1339                 char name[64];
1340
1341                 if (ppi->more_than_one)
1342                         sprintf(name, "%s (%u, ...)", ppi->name, ppi->pid);
1343                 else
1344                         sprintf(name, "%s (%u)", ppi->name, ppi->pid);
1345
1346                 dump_io_stats(NULL, &ppi->io_stats, name);
1347                 dump_wait_stats(ppi);
1348                 ppi = ppi->list_next;
1349         }
1350
1351         fprintf(ofp, "\n");
1352 }
1353
1354 static void show_device_and_cpu_stats(void)
1355 {
1356         struct per_dev_info *pdi;
1357         struct per_cpu_info *pci;
1358         struct io_stats total, *ios;
1359         unsigned long long rrate, wrate, msec;
1360         int i, j, pci_events;
1361         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1362         char name[32];
1363
1364         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1365
1366                 memset(&total, 0, sizeof(total));
1367                 pci_events = 0;
1368
1369                 if (i > 0)
1370                         fprintf(ofp, "\n");
1371
1372                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1373                         if (!pci->nelems)
1374                                 continue;
1375
1376                         ios = &pci->io_stats;
1377                         total.qreads += ios->qreads;
1378                         total.qwrites += ios->qwrites;
1379                         total.creads += ios->creads;
1380                         total.cwrites += ios->cwrites;
1381                         total.mreads += ios->mreads;
1382                         total.mwrites += ios->mwrites;
1383                         total.ireads += ios->ireads;
1384                         total.iwrites += ios->iwrites;
1385                         total.rrqueue += ios->rrqueue;
1386                         total.wrqueue += ios->wrqueue;
1387                         total.qread_kb += ios->qread_kb;
1388                         total.qwrite_kb += ios->qwrite_kb;
1389                         total.cread_kb += ios->cread_kb;
1390                         total.cwrite_kb += ios->cwrite_kb;
1391                         total.iread_kb += ios->iread_kb;
1392                         total.iwrite_kb += ios->iwrite_kb;
1393                         total.timer_unplugs += ios->timer_unplugs;
1394                         total.io_unplugs += ios->io_unplugs;
1395
1396                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1397                                  j, get_dev_name(pdi, name, sizeof(name)));
1398                         dump_io_stats(pdi, ios, line);
1399                         pci_events++;
1400                 }
1401
1402                 if (pci_events > 1) {
1403                         fprintf(ofp, "\n");
1404                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1405                                  get_dev_name(pdi, name, sizeof(name)));
1406                         dump_io_stats(NULL, &total, line);
1407                 }
1408
1409                 wrate = rrate = 0;
1410                 msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
1411                 if (msec) {
1412                         rrate = 1000 * total.cread_kb / msec;
1413                         wrate = 1000 * total.cwrite_kb / msec;
1414                 }
1415
1416                 fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
1417                         rrate, wrate);
1418                 fprintf(ofp, "Events (%s): %'Lu entries\n",
1419                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1420
1421                 collect_pdi_skips(pdi);
1422                 fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
1423                         pdi->skips,pdi->seq_skips,
1424                         100.0 * ((double)pdi->seq_skips /
1425                                 (double)(pdi->events + pdi->seq_skips)));
1426         }
1427 }
1428
1429 /*
1430  * struct trace and blktrace allocation cache, we do potentially
1431  * millions of mallocs for these structures while only using at most
1432  * a few thousand at the time
1433  */
1434 static inline void t_free(struct trace *t)
1435 {
1436         if (t_alloc_cache < 1024) {
1437                 t->next = t_alloc_list;
1438                 t_alloc_list = t;
1439                 t_alloc_cache++;
1440         } else
1441                 free(t);
1442 }
1443
1444 static inline struct trace *t_alloc(void)
1445 {
1446         struct trace *t = t_alloc_list;
1447
1448         if (t) {
1449                 t_alloc_list = t->next;
1450                 t_alloc_cache--;
1451                 return t;
1452         }
1453
1454         return malloc(sizeof(*t));
1455 }
1456
1457 static inline void bit_free(struct blk_io_trace *bit)
1458 {
1459         if (bit_alloc_cache < 1024 && !bit->pdu_len) {
1460                 /*
1461                  * abuse a 64-bit field for a next pointer for the free item
1462                  */
1463                 bit->time = (__u64) (unsigned long) bit_alloc_list;
1464                 bit_alloc_list = (struct blk_io_trace *) bit;
1465                 bit_alloc_cache++;
1466         } else
1467                 free(bit);
1468 }
1469
1470 static inline struct blk_io_trace *bit_alloc(void)
1471 {
1472         struct blk_io_trace *bit = bit_alloc_list;
1473
1474         if (bit) {
1475                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
1476                                  bit->time;
1477                 bit_alloc_cache--;
1478                 return bit;
1479         }
1480
1481         return malloc(sizeof(*bit));
1482 }
1483
1484 static void find_genesis(void)
1485 {
1486         struct trace *t = trace_list;
1487
1488         genesis_time = -1ULL;
1489         while (t != NULL) {
1490                 if (t->bit->time < genesis_time)
1491                         genesis_time = t->bit->time;
1492
1493                 t = t->next;
1494         }
1495 }
1496
1497 static inline int check_stopwatch(struct blk_io_trace *bit)
1498 {
1499         if (bit->time < stopwatch_end &&
1500             bit->time >= stopwatch_start)
1501                 return 0;
1502
1503         return 1;
1504 }
1505
1506 /*
1507  * return youngest entry read
1508  */
1509 static int sort_entries(unsigned long long *youngest)
1510 {
1511         struct trace *t;
1512
1513         if (!genesis_time)
1514                 find_genesis();
1515
1516         *youngest = 0;
1517         while ((t = trace_list) != NULL) {
1518                 struct blk_io_trace *bit = t->bit;
1519
1520                 trace_list = t->next;
1521
1522                 bit->time -= genesis_time;
1523
1524                 if (bit->time < *youngest || !*youngest)
1525                         *youngest = bit->time;
1526
1527                 if (bit->sequence < smallest_seq_read)
1528                         smallest_seq_read = bit->sequence;
1529
1530                 if (check_stopwatch(bit)) {
1531                         bit_free(bit);
1532                         t_free(t);
1533                         continue;
1534                 }
1535
1536                 if (trace_rb_insert_sort(t))
1537                         return -1;
1538         }
1539
1540         return 0;
1541 }
1542
1543 static inline void __put_trace_last(struct per_dev_info *pdi, struct trace *t)
1544 {
1545         rb_erase(&t->rb_node, &pdi->rb_last);
1546         pdi->rb_last_entries--;
1547
1548         bit_free(t->bit);
1549         t_free(t);
1550 }
1551
1552 static void put_trace(struct per_dev_info *pdi, struct trace *t)
1553 {
1554         rb_erase(&t->rb_node, &rb_sort_root);
1555         rb_sort_entries--;
1556
1557         trace_rb_insert_last(pdi, t);
1558
1559         if (pdi->rb_last_entries > rb_batch * pdi->nfiles) {
1560                 struct rb_node *n = rb_first(&pdi->rb_last);
1561
1562                 t = rb_entry(n, struct trace, rb_node);
1563                 __put_trace_last(pdi, t);
1564         }
1565 }
1566
1567 /*
1568  * to continue, we must have traces from all online cpus in the tree
1569  */
1570 static int check_cpu_map(struct per_dev_info *pdi)
1571 {
1572         unsigned long *cpu_map;
1573         struct rb_node *n;
1574         struct trace *__t;
1575         unsigned int i;
1576         int ret, cpu;
1577
1578         /*
1579          * create a map of the cpus we have traces for
1580          */
1581         cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
1582         n = rb_first(&rb_sort_root);
1583         while (n) {
1584                 __t = rb_entry(n, struct trace, rb_node);
1585                 cpu = __t->bit->cpu;
1586
1587                 cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
1588                 n = rb_next(n);
1589         }
1590
1591         /*
1592          * we can't continue if pdi->cpu_map has entries set that we don't
1593          * have in the sort rbtree. the opposite is not a problem, though
1594          */
1595         ret = 0;
1596         for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
1597                 if (pdi->cpu_map[i] & ~(cpu_map[i])) {
1598                         ret = 1;
1599                         break;
1600                 }
1601         }
1602
1603         free(cpu_map);
1604         return ret;
1605 }
1606
1607 static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
1608 {
1609         unsigned long expected_sequence = pdi->last_sequence + 1;
1610         struct blk_io_trace *bit = t->bit;
1611         struct trace *__t;
1612
1613         if (!expected_sequence) {
1614                 /*
1615                  * 1 should be the first entry, just allow it
1616                  */
1617                 if (bit->sequence == 1)
1618                         return 0;
1619                 if (bit->sequence == smallest_seq_read)
1620                         return 0;
1621
1622                 return check_cpu_map(pdi);
1623         }
1624
1625         if (bit->sequence == expected_sequence)
1626                 return 0;
1627
1628         /*
1629          * we may not have seen that sequence yet. if we are not doing
1630          * the final run, break and wait for more entries.
1631          */
1632         if (expected_sequence < smallest_seq_read) {
1633                 __t = trace_rb_find_last(pdi, expected_sequence);
1634                 if (!__t)
1635                         goto skip;
1636
1637                 __put_trace_last(pdi, __t);
1638                 return 0;
1639         } else if (!force) {
1640                 return 1;
1641         } else {
1642 skip:
1643                 if (check_current_skips(pdi,bit->sequence))
1644                         return 0;
1645
1646                 if (expected_sequence < bit->sequence)
1647                         insert_skip(pdi, expected_sequence, bit->sequence - 1);
1648                 return 0;
1649         }
1650 }
1651
1652 static void show_entries_rb(int force)
1653 {
1654         struct per_dev_info *pdi = NULL;
1655         struct per_cpu_info *pci = NULL;
1656         struct blk_io_trace *bit;
1657         struct rb_node *n;
1658         struct trace *t;
1659
1660         while ((n = rb_first(&rb_sort_root)) != NULL) {
1661                 if (is_done() && !force && !pipeline)
1662                         break;
1663
1664                 t = rb_entry(n, struct trace, rb_node);
1665                 bit = t->bit;
1666
1667                 if (!pdi || pdi->dev != bit->device)
1668                         pdi = get_dev_info(bit->device);
1669
1670                 if (!pdi) {
1671                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1672                                 MAJOR(bit->device), MINOR(bit->device));
1673                         break;
1674                 }
1675
1676                 if (check_sequence(pdi, t, force))
1677                         break;
1678
1679                 if (!force && bit->time > last_allowed_time)
1680                         break;
1681
1682                 pdi->last_sequence = bit->sequence;
1683
1684                 check_time(pdi, bit);
1685
1686                 if (!pci || pci->cpu != bit->cpu)
1687                         pci = get_cpu_info(pdi, bit->cpu);
1688
1689                 pci->nelems++;
1690
1691                 if (bit->action & (act_mask << BLK_TC_SHIFT)) 
1692                         dump_trace(bit, pci, pdi);
1693
1694                 put_trace(pdi, t);
1695         }
1696 }
1697
1698 static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
1699 {
1700         int ret, bytes_left, fl;
1701         void *p;
1702
1703         if (block != *fdblock) {
1704                 fl = fcntl(fd, F_GETFL);
1705
1706                 if (!block) {
1707                         *fdblock = 0;
1708                         fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1709                 } else {
1710                         *fdblock = 1;
1711                         fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1712                 }
1713         }
1714
1715         bytes_left = bytes;
1716         p = buffer;
1717         while (bytes_left > 0) {
1718                 ret = read(fd, p, bytes_left);
1719                 if (!ret)
1720                         return 1;
1721                 else if (ret < 0) {
1722                         if (errno != EAGAIN) {
1723                                 perror("read");
1724                                 return -1;
1725                         }
1726
1727                         /*
1728                          * never do partial reads. we can return if we
1729                          * didn't read anything and we should not block,
1730                          * otherwise wait for data
1731                          */
1732                         if ((bytes_left == bytes) && !block)
1733                                 return 1;
1734
1735                         usleep(10);
1736                         continue;
1737                 } else {
1738                         p += ret;
1739                         bytes_left -= ret;
1740                 }
1741         }
1742
1743         return 0;
1744 }
1745
1746 static int read_events(int fd, int always_block, int *fdblock)
1747 {
1748         struct per_dev_info *pdi = NULL;
1749         unsigned int events = 0;
1750
1751         while (!is_done() && events < rb_batch) {
1752                 struct blk_io_trace *bit;
1753                 struct trace *t;
1754                 int pdu_len, should_block, ret;
1755                 __u32 magic;
1756
1757                 bit = bit_alloc();
1758
1759                 should_block = !events || always_block;
1760
1761                 ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
1762                 if (ret) {
1763                         bit_free(bit);
1764                         if (!events && ret < 0)
1765                                 events = ret;
1766                         break;
1767                 }
1768
1769                 magic = be32_to_cpu(bit->magic);
1770                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1771                         fprintf(stderr, "Bad magic %x\n", magic);
1772                         break;
1773                 }
1774
1775                 pdu_len = be16_to_cpu(bit->pdu_len);
1776                 if (pdu_len) {
1777                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1778
1779                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
1780                                 bit_free(ptr);
1781                                 break;
1782                         }
1783
1784                         bit = ptr;
1785                 }
1786
1787                 trace_to_cpu(bit);
1788
1789                 if (verify_trace(bit)) {
1790                         bit_free(bit);
1791                         continue;
1792                 }
1793
1794                 t = t_alloc();
1795                 memset(t, 0, sizeof(*t));
1796                 t->bit = bit;
1797
1798                 t->next = trace_list;
1799                 trace_list = t;
1800
1801                 if (!pdi || pdi->dev != bit->device)
1802                         pdi = get_dev_info(bit->device);
1803
1804                 if (bit->time > pdi->last_read_time)
1805                         pdi->last_read_time = bit->time;
1806
1807                 events++;
1808         }
1809
1810         return events;
1811 }
1812
1813 static int do_file(void)
1814 {
1815         struct per_cpu_info *pci;
1816         struct per_dev_info *pdi;
1817         int i, j, events, events_added;
1818
1819         /*
1820          * first prepare all files for reading
1821          */
1822         for (i = 0; i < ndevices; i++) {
1823                 pdi = &devices[i];
1824                 pdi->nfiles = 0;
1825                 pdi->last_sequence = -1;
1826
1827                 for (j = 0;; j++) {
1828                         struct stat st;
1829                         int len = 0;
1830                         char *p, *dname;
1831
1832                         pci = get_cpu_info(pdi, j);
1833                         pci->cpu = j;
1834                         pci->fd = -1;
1835                         pci->fdblock = -1;
1836         
1837                         p = strdup(pdi->name);
1838                         dname = dirname(p);
1839                         if (strcmp(dname, ".")) {
1840                                 input_dir = dname;
1841                                 p = strdup(pdi->name);
1842                                 strcpy(pdi->name, basename(p));
1843                         }
1844                         free(p);
1845
1846                         if (input_dir)
1847                                 len = sprintf(pci->fname, "%s/", input_dir);
1848
1849                         snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
1850                                  "%s.blktrace.%d", pdi->name, pci->cpu);
1851                         if (stat(pci->fname, &st) < 0)
1852                                 break;
1853                         if (st.st_size) {
1854                                 pci->fd = open(pci->fname, O_RDONLY);
1855                                 if (pci->fd < 0) {
1856                                         perror(pci->fname);
1857                                         continue;
1858                                 }
1859                         }
1860
1861                         printf("Input file %s added\n", pci->fname);
1862                         pdi->nfiles++;
1863                         cpu_mark_online(pdi, pci->cpu);
1864                 }
1865         }
1866
1867         /*
1868          * now loop over the files reading in the data
1869          */
1870         do {
1871                 unsigned long long youngest;
1872
1873                 events_added = 0;
1874                 last_allowed_time = -1ULL;
1875                 smallest_seq_read = -1U;
1876
1877                 for (i = 0; i < ndevices; i++) {
1878                         pdi = &devices[i];
1879
1880                         for (j = 0; j < pdi->nfiles; j++) {
1881
1882                                 pci = get_cpu_info(pdi, j);
1883
1884                                 if (pci->fd == -1)
1885                                         continue;
1886
1887                                 events = read_events(pci->fd, 1, &pci->fdblock);
1888                                 if (events <= 0) {
1889                                         cpu_mark_offline(pdi, pci->cpu);
1890                                         close(pci->fd);
1891                                         pci->fd = -1;
1892                                         continue;
1893                                 }
1894
1895                                 if (pdi->last_read_time < last_allowed_time)
1896                                         last_allowed_time = pdi->last_read_time;
1897
1898                                 events_added += events;
1899                         }
1900                 }
1901
1902                 if (sort_entries(&youngest))
1903                         break;
1904
1905                 if (youngest > stopwatch_end)
1906                         break;
1907
1908                 show_entries_rb(0);
1909
1910         } while (events_added);
1911
1912         if (rb_sort_entries)
1913                 show_entries_rb(1);
1914
1915         return 0;
1916 }
1917
1918 static int do_stdin(void)
1919 {
1920         unsigned long long youngest;
1921         int fd, events, fdblock;
1922
1923         last_allowed_time = -1ULL;
1924         fd = dup(STDIN_FILENO);
1925         if (fd == -1) {
1926                 perror("dup stdin");
1927                 return -1;
1928         }
1929
1930         fdblock = -1;
1931         while ((events = read_events(fd, 0, &fdblock)) > 0) {
1932         
1933                 smallest_seq_read = -1U;
1934
1935                 if (sort_entries(&youngest))
1936                         break;
1937
1938                 if (youngest > stopwatch_end)
1939                         break;
1940
1941                 show_entries_rb(0);
1942         }
1943
1944         if (rb_sort_entries)
1945                 show_entries_rb(1);
1946
1947         close(fd);
1948         return 0;
1949 }
1950
1951 static void show_stats(void)
1952 {
1953         if (!ofp)
1954                 return;
1955         if (stats_printed)
1956                 return;
1957
1958         stats_printed = 1;
1959
1960         if (per_process_stats)
1961                 show_process_stats();
1962
1963         if (per_device_and_cpu_stats)
1964                 show_device_and_cpu_stats();
1965
1966         fflush(ofp);
1967 }
1968
1969 static void handle_sigint(__attribute__((__unused__)) int sig)
1970 {
1971         done = 1;
1972 }
1973
1974 /*
1975  * Extract start and duration times from a string, allowing
1976  * us to specify a time interval of interest within a trace.
1977  * Format: "duration" (start is zero) or "start:duration".
1978  */
1979 static int find_stopwatch_interval(char *string)
1980 {
1981         double value;
1982         char *sp;
1983
1984         value = strtod(string, &sp);
1985         if (sp == string) {
1986                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
1987                 return 1;
1988         }
1989         if (*sp == ':') {
1990                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
1991                 string = sp + 1;
1992                 value = strtod(string, &sp);
1993                 if (sp == string || *sp != '\0') {
1994                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
1995                                 string);
1996                         return 1;
1997                 }
1998         } else if (*sp != '\0') {
1999                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
2000                 return 1;
2001         }
2002         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
2003         if (stopwatch_end <= stopwatch_start) {
2004                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
2005                         stopwatch_start, stopwatch_end);
2006                 return 1;
2007         }
2008
2009         return 0;
2010 }
2011
2012 static char usage_str[] = \
2013         "[ -i <input name> ] [-o <output name> [ -s ] [ -t ] [ -q ]\n" \
2014         "[ -w start:stop ] [ -f output format ] [ -F format spec ] [ -v] \n\n" \
2015         "\t-i Input file containing trace data, or '-' for stdin\n" \
2016         "\t-D Directory to prepend to input file names\n" \
2017         "\t-o Output file. If not given, output is stdout\n" \
2018         "\t-b stdin read batching\n" \
2019         "\t-s Show per-program io statistics\n" \
2020         "\t-h Hash processes by name, not pid\n" \
2021         "\t-t Track individual ios. Will tell you the time a request took\n" \
2022         "\t   to get queued, to get dispatched, and to get completed\n" \
2023         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
2024         "\t-w Only parse data between the given time interval in seconds.\n" \
2025         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
2026         "\t-f Output format. Customize the output format. The format field\n" \
2027         "\t   identifies can be found in the documentation\n" \
2028         "\t-F Format specification. Can be found in the documentation\n" \
2029         "\t-v More verbose for marginal errors\n" \
2030         "\t-V Print program version info\n\n";
2031
2032 static void usage(char *prog)
2033 {
2034         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
2035 }
2036
2037 int main(int argc, char *argv[])
2038 {
2039         char *ofp_buffer;
2040         int i, c, ret, mode;
2041         int act_mask_tmp = 0;
2042
2043         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
2044                 switch (c) {
2045                 case 'a':
2046                         i = find_mask_map(optarg);
2047                         if (i < 0) {
2048                                 fprintf(stderr,"Invalid action mask %s\n",
2049                                         optarg);
2050                                 return 1;
2051                         }
2052                         act_mask_tmp |= i;
2053                         break;
2054
2055                 case 'A':
2056                         if ((sscanf(optarg, "%x", &i) != 1) || 
2057                                                         !valid_act_opt(i)) {
2058                                 fprintf(stderr,
2059                                         "Invalid set action mask %s/0x%x\n",
2060                                         optarg, i);
2061                                 return 1;
2062                         }
2063                         act_mask_tmp = i;
2064                         break;
2065                 case 'i':
2066                         if (!strcmp(optarg, "-") && !pipeline)
2067                                 pipeline = 1;
2068                         else if (resize_devices(optarg) != 0)
2069                                 return 1;
2070                         break;
2071                 case 'D':
2072                         input_dir = optarg;
2073                         break;
2074                 case 'o':
2075                         output_name = optarg;
2076                         break;
2077                 case 'b':
2078                         rb_batch = atoi(optarg);
2079                         if (rb_batch <= 0)
2080                                 rb_batch = RB_BATCH_DEFAULT;
2081                         break;
2082                 case 's':
2083                         per_process_stats = 1;
2084                         break;
2085                 case 't':
2086                         track_ios = 1;
2087                         break;
2088                 case 'q':
2089                         per_device_and_cpu_stats = 0;
2090                         break;
2091                 case 'w':
2092                         if (find_stopwatch_interval(optarg) != 0)
2093                                 return 1;
2094                         break;
2095                 case 'f':
2096                         set_all_format_specs(optarg);
2097                         break;
2098                 case 'F':
2099                         if (add_format_spec(optarg) != 0)
2100                                 return 1;
2101                         break;
2102                 case 'h':
2103                         ppi_hash_by_pid = 0;
2104                         break;
2105                 case 'v':
2106                         verbose++;
2107                         break;
2108                 case 'V':
2109                         printf("%s version %s\n", argv[0], blkparse_version);
2110                         return 0;
2111                 default:
2112                         usage(argv[0]);
2113                         return 1;
2114                 }
2115         }
2116
2117         while (optind < argc) {
2118                 if (!strcmp(argv[optind], "-") && !pipeline)
2119                         pipeline = 1;
2120                 else if (resize_devices(argv[optind]) != 0)
2121                         return 1;
2122                 optind++;
2123         }
2124
2125         if (!pipeline && !ndevices) {
2126                 usage(argv[0]);
2127                 return 1;
2128         }
2129
2130         if (act_mask_tmp != 0)
2131                 act_mask = act_mask_tmp;
2132
2133         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
2134
2135         signal(SIGINT, handle_sigint);
2136         signal(SIGHUP, handle_sigint);
2137         signal(SIGTERM, handle_sigint);
2138
2139         setlocale(LC_NUMERIC, "en_US");
2140
2141         if (!output_name) {
2142                 ofp = fdopen(STDOUT_FILENO, "w");
2143                 mode = _IOLBF;
2144         } else {
2145                 char ofname[128];
2146
2147                 snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
2148                 ofp = fopen(ofname, "w");
2149                 mode = _IOFBF;
2150         }
2151
2152         if (!ofp) {
2153                 perror("fopen");
2154                 return 1;
2155         }
2156
2157         ofp_buffer = malloc(4096);      
2158         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
2159                 perror("setvbuf");
2160                 return 1;
2161         }
2162
2163         if (pipeline)
2164                 ret = do_stdin();
2165         else
2166                 ret = do_file();
2167
2168         show_stats();
2169         free(ofp_buffer);
2170         return ret;
2171 }