Merge branch 'fix-m' into add-P
[blktrace.git] / blkparse.c
1 /*
2  * block queue tracing parse application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  * Copyright (C) 2006 Jens Axboe <axboe@kernel.dk>
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <stdio.h>
26 #include <fcntl.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <getopt.h>
30 #include <errno.h>
31 #include <signal.h>
32 #include <locale.h>
33 #include <libgen.h>
34
35 #include "blktrace.h"
36 #include "rbtree.h"
37 #include "jhash.h"
38
39 static char blkparse_version[] = "1.0.0";
40
41 struct skip_info {
42         unsigned long start, end;
43         struct skip_info *prev, *next;
44 };
45
46 struct per_dev_info {
47         dev_t dev;
48         char *name;
49
50         int backwards;
51         unsigned long long events;
52         unsigned long long first_reported_time;
53         unsigned long long last_reported_time;
54         unsigned long long last_read_time;
55         struct io_stats io_stats;
56         unsigned long skips;
57         unsigned long long seq_skips;
58         unsigned int max_depth[2];
59         unsigned int cur_depth[2];
60
61         struct rb_root rb_track;
62
63         int nfiles;
64         int ncpus;
65
66         unsigned long *cpu_map;
67         unsigned int cpu_map_max;
68
69         struct per_cpu_info *cpus;
70 };
71
72 /*
73  * some duplicated effort here, we can unify this hash and the ppi hash later
74  */
75 struct process_pid_map {
76         pid_t pid;
77         char comm[16];
78         struct process_pid_map *hash_next, *list_next;
79 };
80
81 #define PPM_HASH_SHIFT  (8)
82 #define PPM_HASH_SIZE   (1 << PPM_HASH_SHIFT)
83 #define PPM_HASH_MASK   (PPM_HASH_SIZE - 1)
84 static struct process_pid_map *ppm_hash_table[PPM_HASH_SIZE];
85
86 struct per_process_info {
87         struct process_pid_map *ppm;
88         struct io_stats io_stats;
89         struct per_process_info *hash_next, *list_next;
90         int more_than_one;
91
92         /*
93          * individual io stats
94          */
95         unsigned long long longest_allocation_wait[2];
96         unsigned long long longest_dispatch_wait[2];
97         unsigned long long longest_completion_wait[2];
98 };
99
100 #define PPI_HASH_SHIFT  (8)
101 #define PPI_HASH_SIZE   (1 << PPI_HASH_SHIFT)
102 #define PPI_HASH_MASK   (PPI_HASH_SIZE - 1)
103 static struct per_process_info *ppi_hash_table[PPI_HASH_SIZE];
104 static struct per_process_info *ppi_list;
105 static int ppi_list_entries;
106
107 #define S_OPTS  "a:A:b:D:d:f:F:hi:o:Oqstw:vV"
108 static struct option l_opts[] = {
109         {
110                 .name = "act-mask",
111                 .has_arg = required_argument,
112                 .flag = NULL,
113                 .val = 'a'
114         },
115         {
116                 .name = "set-mask",
117                 .has_arg = required_argument,
118                 .flag = NULL,
119                 .val = 'A'
120         },
121         {
122                 .name = "batch",
123                 .has_arg = required_argument,
124                 .flag = NULL,
125                 .val = 'b'
126         },
127         {
128                 .name = "input-directory",
129                 .has_arg = required_argument,
130                 .flag = NULL,
131                 .val = 'D'
132         },
133         {
134                 .name = "dump-binary",
135                 .has_arg = required_argument,
136                 .flag = NULL,
137                 .val = 'd'
138         },
139         {
140                 .name = "format",
141                 .has_arg = required_argument,
142                 .flag = NULL,
143                 .val = 'f'
144         },
145         {
146                 .name = "format-spec",
147                 .has_arg = required_argument,
148                 .flag = NULL,
149                 .val = 'F'
150         },
151         {
152                 .name = "hash-by-name",
153                 .has_arg = no_argument,
154                 .flag = NULL,
155                 .val = 'h'
156         },
157         {
158                 .name = "input",
159                 .has_arg = required_argument,
160                 .flag = NULL,
161                 .val = 'i'
162         },
163         {
164                 .name = "output",
165                 .has_arg = required_argument,
166                 .flag = NULL,
167                 .val = 'o'
168         },
169         {
170                 .name = "no-text-output",
171                 .has_arg = no_argument,
172                 .flag = NULL,
173                 .val = 'O'
174         },
175         {
176                 .name = "quiet",
177                 .has_arg = no_argument,
178                 .flag = NULL,
179                 .val = 'q'
180         },
181         {
182                 .name = "per-program-stats",
183                 .has_arg = no_argument,
184                 .flag = NULL,
185                 .val = 's'
186         },
187         {
188                 .name = "track-ios",
189                 .has_arg = no_argument,
190                 .flag = NULL,
191                 .val = 't'
192         },
193         {
194                 .name = "stopwatch",
195                 .has_arg = required_argument,
196                 .flag = NULL,
197                 .val = 'w'
198         },
199         {
200                 .name = "verbose",
201                 .has_arg = no_argument,
202                 .flag = NULL,
203                 .val = 'v'
204         },
205         {
206                 .name = "version",
207                 .has_arg = no_argument,
208                 .flag = NULL,
209                 .val = 'V'
210         },
211         {
212                 .name = NULL,
213         }
214 };
215
216 /*
217  * for sorting the displayed output
218  */
219 struct trace {
220         struct blk_io_trace *bit;
221         struct rb_node rb_node;
222         struct trace *next;
223         unsigned long read_sequence;
224 };
225
226 static struct rb_root rb_sort_root;
227 static unsigned long rb_sort_entries;
228
229 static struct trace *trace_list;
230
231 /*
232  * allocation cache
233  */
234 static struct blk_io_trace *bit_alloc_list;
235 static struct trace *t_alloc_list;
236
237 /*
238  * for tracking individual ios
239  */
240 struct io_track {
241         struct rb_node rb_node;
242
243         struct process_pid_map *ppm;
244         __u64 sector;
245         unsigned long long allocation_time;
246         unsigned long long queue_time;
247         unsigned long long dispatch_time;
248         unsigned long long completion_time;
249 };
250
251 static int ndevices;
252 static struct per_dev_info *devices;
253 static char *get_dev_name(struct per_dev_info *, char *, int);
254 static int trace_rb_insert_last(struct per_dev_info *, struct trace *);
255
256 FILE *ofp = NULL;
257 static char *output_name;
258 static char *input_dir;
259
260 static unsigned long long genesis_time;
261 static unsigned long long last_allowed_time;
262 static unsigned long long stopwatch_start;      /* start from zero by default */
263 static unsigned long long stopwatch_end = -1ULL;        /* "infinity" */
264 static unsigned long read_sequence;
265
266 static int per_process_stats;
267 static int per_device_and_cpu_stats = 1;
268 static int track_ios;
269 static int ppi_hash_by_pid = 1;
270 static int verbose;
271 static unsigned int act_mask = -1U;
272 static int stats_printed;
273 int data_is_native = -1;
274
275 static FILE *dump_fp;
276 static char *dump_binary;
277
278 static unsigned int t_alloc_cache;
279 static unsigned int bit_alloc_cache;
280
281 #define RB_BATCH_DEFAULT        (512)
282 static unsigned int rb_batch = RB_BATCH_DEFAULT;
283
284 static int pipeline;
285 static char *pipename;
286
287 static int text_output = 1;
288
289 #define is_done()       (*(volatile int *)(&done))
290 static volatile int done;
291
292 struct timespec         abs_start_time;
293 static unsigned long long start_timestamp;
294
295 static int have_drv_data = 0;
296
297 #define JHASH_RANDOM    (0x3af5f2ee)
298
299 #define CPUS_PER_LONG   (8 * sizeof(unsigned long))
300 #define CPU_IDX(cpu)    ((cpu) / CPUS_PER_LONG)
301 #define CPU_BIT(cpu)    ((cpu) & (CPUS_PER_LONG - 1))
302
303 static void output_binary(void *buf, int len)
304 {
305         if (dump_binary) {
306                 size_t n = fwrite(buf, len, 1, dump_fp);
307                 if (n != 1) {
308                         perror(dump_binary);
309                         fclose(dump_fp);
310                         dump_binary = NULL;
311                 }
312         }
313 }
314
315 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
316 {
317         struct per_cpu_info *cpus = pdi->cpus;
318         int ncpus = pdi->ncpus;
319         int new_count = cpu + 1;
320         int new_space, size;
321         char *new_start;
322
323         size = new_count * sizeof(struct per_cpu_info);
324         cpus = realloc(cpus, size);
325         if (!cpus) {
326                 char name[20];
327                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
328                         get_dev_name(pdi, name, sizeof(name)), size);
329                 exit(1);
330         }
331
332         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
333         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
334         memset(new_start, 0, new_space);
335
336         pdi->ncpus = new_count;
337         pdi->cpus = cpus;
338
339         for (new_count = 0; new_count < pdi->ncpus; new_count++) {
340                 struct per_cpu_info *pci = &pdi->cpus[new_count];
341
342                 if (!pci->fd) {
343                         pci->fd = -1;
344                         memset(&pci->rb_last, 0, sizeof(pci->rb_last));
345                         pci->rb_last_entries = 0;
346                         pci->last_sequence = -1;
347                 }
348         }
349 }
350
351 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
352 {
353         struct per_cpu_info *pci;
354
355         if (cpu >= pdi->ncpus)
356                 resize_cpu_info(pdi, cpu);
357
358         pci = &pdi->cpus[cpu];
359         pci->cpu = cpu;
360         return pci;
361 }
362
363
364 static int resize_devices(char *name)
365 {
366         int size = (ndevices + 1) * sizeof(struct per_dev_info);
367
368         devices = realloc(devices, size);
369         if (!devices) {
370                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
371                 return 1;
372         }
373         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
374         devices[ndevices].name = name;
375         ndevices++;
376         return 0;
377 }
378
379 static struct per_dev_info *get_dev_info(dev_t dev)
380 {
381         struct per_dev_info *pdi;
382         int i;
383
384         for (i = 0; i < ndevices; i++) {
385                 if (!devices[i].dev)
386                         devices[i].dev = dev;
387                 if (devices[i].dev == dev)
388                         return &devices[i];
389         }
390
391         if (resize_devices(NULL))
392                 return NULL;
393
394         pdi = &devices[ndevices - 1];
395         pdi->dev = dev;
396         pdi->first_reported_time = 0;
397         pdi->last_read_time = 0;
398
399         return pdi;
400 }
401
402 static void insert_skip(struct per_cpu_info *pci, unsigned long start,
403                         unsigned long end)
404 {
405         struct skip_info *sip;
406
407         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
408                 if (end == (sip->start - 1)) {
409                         sip->start = start;
410                         return;
411                 } else if (start == (sip->end + 1)) {
412                         sip->end = end;
413                         return;
414                 }
415         }
416
417         sip = malloc(sizeof(struct skip_info));
418         sip->start = start;
419         sip->end = end;
420         sip->prev = sip->next = NULL;
421         if (pci->skips_tail == NULL)
422                 pci->skips_head = pci->skips_tail = sip;
423         else {
424                 sip->prev = pci->skips_tail;
425                 pci->skips_tail->next = sip;
426                 pci->skips_tail = sip;
427         }
428 }
429
430 static void remove_sip(struct per_cpu_info *pci, struct skip_info *sip)
431 {
432         if (sip->prev == NULL) {
433                 if (sip->next == NULL)
434                         pci->skips_head = pci->skips_tail = NULL;
435                 else {
436                         pci->skips_head = sip->next;
437                         sip->next->prev = NULL;
438                 }
439         } else if (sip->next == NULL) {
440                 pci->skips_tail = sip->prev;
441                 sip->prev->next = NULL;
442         } else {
443                 sip->prev->next = sip->next;
444                 sip->next->prev = sip->prev;
445         }
446
447         sip->prev = sip->next = NULL;
448         free(sip);
449 }
450
451 #define IN_SKIP(sip,seq) (((sip)->start <= (seq)) && ((seq) <= sip->end))
452 static int check_current_skips(struct per_cpu_info *pci, unsigned long seq)
453 {
454         struct skip_info *sip;
455
456         for (sip = pci->skips_tail; sip != NULL; sip = sip->prev) {
457                 if (IN_SKIP(sip, seq)) {
458                         if (sip->start == seq) {
459                                 if (sip->end == seq)
460                                         remove_sip(pci, sip);
461                                 else
462                                         sip->start += 1;
463                         } else if (sip->end == seq)
464                                 sip->end -= 1;
465                         else {
466                                 sip->end = seq - 1;
467                                 insert_skip(pci, seq + 1, sip->end);
468                         }
469                         return 1;
470                 }
471         }
472
473         return 0;
474 }
475
476 static void collect_pdi_skips(struct per_dev_info *pdi)
477 {
478         struct skip_info *sip;
479         int cpu;
480
481         pdi->skips = 0;
482         pdi->seq_skips = 0;
483
484         for (cpu = 0; cpu < pdi->ncpus; cpu++) {
485                 struct per_cpu_info *pci = &pdi->cpus[cpu];
486
487                 for (sip = pci->skips_head; sip != NULL; sip = sip->next) {
488                         pdi->skips++;
489                         pdi->seq_skips += (sip->end - sip->start + 1);
490                         if (verbose)
491                                 fprintf(stderr,"(%d,%d): skipping %lu -> %lu\n",
492                                         MAJOR(pdi->dev), MINOR(pdi->dev),
493                                         sip->start, sip->end);
494                 }
495         }
496 }
497
498 static void cpu_mark_online(struct per_dev_info *pdi, unsigned int cpu)
499 {
500         if (cpu >= pdi->cpu_map_max || !pdi->cpu_map) {
501                 int new_max = (cpu + CPUS_PER_LONG) & ~(CPUS_PER_LONG - 1);
502                 unsigned long *map = malloc(new_max / sizeof(long));
503
504                 memset(map, 0, new_max / sizeof(long));
505
506                 if (pdi->cpu_map) {
507                         memcpy(map, pdi->cpu_map, pdi->cpu_map_max / sizeof(long));
508                         free(pdi->cpu_map);
509                 }
510
511                 pdi->cpu_map = map;
512                 pdi->cpu_map_max = new_max;
513         }
514
515         pdi->cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
516 }
517
518 static inline void cpu_mark_offline(struct per_dev_info *pdi, int cpu)
519 {
520         pdi->cpu_map[CPU_IDX(cpu)] &= ~(1UL << CPU_BIT(cpu));
521 }
522
523 static inline int cpu_is_online(struct per_dev_info *pdi, int cpu)
524 {
525         return (pdi->cpu_map[CPU_IDX(cpu)] & (1UL << CPU_BIT(cpu))) != 0;
526 }
527
528 static inline int ppm_hash_pid(pid_t pid)
529 {
530         return jhash_1word(pid, JHASH_RANDOM) & PPM_HASH_MASK;
531 }
532
533 static struct process_pid_map *find_ppm(pid_t pid)
534 {
535         const int hash_idx = ppm_hash_pid(pid);
536         struct process_pid_map *ppm;
537
538         ppm = ppm_hash_table[hash_idx];
539         while (ppm) {
540                 if (ppm->pid == pid)
541                         return ppm;
542
543                 ppm = ppm->hash_next;
544         }
545
546         return NULL;
547 }
548
549 static struct process_pid_map *add_ppm_hash(pid_t pid, const char *name)
550 {
551         const int hash_idx = ppm_hash_pid(pid);
552         struct process_pid_map *ppm;
553
554         ppm = find_ppm(pid);
555         if (!ppm) {
556                 ppm = malloc(sizeof(*ppm));
557                 memset(ppm, 0, sizeof(*ppm));
558                 ppm->pid = pid;
559                 strcpy(ppm->comm, name);
560                 ppm->hash_next = ppm_hash_table[hash_idx];
561                 ppm_hash_table[hash_idx] = ppm;
562         }
563
564         return ppm;
565 }
566
567 static void handle_notify(struct blk_io_trace *bit)
568 {
569         void    *payload = (caddr_t) bit + sizeof(*bit);
570         __u32   two32[2];
571
572         switch (bit->action) {
573         case BLK_TN_PROCESS:
574                 add_ppm_hash(bit->pid, payload);
575                 break;
576
577         case BLK_TN_TIMESTAMP:
578                 if (bit->pdu_len != sizeof(two32))
579                         return;
580                 memcpy(two32, payload, sizeof(two32));
581                 if (!data_is_native) {
582                         two32[0] = be32_to_cpu(two32[0]);
583                         two32[1] = be32_to_cpu(two32[1]);
584                 }
585                 start_timestamp = bit->time;
586                 abs_start_time.tv_sec  = two32[0];
587                 abs_start_time.tv_nsec = two32[1];
588                 if (abs_start_time.tv_nsec < 0) {
589                         abs_start_time.tv_sec--;
590                         abs_start_time.tv_nsec += 1000000000;
591                 }
592
593                 break;
594
595         case BLK_TN_MESSAGE:
596                 if (bit->pdu_len > 0) {
597                         char msg[bit->pdu_len+1];
598
599                         memcpy(msg, (char *)payload, bit->pdu_len);
600                         msg[bit->pdu_len] = '\0';
601
602                         fprintf(ofp,
603                                 "%3d,%-3d %2d %8s %5d.%09lu %5u %2s %3s %s\n",
604                                 MAJOR(bit->device), MINOR(bit->device),
605                                 bit->cpu, "0", (int) SECONDS(bit->time),
606                                 (unsigned long) NANO_SECONDS(bit->time),
607                                 0, "m", "N", msg);
608                 }
609                 break;
610
611         default:
612                 /* Ignore unknown notify events */
613                 ;
614         }
615 }
616
617 char *find_process_name(pid_t pid)
618 {
619         struct process_pid_map *ppm = find_ppm(pid);
620
621         if (ppm)
622                 return ppm->comm;
623
624         return NULL;
625 }
626
627 static inline int ppi_hash_pid(pid_t pid)
628 {
629         return jhash_1word(pid, JHASH_RANDOM) & PPI_HASH_MASK;
630 }
631
632 static inline int ppi_hash_name(const char *name)
633 {
634         return jhash(name, 16, JHASH_RANDOM) & PPI_HASH_MASK;
635 }
636
637 static inline int ppi_hash(struct per_process_info *ppi)
638 {
639         struct process_pid_map *ppm = ppi->ppm;
640
641         if (ppi_hash_by_pid)
642                 return ppi_hash_pid(ppm->pid);
643
644         return ppi_hash_name(ppm->comm);
645 }
646
647 static inline void add_ppi_to_hash(struct per_process_info *ppi)
648 {
649         const int hash_idx = ppi_hash(ppi);
650
651         ppi->hash_next = ppi_hash_table[hash_idx];
652         ppi_hash_table[hash_idx] = ppi;
653 }
654
655 static inline void add_ppi_to_list(struct per_process_info *ppi)
656 {
657         ppi->list_next = ppi_list;
658         ppi_list = ppi;
659         ppi_list_entries++;
660 }
661
662 static struct per_process_info *find_ppi_by_name(char *name)
663 {
664         const int hash_idx = ppi_hash_name(name);
665         struct per_process_info *ppi;
666
667         ppi = ppi_hash_table[hash_idx];
668         while (ppi) {
669                 struct process_pid_map *ppm = ppi->ppm;
670
671                 if (!strcmp(ppm->comm, name))
672                         return ppi;
673
674                 ppi = ppi->hash_next;
675         }
676
677         return NULL;
678 }
679
680 static struct per_process_info *find_ppi_by_pid(pid_t pid)
681 {
682         const int hash_idx = ppi_hash_pid(pid);
683         struct per_process_info *ppi;
684
685         ppi = ppi_hash_table[hash_idx];
686         while (ppi) {
687                 struct process_pid_map *ppm = ppi->ppm;
688
689                 if (ppm->pid == pid)
690                         return ppi;
691
692                 ppi = ppi->hash_next;
693         }
694
695         return NULL;
696 }
697
698 static struct per_process_info *find_ppi(pid_t pid)
699 {
700         struct per_process_info *ppi;
701         char *name;
702
703         if (ppi_hash_by_pid)
704                 return find_ppi_by_pid(pid);
705
706         name = find_process_name(pid);
707         if (!name)
708                 return NULL;
709
710         ppi = find_ppi_by_name(name);
711         if (ppi && ppi->ppm->pid != pid)
712                 ppi->more_than_one = 1;
713
714         return ppi;
715 }
716
717 /*
718  * struct trace and blktrace allocation cache, we do potentially
719  * millions of mallocs for these structures while only using at most
720  * a few thousand at the time
721  */
722 static inline void t_free(struct trace *t)
723 {
724         if (t_alloc_cache < 1024) {
725                 t->next = t_alloc_list;
726                 t_alloc_list = t;
727                 t_alloc_cache++;
728         } else
729                 free(t);
730 }
731
732 static inline struct trace *t_alloc(void)
733 {
734         struct trace *t = t_alloc_list;
735
736         if (t) {
737                 t_alloc_list = t->next;
738                 t_alloc_cache--;
739                 return t;
740         }
741
742         return malloc(sizeof(*t));
743 }
744
745 static inline void bit_free(struct blk_io_trace *bit)
746 {
747         if (bit_alloc_cache < 1024 && !bit->pdu_len) {
748                 /*
749                  * abuse a 64-bit field for a next pointer for the free item
750                  */
751                 bit->time = (__u64) (unsigned long) bit_alloc_list;
752                 bit_alloc_list = (struct blk_io_trace *) bit;
753                 bit_alloc_cache++;
754         } else
755                 free(bit);
756 }
757
758 static inline struct blk_io_trace *bit_alloc(void)
759 {
760         struct blk_io_trace *bit = bit_alloc_list;
761
762         if (bit) {
763                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
764                                  bit->time;
765                 bit_alloc_cache--;
766                 return bit;
767         }
768
769         return malloc(sizeof(*bit));
770 }
771
772 static inline void __put_trace_last(struct per_dev_info *pdi, struct trace *t)
773 {
774         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
775
776         rb_erase(&t->rb_node, &pci->rb_last);
777         pci->rb_last_entries--;
778
779         bit_free(t->bit);
780         t_free(t);
781 }
782
783 static void put_trace(struct per_dev_info *pdi, struct trace *t)
784 {
785         rb_erase(&t->rb_node, &rb_sort_root);
786         rb_sort_entries--;
787
788         trace_rb_insert_last(pdi, t);
789 }
790
791 static inline int trace_rb_insert(struct trace *t, struct rb_root *root)
792 {
793         struct rb_node **p = &root->rb_node;
794         struct rb_node *parent = NULL;
795         struct trace *__t;
796
797         while (*p) {
798                 parent = *p;
799
800                 __t = rb_entry(parent, struct trace, rb_node);
801
802                 if (t->bit->time < __t->bit->time)
803                         p = &(*p)->rb_left;
804                 else if (t->bit->time > __t->bit->time)
805                         p = &(*p)->rb_right;
806                 else if (t->bit->device < __t->bit->device)
807                         p = &(*p)->rb_left;
808                 else if (t->bit->device > __t->bit->device)
809                         p = &(*p)->rb_right;
810                 else if (t->bit->sequence < __t->bit->sequence)
811                         p = &(*p)->rb_left;
812                 else    /* >= sequence */
813                         p = &(*p)->rb_right;
814         }
815
816         rb_link_node(&t->rb_node, parent, p);
817         rb_insert_color(&t->rb_node, root);
818         return 0;
819 }
820
821 static inline int trace_rb_insert_sort(struct trace *t)
822 {
823         if (!trace_rb_insert(t, &rb_sort_root)) {
824                 rb_sort_entries++;
825                 return 0;
826         }
827
828         return 1;
829 }
830
831 static int trace_rb_insert_last(struct per_dev_info *pdi, struct trace *t)
832 {
833         struct per_cpu_info *pci = get_cpu_info(pdi, t->bit->cpu);
834
835         if (trace_rb_insert(t, &pci->rb_last))
836                 return 1;
837
838         pci->rb_last_entries++;
839
840         if (pci->rb_last_entries > rb_batch * pdi->nfiles) {
841                 struct rb_node *n = rb_first(&pci->rb_last);
842
843                 t = rb_entry(n, struct trace, rb_node);
844                 __put_trace_last(pdi, t);
845         }
846
847         return 0;
848 }
849
850 static struct trace *trace_rb_find(dev_t device, unsigned long sequence,
851                                    struct rb_root *root, int order)
852 {
853         struct rb_node *n = root->rb_node;
854         struct rb_node *prev = NULL;
855         struct trace *__t;
856
857         while (n) {
858                 __t = rb_entry(n, struct trace, rb_node);
859                 prev = n;
860
861                 if (device < __t->bit->device)
862                         n = n->rb_left;
863                 else if (device > __t->bit->device)
864                         n = n->rb_right;
865                 else if (sequence < __t->bit->sequence)
866                         n = n->rb_left;
867                 else if (sequence > __t->bit->sequence)
868                         n = n->rb_right;
869                 else
870                         return __t;
871         }
872
873         /*
874          * hack - the list may not be sequence ordered because some
875          * events don't have sequence and time matched. so we end up
876          * being a little off in the rb lookup here, because we don't
877          * know the time we are looking for. compensate by browsing
878          * a little ahead from the last entry to find the match
879          */
880         if (order && prev) {
881                 int max = 5;
882
883                 while (((n = rb_next(prev)) != NULL) && max--) {
884                         __t = rb_entry(n, struct trace, rb_node);
885
886                         if (__t->bit->device == device &&
887                             __t->bit->sequence == sequence)
888                                 return __t;
889
890                         prev = n;
891                 }
892         }
893
894         return NULL;
895 }
896
897 static inline struct trace *trace_rb_find_last(struct per_dev_info *pdi,
898                                                struct per_cpu_info *pci,
899                                                unsigned long seq)
900 {
901         return trace_rb_find(pdi->dev, seq, &pci->rb_last, 0);
902 }
903
904 static inline int track_rb_insert(struct per_dev_info *pdi,struct io_track *iot)
905 {
906         struct rb_node **p = &pdi->rb_track.rb_node;
907         struct rb_node *parent = NULL;
908         struct io_track *__iot;
909
910         while (*p) {
911                 parent = *p;
912                 __iot = rb_entry(parent, struct io_track, rb_node);
913
914                 if (iot->sector < __iot->sector)
915                         p = &(*p)->rb_left;
916                 else if (iot->sector > __iot->sector)
917                         p = &(*p)->rb_right;
918                 else {
919                         fprintf(stderr,
920                                 "sector alias (%Lu) on device %d,%d!\n",
921                                 (unsigned long long) iot->sector,
922                                 MAJOR(pdi->dev), MINOR(pdi->dev));
923                         return 1;
924                 }
925         }
926
927         rb_link_node(&iot->rb_node, parent, p);
928         rb_insert_color(&iot->rb_node, &pdi->rb_track);
929         return 0;
930 }
931
932 static struct io_track *__find_track(struct per_dev_info *pdi, __u64 sector)
933 {
934         struct rb_node *n = pdi->rb_track.rb_node;
935         struct io_track *__iot;
936
937         while (n) {
938                 __iot = rb_entry(n, struct io_track, rb_node);
939
940                 if (sector < __iot->sector)
941                         n = n->rb_left;
942                 else if (sector > __iot->sector)
943                         n = n->rb_right;
944                 else
945                         return __iot;
946         }
947
948         return NULL;
949 }
950
951 static struct io_track *find_track(struct per_dev_info *pdi, pid_t pid,
952                                    __u64 sector)
953 {
954         struct io_track *iot;
955
956         iot = __find_track(pdi, sector);
957         if (!iot) {
958                 iot = malloc(sizeof(*iot));
959                 iot->ppm = find_ppm(pid);
960                 if (!iot->ppm)
961                         iot->ppm = add_ppm_hash(pid, "unknown");
962                 iot->sector = sector;
963                 track_rb_insert(pdi, iot);
964         }
965
966         return iot;
967 }
968
969 static void log_track_frontmerge(struct per_dev_info *pdi,
970                                  struct blk_io_trace *t)
971 {
972         struct io_track *iot;
973
974         if (!track_ios)
975                 return;
976
977         iot = __find_track(pdi, t->sector + t_sec(t));
978         if (!iot) {
979                 if (verbose)
980                         fprintf(stderr, "merge not found for (%d,%d): %llu\n",
981                                 MAJOR(pdi->dev), MINOR(pdi->dev),
982                                 (unsigned long long) t->sector + t_sec(t));
983                 return;
984         }
985
986         rb_erase(&iot->rb_node, &pdi->rb_track);
987         iot->sector -= t_sec(t);
988         track_rb_insert(pdi, iot);
989 }
990
991 static void log_track_getrq(struct per_dev_info *pdi, struct blk_io_trace *t)
992 {
993         struct io_track *iot;
994
995         if (!track_ios)
996                 return;
997
998         iot = find_track(pdi, t->pid, t->sector);
999         iot->allocation_time = t->time;
1000 }
1001
1002 static inline int is_remapper(struct per_dev_info *pdi)
1003 {
1004         int major = MAJOR(pdi->dev);
1005
1006         return (major == 253 || major == 9);
1007 }
1008
1009 /*
1010  * for md/dm setups, the interesting cycle is Q -> C. So track queueing
1011  * time here, as dispatch time
1012  */
1013 static void log_track_queue(struct per_dev_info *pdi, struct blk_io_trace *t)
1014 {
1015         struct io_track *iot;
1016
1017         if (!track_ios)
1018                 return;
1019         if (!is_remapper(pdi))
1020                 return;
1021
1022         iot = find_track(pdi, t->pid, t->sector);
1023         iot->dispatch_time = t->time;
1024 }
1025
1026 /*
1027  * return time between rq allocation and insertion
1028  */
1029 static unsigned long long log_track_insert(struct per_dev_info *pdi,
1030                                            struct blk_io_trace *t)
1031 {
1032         unsigned long long elapsed;
1033         struct io_track *iot;
1034
1035         if (!track_ios)
1036                 return -1;
1037
1038         iot = find_track(pdi, t->pid, t->sector);
1039         iot->queue_time = t->time;
1040
1041         if (!iot->allocation_time)
1042                 return -1;
1043
1044         elapsed = iot->queue_time - iot->allocation_time;
1045
1046         if (per_process_stats) {
1047                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1048                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1049
1050                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
1051                         ppi->longest_allocation_wait[w] = elapsed;
1052         }
1053
1054         return elapsed;
1055 }
1056
1057 /*
1058  * return time between queue and issue
1059  */
1060 static unsigned long long log_track_issue(struct per_dev_info *pdi,
1061                                           struct blk_io_trace *t)
1062 {
1063         unsigned long long elapsed;
1064         struct io_track *iot;
1065
1066         if (!track_ios)
1067                 return -1;
1068         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
1069                 return -1;
1070
1071         iot = __find_track(pdi, t->sector);
1072         if (!iot) {
1073                 if (verbose)
1074                         fprintf(stderr, "issue not found for (%d,%d): %llu\n",
1075                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1076                                 (unsigned long long) t->sector);
1077                 return -1;
1078         }
1079
1080         iot->dispatch_time = t->time;
1081         elapsed = iot->dispatch_time - iot->queue_time;
1082
1083         if (per_process_stats) {
1084                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1085                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1086
1087                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
1088                         ppi->longest_dispatch_wait[w] = elapsed;
1089         }
1090
1091         return elapsed;
1092 }
1093
1094 /*
1095  * return time between dispatch and complete
1096  */
1097 static unsigned long long log_track_complete(struct per_dev_info *pdi,
1098                                              struct blk_io_trace *t)
1099 {
1100         unsigned long long elapsed;
1101         struct io_track *iot;
1102
1103         if (!track_ios)
1104                 return -1;
1105
1106         iot = __find_track(pdi, t->sector);
1107         if (!iot) {
1108                 if (verbose)
1109                         fprintf(stderr,"complete not found for (%d,%d): %llu\n",
1110                                 MAJOR(pdi->dev), MINOR(pdi->dev),
1111                                 (unsigned long long) t->sector);
1112                 return -1;
1113         }
1114
1115         iot->completion_time = t->time;
1116         elapsed = iot->completion_time - iot->dispatch_time;
1117
1118         if (per_process_stats) {
1119                 struct per_process_info *ppi = find_ppi(iot->ppm->pid);
1120                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1121
1122                 if (ppi && elapsed > ppi->longest_completion_wait[w])
1123                         ppi->longest_completion_wait[w] = elapsed;
1124         }
1125
1126         /*
1127          * kill the trace, we don't need it after completion
1128          */
1129         rb_erase(&iot->rb_node, &pdi->rb_track);
1130         free(iot);
1131
1132         return elapsed;
1133 }
1134
1135
1136 static struct io_stats *find_process_io_stats(pid_t pid)
1137 {
1138         struct per_process_info *ppi = find_ppi(pid);
1139
1140         if (!ppi) {
1141                 ppi = malloc(sizeof(*ppi));
1142                 memset(ppi, 0, sizeof(*ppi));
1143                 ppi->ppm = find_ppm(pid);
1144                 if (!ppi->ppm)
1145                         ppi->ppm = add_ppm_hash(pid, "unknown");
1146                 add_ppi_to_hash(ppi);
1147                 add_ppi_to_list(ppi);
1148         }
1149
1150         return &ppi->io_stats;
1151 }
1152
1153 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
1154 {
1155         if (pdi->name)
1156                 snprintf(buffer, size, "%s", pdi->name);
1157         else
1158                 snprintf(buffer, size, "%d,%d",MAJOR(pdi->dev),MINOR(pdi->dev));
1159         return buffer;
1160 }
1161
1162 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
1163 {
1164         unsigned long long this = bit->time;
1165         unsigned long long last = pdi->last_reported_time;
1166
1167         pdi->backwards = (this < last) ? 'B' : ' ';
1168         pdi->last_reported_time = this;
1169 }
1170
1171 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
1172                                int rw)
1173 {
1174         if (rw) {
1175                 ios->mwrites++;
1176                 ios->mwrite_kb += t_kb(t);
1177         } else {
1178                 ios->mreads++;
1179                 ios->mread_kb += t_kb(t);
1180         }
1181 }
1182
1183 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
1184                              int rw)
1185 {
1186         __account_m(&pci->io_stats, t, rw);
1187
1188         if (per_process_stats) {
1189                 struct io_stats *ios = find_process_io_stats(t->pid);
1190
1191                 __account_m(ios, t, rw);
1192         }
1193 }
1194
1195 static inline void __account_pc_queue(struct io_stats *ios,
1196                                       struct blk_io_trace *t, int rw)
1197 {
1198         if (rw) {
1199                 ios->qwrites_pc++;
1200                 ios->qwrite_kb_pc += t_kb(t);
1201         } else {
1202                 ios->qreads_pc++;
1203                 ios->qread_kb += t_kb(t);
1204         }
1205 }
1206
1207 static inline void account_pc_queue(struct blk_io_trace *t,
1208                                     struct per_cpu_info *pci, int rw)
1209 {
1210         __account_pc_queue(&pci->io_stats, t, rw);
1211
1212         if (per_process_stats) {
1213                 struct io_stats *ios = find_process_io_stats(t->pid);
1214
1215                 __account_pc_queue(ios, t, rw);
1216         }
1217 }
1218
1219 static inline void __account_pc_issue(struct io_stats *ios, int rw,
1220                                       unsigned int bytes)
1221 {
1222         if (rw) {
1223                 ios->iwrites_pc++;
1224                 ios->iwrite_kb_pc += bytes >> 10;
1225         } else {
1226                 ios->ireads_pc++;
1227                 ios->iread_kb_pc += bytes >> 10;
1228         }
1229 }
1230
1231 static inline void account_pc_issue(struct blk_io_trace *t,
1232                                     struct per_cpu_info *pci, int rw)
1233 {
1234         __account_pc_issue(&pci->io_stats, rw, t->bytes);
1235
1236         if (per_process_stats) {
1237                 struct io_stats *ios = find_process_io_stats(t->pid);
1238
1239                 __account_pc_issue(ios, rw, t->bytes);
1240         }
1241 }
1242
1243 static inline void __account_pc_requeue(struct io_stats *ios,
1244                                         struct blk_io_trace *t, int rw)
1245 {
1246         if (rw) {
1247                 ios->wrqueue_pc++;
1248                 ios->iwrite_kb_pc -= t_kb(t);
1249         } else {
1250                 ios->rrqueue_pc++;
1251                 ios->iread_kb_pc -= t_kb(t);
1252         }
1253 }
1254
1255 static inline void account_pc_requeue(struct blk_io_trace *t,
1256                                       struct per_cpu_info *pci, int rw)
1257 {
1258         __account_pc_requeue(&pci->io_stats, t, rw);
1259
1260         if (per_process_stats) {
1261                 struct io_stats *ios = find_process_io_stats(t->pid);
1262
1263                 __account_pc_requeue(ios, t, rw);
1264         }
1265 }
1266
1267 static inline void __account_pc_c(struct io_stats *ios, int rw)
1268 {
1269         if (rw)
1270                 ios->cwrites_pc++;
1271         else
1272                 ios->creads_pc++;
1273 }
1274
1275 static inline void account_pc_c(struct blk_io_trace *t,
1276                                 struct per_cpu_info *pci, int rw)
1277 {
1278         __account_pc_c(&pci->io_stats, rw);
1279
1280         if (per_process_stats) {
1281                 struct io_stats *ios = find_process_io_stats(t->pid);
1282
1283                 __account_pc_c(ios, rw);
1284         }
1285 }
1286
1287 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
1288                                    int rw)
1289 {
1290         if (rw) {
1291                 ios->qwrites++;
1292                 ios->qwrite_kb += t_kb(t);
1293         } else {
1294                 ios->qreads++;
1295                 ios->qread_kb += t_kb(t);
1296         }
1297 }
1298
1299 static inline void account_queue(struct blk_io_trace *t,
1300                                  struct per_cpu_info *pci, int rw)
1301 {
1302         __account_queue(&pci->io_stats, t, rw);
1303
1304         if (per_process_stats) {
1305                 struct io_stats *ios = find_process_io_stats(t->pid);
1306
1307                 __account_queue(ios, t, rw);
1308         }
1309 }
1310
1311 static inline void __account_c(struct io_stats *ios, int rw, int bytes)
1312 {
1313         if (rw) {
1314                 ios->cwrites++;
1315                 ios->cwrite_kb += bytes >> 10;
1316         } else {
1317                 ios->creads++;
1318                 ios->cread_kb += bytes >> 10;
1319         }
1320 }
1321
1322 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
1323                              int rw, int bytes)
1324 {
1325         __account_c(&pci->io_stats, rw, bytes);
1326
1327         if (per_process_stats) {
1328                 struct io_stats *ios = find_process_io_stats(t->pid);
1329
1330                 __account_c(ios, rw, bytes);
1331         }
1332 }
1333
1334 static inline void __account_issue(struct io_stats *ios, int rw,
1335                                    unsigned int bytes)
1336 {
1337         if (rw) {
1338                 ios->iwrites++;
1339                 ios->iwrite_kb += bytes >> 10;
1340         } else {
1341                 ios->ireads++;
1342                 ios->iread_kb += bytes >> 10;
1343         }
1344 }
1345
1346 static inline void account_issue(struct blk_io_trace *t,
1347                                  struct per_cpu_info *pci, int rw)
1348 {
1349         __account_issue(&pci->io_stats, rw, t->bytes);
1350
1351         if (per_process_stats) {
1352                 struct io_stats *ios = find_process_io_stats(t->pid);
1353
1354                 __account_issue(ios, rw, t->bytes);
1355         }
1356 }
1357
1358 static inline void __account_unplug(struct io_stats *ios, int timer)
1359 {
1360         if (timer)
1361                 ios->timer_unplugs++;
1362         else
1363                 ios->io_unplugs++;
1364 }
1365
1366 static inline void account_unplug(struct blk_io_trace *t,
1367                                   struct per_cpu_info *pci, int timer)
1368 {
1369         __account_unplug(&pci->io_stats, timer);
1370
1371         if (per_process_stats) {
1372                 struct io_stats *ios = find_process_io_stats(t->pid);
1373
1374                 __account_unplug(ios, timer);
1375         }
1376 }
1377
1378 static inline void __account_requeue(struct io_stats *ios,
1379                                      struct blk_io_trace *t, int rw)
1380 {
1381         if (rw) {
1382                 ios->wrqueue++;
1383                 ios->iwrite_kb -= t_kb(t);
1384         } else {
1385                 ios->rrqueue++;
1386                 ios->iread_kb -= t_kb(t);
1387         }
1388 }
1389
1390 static inline void account_requeue(struct blk_io_trace *t,
1391                                    struct per_cpu_info *pci, int rw)
1392 {
1393         __account_requeue(&pci->io_stats, t, rw);
1394
1395         if (per_process_stats) {
1396                 struct io_stats *ios = find_process_io_stats(t->pid);
1397
1398                 __account_requeue(ios, t, rw);
1399         }
1400 }
1401
1402 static void log_complete(struct per_dev_info *pdi, struct per_cpu_info *pci,
1403                          struct blk_io_trace *t, char *act)
1404 {
1405         process_fmt(act, pci, t, log_track_complete(pdi, t), 0, NULL);
1406 }
1407
1408 static void log_insert(struct per_dev_info *pdi, struct per_cpu_info *pci,
1409                        struct blk_io_trace *t, char *act)
1410 {
1411         process_fmt(act, pci, t, log_track_insert(pdi, t), 0, NULL);
1412 }
1413
1414 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
1415                       char *act)
1416 {
1417         process_fmt(act, pci, t, -1, 0, NULL);
1418 }
1419
1420 static void log_issue(struct per_dev_info *pdi, struct per_cpu_info *pci,
1421                       struct blk_io_trace *t, char *act)
1422 {
1423         process_fmt(act, pci, t, log_track_issue(pdi, t), 0, NULL);
1424 }
1425
1426 static void log_merge(struct per_dev_info *pdi, struct per_cpu_info *pci,
1427                       struct blk_io_trace *t, char *act)
1428 {
1429         if (act[0] == 'F')
1430                 log_track_frontmerge(pdi, t);
1431
1432         process_fmt(act, pci, t, -1ULL, 0, NULL);
1433 }
1434
1435 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
1436                         char *act)
1437 {
1438         process_fmt(act, pci, t, -1ULL, 0, NULL);
1439 }
1440
1441 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
1442                         char *act)
1443 {
1444         process_fmt(act, pci, t, -1ULL, 0, NULL);
1445 }
1446
1447 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
1448                       char *act)
1449 {
1450         process_fmt(act, pci, t, -1ULL, 0, NULL);
1451 }
1452
1453 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
1454                       char *act)
1455 {
1456         process_fmt(act, pci, t, -1ULL, 0, NULL);
1457 }
1458
1459 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
1460 {
1461         unsigned char *buf = (unsigned char *) t + sizeof(*t);
1462
1463         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
1464 }
1465
1466 static void dump_trace_pc(struct blk_io_trace *t, struct per_dev_info *pdi,
1467                           struct per_cpu_info *pci)
1468 {
1469         int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1470         int act = t->action & 0xffff;
1471
1472         switch (act) {
1473                 case __BLK_TA_QUEUE:
1474                         log_generic(pci, t, "Q");
1475                         account_pc_queue(t, pci, w);
1476                         break;
1477                 case __BLK_TA_GETRQ:
1478                         log_generic(pci, t, "G");
1479                         break;
1480                 case __BLK_TA_SLEEPRQ:
1481                         log_generic(pci, t, "S");
1482                         break;
1483                 case __BLK_TA_REQUEUE:
1484                         /*
1485                          * can happen if we miss traces, don't let it go
1486                          * below zero
1487                          */
1488                         if (pdi->cur_depth[w])
1489                                 pdi->cur_depth[w]--;
1490                         account_pc_requeue(t, pci, w);
1491                         log_generic(pci, t, "R");
1492                         break;
1493                 case __BLK_TA_ISSUE:
1494                         account_pc_issue(t, pci, w);
1495                         pdi->cur_depth[w]++;
1496                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1497                                 pdi->max_depth[w] = pdi->cur_depth[w];
1498                         log_pc(pci, t, "D");
1499                         break;
1500                 case __BLK_TA_COMPLETE:
1501                         if (pdi->cur_depth[w])
1502                                 pdi->cur_depth[w]--;
1503                         log_pc(pci, t, "C");
1504                         account_pc_c(t, pci, w);
1505                         break;
1506                 case __BLK_TA_INSERT:
1507                         log_pc(pci, t, "I");
1508                         break;
1509                 default:
1510                         fprintf(stderr, "Bad pc action %x\n", act);
1511                         break;
1512         }
1513 }
1514
1515 static void dump_trace_fs(struct blk_io_trace *t, struct per_dev_info *pdi,
1516                           struct per_cpu_info *pci)
1517 {
1518         int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
1519         int act = t->action & 0xffff;
1520
1521         switch (act) {
1522                 case __BLK_TA_QUEUE:
1523                         log_track_queue(pdi, t);
1524                         account_queue(t, pci, w);
1525                         log_queue(pci, t, "Q");
1526                         break;
1527                 case __BLK_TA_INSERT:
1528                         log_insert(pdi, pci, t, "I");
1529                         break;
1530                 case __BLK_TA_BACKMERGE:
1531                         account_m(t, pci, w);
1532                         log_merge(pdi, pci, t, "M");
1533                         break;
1534                 case __BLK_TA_FRONTMERGE:
1535                         account_m(t, pci, w);
1536                         log_merge(pdi, pci, t, "F");
1537                         break;
1538                 case __BLK_TA_GETRQ:
1539                         log_track_getrq(pdi, t);
1540                         log_generic(pci, t, "G");
1541                         break;
1542                 case __BLK_TA_SLEEPRQ:
1543                         log_generic(pci, t, "S");
1544                         break;
1545                 case __BLK_TA_REQUEUE:
1546                         /*
1547                          * can happen if we miss traces, don't let it go
1548                          * below zero
1549                          */
1550                         if (pdi->cur_depth[w])
1551                                 pdi->cur_depth[w]--;
1552                         account_requeue(t, pci, w);
1553                         log_queue(pci, t, "R");
1554                         break;
1555                 case __BLK_TA_ISSUE:
1556                         account_issue(t, pci, w);
1557                         pdi->cur_depth[w]++;
1558                         if (pdi->cur_depth[w] > pdi->max_depth[w])
1559                                 pdi->max_depth[w] = pdi->cur_depth[w];
1560                         log_issue(pdi, pci, t, "D");
1561                         break;
1562                 case __BLK_TA_COMPLETE:
1563                         if (pdi->cur_depth[w])
1564                                 pdi->cur_depth[w]--;
1565                         account_c(t, pci, w, t->bytes);
1566                         log_complete(pdi, pci, t, "C");
1567                         break;
1568                 case __BLK_TA_PLUG:
1569                         log_action(pci, t, "P");
1570                         break;
1571                 case __BLK_TA_UNPLUG_IO:
1572                         account_unplug(t, pci, 0);
1573                         log_unplug(pci, t, "U");
1574                         break;
1575                 case __BLK_TA_UNPLUG_TIMER:
1576                         account_unplug(t, pci, 1);
1577                         log_unplug(pci, t, "UT");
1578                         break;
1579                 case __BLK_TA_SPLIT:
1580                         log_split(pci, t, "X");
1581                         break;
1582                 case __BLK_TA_BOUNCE:
1583                         log_generic(pci, t, "B");
1584                         break;
1585                 case __BLK_TA_REMAP:
1586                         log_generic(pci, t, "A");
1587                         break;
1588                 case __BLK_TA_DRV_DATA:
1589                         have_drv_data = 1;
1590                         /* dump to binary file only */
1591                         break;
1592                 default:
1593                         fprintf(stderr, "Bad fs action %x\n", t->action);
1594                         break;
1595         }
1596 }
1597
1598 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1599                        struct per_dev_info *pdi)
1600 {
1601         if (text_output) {
1602                 if (t->action == BLK_TN_MESSAGE)
1603                         handle_notify(t);
1604                 else if (t->action & BLK_TC_ACT(BLK_TC_PC))
1605                         dump_trace_pc(t, pdi, pci);
1606                 else
1607                         dump_trace_fs(t, pdi, pci);
1608         }
1609
1610         if (!pdi->events)
1611                 pdi->first_reported_time = t->time;
1612
1613         pdi->events++;
1614
1615         output_binary(t, sizeof(*t) + t->pdu_len);
1616 }
1617
1618 /*
1619  * print in a proper way, not too small and not too big. if more than
1620  * 1000,000K, turn into M and so on
1621  */
1622 static char *size_cnv(char *dst, unsigned long long num, int in_kb)
1623 {
1624         char suff[] = { '\0', 'K', 'M', 'G', 'P' };
1625         unsigned int i = 0;
1626
1627         if (in_kb)
1628                 i++;
1629
1630         while (num > 1000 * 1000ULL && (i < sizeof(suff) - 1)) {
1631                 i++;
1632                 num /= 1000;
1633         }
1634
1635         sprintf(dst, "%'8Lu%c", num, suff[i]);
1636         return dst;
1637 }
1638
1639 static void dump_io_stats(struct per_dev_info *pdi, struct io_stats *ios,
1640                           char *msg)
1641 {
1642         static char x[256], y[256];
1643
1644         fprintf(ofp, "%s\n", msg);
1645
1646         fprintf(ofp, " Reads Queued:    %s, %siB\t", size_cnv(x, ios->qreads, 0), size_cnv(y, ios->qread_kb, 1));
1647         fprintf(ofp, " Writes Queued:    %s, %siB\n", size_cnv(x, ios->qwrites, 0), size_cnv(y, ios->qwrite_kb, 1));
1648         fprintf(ofp, " Read Dispatches: %s, %siB\t", size_cnv(x, ios->ireads, 0), size_cnv(y, ios->iread_kb, 1));
1649         fprintf(ofp, " Write Dispatches: %s, %siB\n", size_cnv(x, ios->iwrites, 0), size_cnv(y, ios->iwrite_kb, 1));
1650         fprintf(ofp, " Reads Requeued:  %s\t\t", size_cnv(x, ios->rrqueue, 0));
1651         fprintf(ofp, " Writes Requeued:  %s\n", size_cnv(x, ios->wrqueue, 0));
1652         fprintf(ofp, " Reads Completed: %s, %siB\t", size_cnv(x, ios->creads, 0), size_cnv(y, ios->cread_kb, 1));
1653         fprintf(ofp, " Writes Completed: %s, %siB\n", size_cnv(x, ios->cwrites, 0), size_cnv(y, ios->cwrite_kb, 1));
1654         fprintf(ofp, " Read Merges:     %s, %siB\t", size_cnv(x, ios->mreads, 0), size_cnv(y, ios->mread_kb, 1));
1655         fprintf(ofp, " Write Merges:     %s, %siB\n", size_cnv(x, ios->mwrites, 0), size_cnv(y, ios->mwrite_kb, 1));
1656         if (pdi) {
1657                 fprintf(ofp, " Read depth:      %'8u%8c\t", pdi->max_depth[0], ' ');
1658                 fprintf(ofp, " Write depth:      %'8u\n", pdi->max_depth[1]);
1659         }
1660         if (ios->qreads_pc || ios->qwrites_pc || ios->ireads_pc || ios->iwrites_pc ||
1661             ios->rrqueue_pc || ios->wrqueue_pc || ios->creads_pc || ios->cwrites_pc) {
1662                 fprintf(ofp, " PC Reads Queued: %s, %siB\t", size_cnv(x, ios->qreads_pc, 0), size_cnv(y, ios->qread_kb_pc, 1));
1663                 fprintf(ofp, " PC Writes Queued: %s, %siB\n", size_cnv(x, ios->qwrites_pc, 0), size_cnv(y, ios->qwrite_kb_pc, 1));
1664                 fprintf(ofp, " PC Read Disp.:   %s, %siB\t", size_cnv(x, ios->ireads_pc, 0), size_cnv(y, ios->iread_kb_pc, 1));
1665                 fprintf(ofp, " PC Write Disp.:   %s, %siB\n", size_cnv(x, ios->iwrites_pc, 0), size_cnv(y, ios->iwrite_kb_pc, 1));
1666                 fprintf(ofp, " PC Reads Req.:   %s\t\t", size_cnv(x, ios->rrqueue_pc, 0));
1667                 fprintf(ofp, " PC Writes Req.:   %s\n", size_cnv(x, ios->wrqueue_pc, 0));
1668                 fprintf(ofp, " PC Reads Compl.: %s\t\t", size_cnv(x, ios->creads_pc, 0));
1669                 fprintf(ofp, " PC Writes Compl.: %s\n", size_cnv(x, ios->cwrites, 0));
1670         }
1671         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1672         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1673 }
1674
1675 static void dump_wait_stats(struct per_process_info *ppi)
1676 {
1677         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1678         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1679         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1680         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1681         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1682         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1683
1684         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1685         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1686         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1687         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1688         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1689         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1690 }
1691
1692 static int ppi_name_compare(const void *p1, const void *p2)
1693 {
1694         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1695         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1696         int res;
1697
1698         res = strverscmp(ppi1->ppm->comm, ppi2->ppm->comm);
1699         if (!res)
1700                 res = ppi1->ppm->pid > ppi2->ppm->pid;
1701
1702         return res;
1703 }
1704
1705 static void sort_process_list(void)
1706 {
1707         struct per_process_info **ppis;
1708         struct per_process_info *ppi;
1709         int i = 0;
1710
1711         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1712
1713         ppi = ppi_list;
1714         while (ppi) {
1715                 ppis[i++] = ppi;
1716                 ppi = ppi->list_next;
1717         }
1718
1719         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1720
1721         i = ppi_list_entries - 1;
1722         ppi_list = NULL;
1723         while (i >= 0) {
1724                 ppi = ppis[i];
1725
1726                 ppi->list_next = ppi_list;
1727                 ppi_list = ppi;
1728                 i--;
1729         }
1730
1731         free(ppis);
1732 }
1733
1734 static void show_process_stats(void)
1735 {
1736         struct per_process_info *ppi;
1737
1738         sort_process_list();
1739
1740         ppi = ppi_list;
1741         while (ppi) {
1742                 struct process_pid_map *ppm = ppi->ppm;
1743                 char name[64];
1744
1745                 if (ppi->more_than_one)
1746                         sprintf(name, "%s (%u, ...)", ppm->comm, ppm->pid);
1747                 else
1748                         sprintf(name, "%s (%u)", ppm->comm, ppm->pid);
1749
1750                 dump_io_stats(NULL, &ppi->io_stats, name);
1751                 dump_wait_stats(ppi);
1752                 ppi = ppi->list_next;
1753         }
1754
1755         fprintf(ofp, "\n");
1756 }
1757
1758 static void show_device_and_cpu_stats(void)
1759 {
1760         struct per_dev_info *pdi;
1761         struct per_cpu_info *pci;
1762         struct io_stats total, *ios;
1763         unsigned long long rrate, wrate, msec;
1764         int i, j, pci_events;
1765         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1766         char name[32];
1767         double ratio;
1768
1769         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1770
1771                 memset(&total, 0, sizeof(total));
1772                 pci_events = 0;
1773
1774                 if (i > 0)
1775                         fprintf(ofp, "\n");
1776
1777                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1778                         if (!pci->nelems)
1779                                 continue;
1780
1781                         ios = &pci->io_stats;
1782                         total.qreads += ios->qreads;
1783                         total.qwrites += ios->qwrites;
1784                         total.creads += ios->creads;
1785                         total.cwrites += ios->cwrites;
1786                         total.mreads += ios->mreads;
1787                         total.mwrites += ios->mwrites;
1788                         total.ireads += ios->ireads;
1789                         total.iwrites += ios->iwrites;
1790                         total.rrqueue += ios->rrqueue;
1791                         total.wrqueue += ios->wrqueue;
1792                         total.qread_kb += ios->qread_kb;
1793                         total.qwrite_kb += ios->qwrite_kb;
1794                         total.cread_kb += ios->cread_kb;
1795                         total.cwrite_kb += ios->cwrite_kb;
1796                         total.iread_kb += ios->iread_kb;
1797                         total.iwrite_kb += ios->iwrite_kb;
1798                         total.mread_kb += ios->mread_kb;
1799                         total.mwrite_kb += ios->mwrite_kb;
1800
1801                         total.qreads_pc += ios->qreads_pc;
1802                         total.qwrites_pc += ios->qwrites_pc;
1803                         total.creads_pc += ios->creads_pc;
1804                         total.cwrites_pc += ios->cwrites_pc;
1805                         total.ireads_pc += ios->ireads_pc;
1806                         total.iwrites_pc += ios->iwrites_pc;
1807                         total.rrqueue_pc += ios->rrqueue_pc;
1808                         total.wrqueue_pc += ios->wrqueue_pc;
1809                         total.qread_kb_pc += ios->qread_kb_pc;
1810                         total.qwrite_kb_pc += ios->qwrite_kb_pc;
1811                         total.iread_kb_pc += ios->iread_kb_pc;
1812                         total.iwrite_kb_pc += ios->iwrite_kb_pc;
1813
1814                         total.timer_unplugs += ios->timer_unplugs;
1815                         total.io_unplugs += ios->io_unplugs;
1816
1817                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1818                                  j, get_dev_name(pdi, name, sizeof(name)));
1819                         dump_io_stats(pdi, ios, line);
1820                         pci_events++;
1821                 }
1822
1823                 if (pci_events > 1) {
1824                         fprintf(ofp, "\n");
1825                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1826                                  get_dev_name(pdi, name, sizeof(name)));
1827                         dump_io_stats(NULL, &total, line);
1828                 }
1829
1830                 wrate = rrate = 0;
1831                 msec = (pdi->last_reported_time - pdi->first_reported_time) / 1000000;
1832                 if (msec) {
1833                         rrate = 1000 * total.cread_kb / msec;
1834                         wrate = 1000 * total.cwrite_kb / msec;
1835                 }
1836
1837                 fprintf(ofp, "\nThroughput (R/W): %'LuKiB/s / %'LuKiB/s\n",
1838                         rrate, wrate);
1839                 fprintf(ofp, "Events (%s): %'Lu entries\n",
1840                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1841
1842                 collect_pdi_skips(pdi);
1843                 if (!pdi->skips && !pdi->events)
1844                         ratio = 0.0;
1845                 else
1846                         ratio = 100.0 * ((double)pdi->seq_skips /
1847                                         (double)(pdi->events + pdi->seq_skips));
1848                 fprintf(ofp, "Skips: %'lu forward (%'llu - %5.1lf%%)\n",
1849                         pdi->skips, pdi->seq_skips, ratio);
1850         }
1851 }
1852
1853 static void find_genesis(void)
1854 {
1855         struct trace *t = trace_list;
1856
1857         genesis_time = -1ULL;
1858         while (t != NULL) {
1859                 if (t->bit->time < genesis_time)
1860                         genesis_time = t->bit->time;
1861
1862                 t = t->next;
1863         }
1864
1865         /* The time stamp record will usually be the first
1866          * record in the trace, but not always.
1867          */
1868         if (start_timestamp
1869          && start_timestamp != genesis_time) {
1870                 long delta = genesis_time - start_timestamp;
1871
1872                 abs_start_time.tv_sec  += SECONDS(delta);
1873                 abs_start_time.tv_nsec += NANO_SECONDS(delta);
1874                 if (abs_start_time.tv_nsec < 0) {
1875                         abs_start_time.tv_nsec += 1000000000;
1876                         abs_start_time.tv_sec -= 1;
1877                 } else
1878                 if (abs_start_time.tv_nsec > 1000000000) {
1879                         abs_start_time.tv_nsec -= 1000000000;
1880                         abs_start_time.tv_sec += 1;
1881                 }
1882         }
1883 }
1884
1885 static inline int check_stopwatch(struct blk_io_trace *bit)
1886 {
1887         if (bit->time < stopwatch_end &&
1888             bit->time >= stopwatch_start)
1889                 return 0;
1890
1891         return 1;
1892 }
1893
1894 /*
1895  * return youngest entry read
1896  */
1897 static int sort_entries(unsigned long long *youngest)
1898 {
1899         struct per_dev_info *pdi = NULL;
1900         struct per_cpu_info *pci = NULL;
1901         struct trace *t;
1902
1903         if (!genesis_time)
1904                 find_genesis();
1905
1906         *youngest = 0;
1907         while ((t = trace_list) != NULL) {
1908                 struct blk_io_trace *bit = t->bit;
1909
1910                 trace_list = t->next;
1911
1912                 bit->time -= genesis_time;
1913
1914                 if (bit->time < *youngest || !*youngest)
1915                         *youngest = bit->time;
1916
1917                 if (!pdi || pdi->dev != bit->device) {
1918                         pdi = get_dev_info(bit->device);
1919                         pci = NULL;
1920                 }
1921
1922                 if (!pci || pci->cpu != bit->cpu)
1923                         pci = get_cpu_info(pdi, bit->cpu);
1924
1925                 if (bit->sequence < pci->smallest_seq_read)
1926                         pci->smallest_seq_read = bit->sequence;
1927
1928                 if (check_stopwatch(bit)) {
1929                         bit_free(bit);
1930                         t_free(t);
1931                         continue;
1932                 }
1933
1934                 if (trace_rb_insert_sort(t))
1935                         return -1;
1936         }
1937
1938         return 0;
1939 }
1940
1941 /*
1942  * to continue, we must have traces from all online cpus in the tree
1943  */
1944 static int check_cpu_map(struct per_dev_info *pdi)
1945 {
1946         unsigned long *cpu_map;
1947         struct rb_node *n;
1948         struct trace *__t;
1949         unsigned int i;
1950         int ret, cpu;
1951
1952         /*
1953          * create a map of the cpus we have traces for
1954          */
1955         cpu_map = malloc(pdi->cpu_map_max / sizeof(long));
1956         n = rb_first(&rb_sort_root);
1957         while (n) {
1958                 __t = rb_entry(n, struct trace, rb_node);
1959                 cpu = __t->bit->cpu;
1960
1961                 cpu_map[CPU_IDX(cpu)] |= (1UL << CPU_BIT(cpu));
1962                 n = rb_next(n);
1963         }
1964
1965         /*
1966          * we can't continue if pdi->cpu_map has entries set that we don't
1967          * have in the sort rbtree. the opposite is not a problem, though
1968          */
1969         ret = 0;
1970         for (i = 0; i < pdi->cpu_map_max / CPUS_PER_LONG; i++) {
1971                 if (pdi->cpu_map[i] & ~(cpu_map[i])) {
1972                         ret = 1;
1973                         break;
1974                 }
1975         }
1976
1977         free(cpu_map);
1978         return ret;
1979 }
1980
1981 static int check_sequence(struct per_dev_info *pdi, struct trace *t, int force)
1982 {
1983         struct blk_io_trace *bit = t->bit;
1984         unsigned long expected_sequence;
1985         struct per_cpu_info *pci;
1986         struct trace *__t;
1987
1988         pci = get_cpu_info(pdi, bit->cpu);
1989         expected_sequence = pci->last_sequence + 1;
1990
1991         if (!expected_sequence) {
1992                 /*
1993                  * 1 should be the first entry, just allow it
1994                  */
1995                 if (bit->sequence == 1)
1996                         return 0;
1997                 if (bit->sequence == pci->smallest_seq_read)
1998                         return 0;
1999
2000                 return check_cpu_map(pdi);
2001         }
2002
2003         if (bit->sequence == expected_sequence)
2004                 return 0;
2005
2006         /*
2007          * we may not have seen that sequence yet. if we are not doing
2008          * the final run, break and wait for more entries.
2009          */
2010         if (expected_sequence < pci->smallest_seq_read) {
2011                 __t = trace_rb_find_last(pdi, pci, expected_sequence);
2012                 if (!__t)
2013                         goto skip;
2014
2015                 __put_trace_last(pdi, __t);
2016                 return 0;
2017         } else if (!force) {
2018                 return 1;
2019         } else {
2020 skip:
2021                 if (check_current_skips(pci, bit->sequence))
2022                         return 0;
2023
2024                 if (expected_sequence < bit->sequence)
2025                         insert_skip(pci, expected_sequence, bit->sequence - 1);
2026                 return 0;
2027         }
2028 }
2029
2030 static void show_entries_rb(int force)
2031 {
2032         struct per_dev_info *pdi = NULL;
2033         struct per_cpu_info *pci = NULL;
2034         struct blk_io_trace *bit;
2035         struct rb_node *n;
2036         struct trace *t;
2037
2038         while ((n = rb_first(&rb_sort_root)) != NULL) {
2039                 if (is_done() && !force && !pipeline)
2040                         break;
2041
2042                 t = rb_entry(n, struct trace, rb_node);
2043                 bit = t->bit;
2044
2045                 if (read_sequence - t->read_sequence < 1 && !force)
2046                         break;
2047
2048                 if (!pdi || pdi->dev != bit->device) {
2049                         pdi = get_dev_info(bit->device);
2050                         pci = NULL;
2051                 }
2052
2053                 if (!pdi) {
2054                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
2055                                 MAJOR(bit->device), MINOR(bit->device));
2056                         break;
2057                 }
2058
2059                 if (check_sequence(pdi, t, force))
2060                         break;
2061
2062                 if (!force && bit->time > last_allowed_time)
2063                         break;
2064
2065                 check_time(pdi, bit);
2066
2067                 if (!pci || pci->cpu != bit->cpu)
2068                         pci = get_cpu_info(pdi, bit->cpu);
2069
2070                 pci->last_sequence = bit->sequence;
2071
2072                 pci->nelems++;
2073
2074                 if (bit->action & (act_mask << BLK_TC_SHIFT))
2075                         dump_trace(bit, pci, pdi);
2076
2077                 put_trace(pdi, t);
2078         }
2079 }
2080
2081 static int read_data(int fd, void *buffer, int bytes, int block, int *fdblock)
2082 {
2083         int ret, bytes_left, fl;
2084         void *p;
2085
2086         if (block != *fdblock) {
2087                 fl = fcntl(fd, F_GETFL);
2088
2089                 if (!block) {
2090                         *fdblock = 0;
2091                         fcntl(fd, F_SETFL, fl | O_NONBLOCK);
2092                 } else {
2093                         *fdblock = 1;
2094                         fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
2095                 }
2096         }
2097
2098         bytes_left = bytes;
2099         p = buffer;
2100         while (bytes_left > 0) {
2101                 ret = read(fd, p, bytes_left);
2102                 if (!ret)
2103                         return 1;
2104                 else if (ret < 0) {
2105                         if (errno != EAGAIN) {
2106                                 perror("read");
2107                                 return -1;
2108                         }
2109
2110                         /*
2111                          * never do partial reads. we can return if we
2112                          * didn't read anything and we should not block,
2113                          * otherwise wait for data
2114                          */
2115                         if ((bytes_left == bytes) && !block)
2116                                 return 1;
2117
2118                         usleep(10);
2119                         continue;
2120                 } else {
2121                         p += ret;
2122                         bytes_left -= ret;
2123                 }
2124         }
2125
2126         return 0;
2127 }
2128
2129 static inline __u16 get_pdulen(struct blk_io_trace *bit)
2130 {
2131         if (data_is_native)
2132                 return bit->pdu_len;
2133
2134         return __bswap_16(bit->pdu_len);
2135 }
2136
2137 static inline __u32 get_magic(struct blk_io_trace *bit)
2138 {
2139         if (data_is_native)
2140                 return bit->magic;
2141
2142         return __bswap_32(bit->magic);
2143 }
2144
2145 static int read_events(int fd, int always_block, int *fdblock)
2146 {
2147         struct per_dev_info *pdi = NULL;
2148         unsigned int events = 0;
2149
2150         while (!is_done() && events < rb_batch) {
2151                 struct blk_io_trace *bit;
2152                 struct trace *t;
2153                 int pdu_len, should_block, ret;
2154                 __u32 magic;
2155
2156                 bit = bit_alloc();
2157
2158                 should_block = !events || always_block;
2159
2160                 ret = read_data(fd, bit, sizeof(*bit), should_block, fdblock);
2161                 if (ret) {
2162                         bit_free(bit);
2163                         if (!events && ret < 0)
2164                                 events = ret;
2165                         break;
2166                 }
2167
2168                 /*
2169                  * look at first trace to check whether we need to convert
2170                  * data in the future
2171                  */
2172                 if (data_is_native == -1 && check_data_endianness(bit->magic))
2173                         break;
2174
2175                 magic = get_magic(bit);
2176                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2177                         fprintf(stderr, "Bad magic %x\n", magic);
2178                         break;
2179                 }
2180
2181                 pdu_len = get_pdulen(bit);
2182                 if (pdu_len) {
2183                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
2184
2185                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1, fdblock)) {
2186                                 bit_free(ptr);
2187                                 break;
2188                         }
2189
2190                         bit = ptr;
2191                 }
2192
2193                 trace_to_cpu(bit);
2194
2195                 if (verify_trace(bit)) {
2196                         bit_free(bit);
2197                         continue;
2198                 }
2199
2200                 /*
2201                  * not a real trace, so grab and handle it here
2202                  */
2203                 if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY) && bit->action != BLK_TN_MESSAGE) {
2204                         handle_notify(bit);
2205                         output_binary(bit, sizeof(*bit) + bit->pdu_len);
2206                         continue;
2207                 }
2208
2209                 t = t_alloc();
2210                 memset(t, 0, sizeof(*t));
2211                 t->bit = bit;
2212                 t->read_sequence = read_sequence;
2213
2214                 t->next = trace_list;
2215                 trace_list = t;
2216
2217                 if (!pdi || pdi->dev != bit->device)
2218                         pdi = get_dev_info(bit->device);
2219
2220                 if (bit->time > pdi->last_read_time)
2221                         pdi->last_read_time = bit->time;
2222
2223                 events++;
2224         }
2225
2226         return events;
2227 }
2228
2229 /*
2230  * Managing input streams
2231  */
2232
2233 struct ms_stream {
2234         struct ms_stream *next;
2235         struct trace *first, *last;
2236         struct per_dev_info *pdi;
2237         unsigned int cpu;
2238 };
2239
2240 #define MS_HASH(d, c) ((MAJOR(d) & 0xff) ^ (MINOR(d) & 0xff) ^ (cpu & 0xff))
2241
2242 struct ms_stream *ms_head;
2243 struct ms_stream *ms_hash[256];
2244
2245 static void ms_sort(struct ms_stream *msp);
2246 static int ms_prime(struct ms_stream *msp);
2247
2248 static inline struct trace *ms_peek(struct ms_stream *msp)
2249 {
2250         return (msp == NULL) ? NULL : msp->first;
2251 }
2252
2253 static inline __u64 ms_peek_time(struct ms_stream *msp)
2254 {
2255         return ms_peek(msp)->bit->time;
2256 }
2257
2258 static inline void ms_resort(struct ms_stream *msp)
2259 {
2260         if (msp->next && ms_peek_time(msp) > ms_peek_time(msp->next)) {
2261                 ms_head = msp->next;
2262                 msp->next = NULL;
2263                 ms_sort(msp);
2264         }
2265 }
2266
2267 static inline void ms_deq(struct ms_stream *msp)
2268 {
2269         msp->first = msp->first->next;
2270         if (!msp->first) {
2271                 msp->last = NULL;
2272                 if (!ms_prime(msp)) {
2273                         ms_head = msp->next;
2274                         msp->next = NULL;
2275                         return;
2276                 }
2277         }
2278
2279         ms_resort(msp);
2280 }
2281
2282 static void ms_sort(struct ms_stream *msp)
2283 {
2284         __u64 msp_t = ms_peek_time(msp);
2285         struct ms_stream *this_msp = ms_head;
2286
2287         if (this_msp == NULL)
2288                 ms_head = msp;
2289         else if (msp_t < ms_peek_time(this_msp)) {
2290                 msp->next = this_msp;
2291                 ms_head = msp;
2292         }
2293         else {
2294                 while (this_msp->next && ms_peek_time(this_msp->next) < msp_t)
2295                         this_msp = this_msp->next;
2296
2297                 msp->next = this_msp->next;
2298                 this_msp->next = msp;
2299         }
2300 }
2301
2302 static int ms_prime(struct ms_stream *msp)
2303 {
2304         __u32 magic;
2305         unsigned int i;
2306         struct trace *t;
2307         struct per_dev_info *pdi = msp->pdi;
2308         struct per_cpu_info *pci = get_cpu_info(pdi, msp->cpu);
2309         struct blk_io_trace *bit = NULL;
2310         int ret, pdu_len, ndone = 0;
2311
2312         for (i = 0; !is_done() && pci->fd >= 0 && i < rb_batch; i++) {
2313                 bit = bit_alloc();
2314                 ret = read_data(pci->fd, bit, sizeof(*bit), 1, &pci->fdblock);
2315                 if (ret)
2316                         goto err;
2317
2318                 if (data_is_native == -1 && check_data_endianness(bit->magic))
2319                         goto err;
2320
2321                 magic = get_magic(bit);
2322                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
2323                         fprintf(stderr, "Bad magic %x\n", magic);
2324                         goto err;
2325
2326                 }
2327
2328                 pdu_len = get_pdulen(bit);
2329                 if (pdu_len) {
2330                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
2331                         ret = read_data(pci->fd, ptr + sizeof(*bit), pdu_len,
2332                                                              1, &pci->fdblock);
2333                         if (ret) {
2334                                 free(ptr);
2335                                 bit = NULL;
2336                                 goto err;
2337                         }
2338
2339                         bit = ptr;
2340                 }
2341
2342                 trace_to_cpu(bit);
2343                 if (verify_trace(bit))
2344                         goto err;
2345
2346                 if (bit->action & BLK_TC_ACT(BLK_TC_NOTIFY) && bit->action != BLK_TN_MESSAGE) {
2347                         handle_notify(bit);
2348                         output_binary(bit, sizeof(*bit) + bit->pdu_len);
2349                         bit_free(bit);
2350
2351                         i -= 1;
2352                         continue;
2353                 }
2354
2355                 if (bit->time > pdi->last_read_time)
2356                         pdi->last_read_time = bit->time;
2357
2358                 t = t_alloc();
2359                 memset(t, 0, sizeof(*t));
2360                 t->bit = bit;
2361
2362                 if (msp->first == NULL)
2363                         msp->first = msp->last = t;
2364                 else {
2365                         msp->last->next = t;
2366                         msp->last = t;
2367                 }
2368
2369                 ndone++;
2370         }
2371
2372         return ndone;
2373
2374 err:
2375         if (bit) bit_free(bit);
2376
2377         cpu_mark_offline(pdi, pci->cpu);
2378         close(pci->fd);
2379         pci->fd = -1;
2380
2381         return ndone;
2382 }
2383
2384 static struct ms_stream *ms_alloc(struct per_dev_info *pdi, int cpu)
2385 {
2386         struct ms_stream *msp = malloc(sizeof(*msp));
2387
2388         msp->next = NULL;
2389         msp->first = msp->last = NULL;
2390         msp->pdi = pdi;
2391         msp->cpu = cpu;
2392
2393         if (ms_prime(msp))
2394                 ms_sort(msp);
2395
2396         return msp;
2397 }
2398
2399 static int setup_file(struct per_dev_info *pdi, int cpu)
2400 {
2401         int len = 0;
2402         struct stat st;
2403         char *p, *dname;
2404         struct per_cpu_info *pci = get_cpu_info(pdi, cpu);
2405
2406         pci->cpu = cpu;
2407         pci->fdblock = -1;
2408
2409         p = strdup(pdi->name);
2410         dname = dirname(p);
2411         if (strcmp(dname, ".")) {
2412                 input_dir = dname;
2413                 p = strdup(pdi->name);
2414                 strcpy(pdi->name, basename(p));
2415         }
2416         free(p);
2417
2418         if (input_dir)
2419                 len = sprintf(pci->fname, "%s/", input_dir);
2420
2421         snprintf(pci->fname + len, sizeof(pci->fname)-1-len,
2422                  "%s.blktrace.%d", pdi->name, pci->cpu);
2423         if (stat(pci->fname, &st) < 0)
2424                 return 0;
2425         if (!st.st_size)
2426                 return 1;
2427
2428         pci->fd = open(pci->fname, O_RDONLY);
2429         if (pci->fd < 0) {
2430                 perror(pci->fname);
2431                 return 0;
2432         }
2433
2434         printf("Input file %s added\n", pci->fname);
2435         cpu_mark_online(pdi, pci->cpu);
2436
2437         pdi->nfiles++;
2438         ms_alloc(pdi, pci->cpu);
2439
2440         return 1;
2441 }
2442
2443 static int handle(struct ms_stream *msp)
2444 {
2445         struct trace *t;
2446         struct per_dev_info *pdi;
2447         struct per_cpu_info *pci;
2448         struct blk_io_trace *bit;
2449
2450         t = ms_peek(msp);
2451
2452         bit = t->bit;
2453         pdi = msp->pdi;
2454         pci = get_cpu_info(pdi, msp->cpu);
2455         pci->nelems++;
2456         bit->time -= genesis_time;
2457
2458         if (t->bit->time > stopwatch_end)
2459                 return 0;
2460
2461         pdi->last_reported_time = bit->time;
2462         if ((bit->action & (act_mask << BLK_TC_SHIFT))&&
2463             t->bit->time >= stopwatch_start)
2464                 dump_trace(bit, pci, pdi);
2465
2466         ms_deq(msp);
2467
2468         if (text_output)
2469                 trace_rb_insert_last(pdi, t);
2470         else {
2471                 bit_free(t->bit);
2472                 t_free(t);
2473         }
2474
2475         return 1;
2476 }
2477
2478 /*
2479  * Check if we need to sanitize the name. We allow 'foo', or if foo.blktrace.X
2480  * is given, then strip back down to 'foo' to avoid missing files.
2481  */
2482 static int name_fixup(char *name)
2483 {
2484         char *b;
2485
2486         if (!name)
2487                 return 1;
2488
2489         b = strstr(name, ".blktrace.");
2490         if (b)
2491                 *b = '\0';
2492
2493         return 0;
2494 }
2495
2496 static int do_file(void)
2497 {
2498         int i, cpu, ret;
2499         struct per_dev_info *pdi;
2500
2501         /*
2502          * first prepare all files for reading
2503          */
2504         for (i = 0; i < ndevices; i++) {
2505                 pdi = &devices[i];
2506                 ret = name_fixup(pdi->name);
2507                 if (ret)
2508                         return ret;
2509
2510                 for (cpu = 0; setup_file(pdi, cpu); cpu++)
2511                         ;
2512         }
2513
2514         /*
2515          * Get the initial time stamp
2516          */
2517         if (ms_head)
2518                 genesis_time = ms_peek_time(ms_head);
2519
2520         /*
2521          * Keep processing traces while any are left
2522          */
2523         while (!is_done() && ms_head && handle(ms_head))
2524                 ;
2525
2526         return 0;
2527 }
2528
2529 static void do_pipe(int fd)
2530 {
2531         unsigned long long youngest;
2532         int events, fdblock;
2533
2534         last_allowed_time = -1ULL;
2535         fdblock = -1;
2536         while ((events = read_events(fd, 0, &fdblock)) > 0) {
2537                 read_sequence++;
2538         
2539 #if 0
2540                 smallest_seq_read = -1U;
2541 #endif
2542
2543                 if (sort_entries(&youngest))
2544                         break;
2545
2546                 if (youngest > stopwatch_end)
2547                         break;
2548
2549                 show_entries_rb(0);
2550         }
2551
2552         if (rb_sort_entries)
2553                 show_entries_rb(1);
2554 }
2555
2556 static int do_fifo(void)
2557 {
2558         int fd;
2559
2560         if (!strcmp(pipename, "-"))
2561                 fd = dup(STDIN_FILENO);
2562         else
2563                 fd = open(pipename, O_RDONLY);
2564
2565         if (fd == -1) {
2566                 perror("dup stdin");
2567                 return -1;
2568         }
2569
2570         do_pipe(fd);
2571         close(fd);
2572         return 0;
2573 }
2574
2575 static void show_stats(void)
2576 {
2577         if (!ofp)
2578                 return;
2579         if (stats_printed)
2580                 return;
2581
2582         stats_printed = 1;
2583
2584         if (per_process_stats)
2585                 show_process_stats();
2586
2587         if (per_device_and_cpu_stats)
2588                 show_device_and_cpu_stats();
2589
2590         fflush(ofp);
2591 }
2592
2593 static void handle_sigint(__attribute__((__unused__)) int sig)
2594 {
2595         done = 1;
2596 }
2597
2598 /*
2599  * Extract start and duration times from a string, allowing
2600  * us to specify a time interval of interest within a trace.
2601  * Format: "duration" (start is zero) or "start:duration".
2602  */
2603 static int find_stopwatch_interval(char *string)
2604 {
2605         double value;
2606         char *sp;
2607
2608         value = strtod(string, &sp);
2609         if (sp == string) {
2610                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
2611                 return 1;
2612         }
2613         if (*sp == ':') {
2614                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
2615                 string = sp + 1;
2616                 value = strtod(string, &sp);
2617                 if (sp == string || *sp != '\0') {
2618                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
2619                                 string);
2620                         return 1;
2621                 }
2622         } else if (*sp != '\0') {
2623                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
2624                 return 1;
2625         }
2626         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
2627         if (stopwatch_end <= stopwatch_start) {
2628                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
2629                         stopwatch_start, stopwatch_end);
2630                 return 1;
2631         }
2632
2633         return 0;
2634 }
2635
2636 static int is_pipe(const char *str)
2637 {
2638         struct stat st;
2639
2640         if (!strcmp(str, "-"))
2641                 return 1;
2642         if (!stat(str, &st) && S_ISFIFO(st.st_mode))
2643                 return 1;
2644
2645         return 0;
2646 }
2647
2648 #define S_OPTS  "a:A:b:D:d:f:F:hi:o:Oqstw:vV"
2649 static char usage_str[] =    "\n\n" \
2650         "-i <file>           | --input=<file>\n" \
2651         "[ -a <action field> | --act-mask=<action field> ]\n" \
2652         "[ -A <action mask>  | --set-mask=<action mask> ]\n" \
2653         "[ -b <traces>       | --batch=<traces> ]\n" \
2654         "[ -d <file>         | --dump-binary=<file> ]\n" \
2655         "[ -D <dir>          | --input-directory=<dir> ]\n" \
2656         "[ -f <format>       | --format=<format> ]\n" \
2657         "[ -F <spec>         | --format-spec=<spec> ]\n" \
2658         "[ -h                | --hash-by-name ]\n" \
2659         "[ -o <file>         | --output=<file> ]\n" \
2660         "[ -O                | --no-text-output ]\n" \
2661         "[ -q                | --quiet ]\n" \
2662         "[ -s                | --per-program-stats ]\n" \
2663         "[ -t                | --track-ios ]\n" \
2664         "[ -w <time>         | --stopwatch=<time> ]\n" \
2665         "[ -v                | --verbose ]\n" \
2666         "[ -V                | --version ]\n\n" \
2667         "\t-b stdin read batching\n" \
2668         "\t-d Output file. If specified, binary data is written to file\n" \
2669         "\t-D Directory to prepend to input file names\n" \
2670         "\t-f Output format. Customize the output format. The format field\n" \
2671         "\t   identifies can be found in the documentation\n" \
2672         "\t-F Format specification. Can be found in the documentation\n" \
2673         "\t-h Hash processes by name, not pid\n" \
2674         "\t-i Input file containing trace data, or '-' for stdin\n" \
2675         "\t-o Output file. If not given, output is stdout\n" \
2676         "\t-O Do NOT output text data\n" \
2677         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
2678         "\t-s Show per-program io statistics\n" \
2679         "\t-t Track individual ios. Will tell you the time a request took\n" \
2680         "\t   to get queued, to get dispatched, and to get completed\n" \
2681         "\t-w Only parse data between the given time interval in seconds.\n" \
2682         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
2683         "\t-v More verbose for marginal errors\n" \
2684         "\t-V Print program version info\n\n";
2685
2686 static void usage(char *prog)
2687 {
2688         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
2689 }
2690
2691 int main(int argc, char *argv[])
2692 {
2693         int i, c, ret, mode;
2694         int act_mask_tmp = 0;
2695         char *ofp_buffer = NULL;
2696         char *bin_ofp_buffer = NULL;
2697
2698         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
2699                 switch (c) {
2700                 case 'a':
2701                         i = find_mask_map(optarg);
2702                         if (i < 0) {
2703                                 fprintf(stderr,"Invalid action mask %s\n",
2704                                         optarg);
2705                                 return 1;
2706                         }
2707                         act_mask_tmp |= i;
2708                         break;
2709
2710                 case 'A':
2711                         if ((sscanf(optarg, "%x", &i) != 1) || 
2712                                                         !valid_act_opt(i)) {
2713                                 fprintf(stderr,
2714                                         "Invalid set action mask %s/0x%x\n",
2715                                         optarg, i);
2716                                 return 1;
2717                         }
2718                         act_mask_tmp = i;
2719                         break;
2720                 case 'i':
2721                         if (is_pipe(optarg) && !pipeline) {
2722                                 pipeline = 1;
2723                                 pipename = strdup(optarg);
2724                         } else if (resize_devices(optarg) != 0)
2725                                 return 1;
2726                         break;
2727                 case 'D':
2728                         input_dir = optarg;
2729                         break;
2730                 case 'o':
2731                         output_name = optarg;
2732                         break;
2733                 case 'O':
2734                         text_output = 0;
2735                         break;
2736                 case 'b':
2737                         rb_batch = atoi(optarg);
2738                         if (rb_batch <= 0)
2739                                 rb_batch = RB_BATCH_DEFAULT;
2740                         break;
2741                 case 's':
2742                         per_process_stats = 1;
2743                         break;
2744                 case 't':
2745                         track_ios = 1;
2746                         break;
2747                 case 'q':
2748                         per_device_and_cpu_stats = 0;
2749                         break;
2750                 case 'w':
2751                         if (find_stopwatch_interval(optarg) != 0)
2752                                 return 1;
2753                         break;
2754                 case 'f':
2755                         set_all_format_specs(optarg);
2756                         break;
2757                 case 'F':
2758                         if (add_format_spec(optarg) != 0)
2759                                 return 1;
2760                         break;
2761                 case 'h':
2762                         ppi_hash_by_pid = 0;
2763                         break;
2764                 case 'v':
2765                         verbose++;
2766                         break;
2767                 case 'V':
2768                         printf("%s version %s\n", argv[0], blkparse_version);
2769                         return 0;
2770                 case 'd':
2771                         dump_binary = optarg;
2772                         break;
2773                 default:
2774                         usage(argv[0]);
2775                         return 1;
2776                 }
2777         }
2778
2779         while (optind < argc) {
2780                 if (is_pipe(argv[optind]) && !pipeline) {
2781                         pipeline = 1;
2782                         pipename = strdup(argv[optind]);
2783                 } else if (resize_devices(argv[optind]) != 0)
2784                         return 1;
2785                 optind++;
2786         }
2787
2788         if (!pipeline && !ndevices) {
2789                 usage(argv[0]);
2790                 return 1;
2791         }
2792
2793         if (act_mask_tmp != 0)
2794                 act_mask = act_mask_tmp;
2795
2796         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
2797
2798         signal(SIGINT, handle_sigint);
2799         signal(SIGHUP, handle_sigint);
2800         signal(SIGTERM, handle_sigint);
2801
2802         setlocale(LC_NUMERIC, "en_US");
2803
2804         if (text_output) {
2805                 if (!output_name) {
2806                         ofp = fdopen(STDOUT_FILENO, "w");
2807                         mode = _IOLBF;
2808                 } else {
2809                         char ofname[128];
2810
2811                         snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
2812                         ofp = fopen(ofname, "w");
2813                         mode = _IOFBF;
2814                 }
2815
2816                 if (!ofp) {
2817                         perror("fopen");
2818                         return 1;
2819                 }
2820
2821                 ofp_buffer = malloc(4096);
2822                 if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
2823                         perror("setvbuf");
2824                         return 1;
2825                 }
2826         }
2827
2828         if (dump_binary) {
2829                 dump_fp = fopen(dump_binary, "w");
2830                 if (!dump_fp) {
2831                         perror(dump_binary);
2832                         dump_binary = NULL;
2833                         return 1;
2834                 }
2835                 bin_ofp_buffer = malloc(128 * 1024);
2836                 if (setvbuf(dump_fp, bin_ofp_buffer, _IOFBF, 128 * 1024)) {
2837                         perror("setvbuf binary");
2838                         return 1;
2839                 }
2840         }
2841
2842         if (pipeline)
2843                 ret = do_fifo();
2844         else
2845                 ret = do_file();
2846
2847         if (!ret)
2848                 show_stats();
2849
2850         if (have_drv_data && !dump_binary)
2851                 printf("\ndiscarded traces containing low-level device driver "
2852                        "specific data (only available in binary output)\n");
2853
2854         if (ofp_buffer) {
2855                 fflush(ofp);
2856                 free(ofp_buffer);
2857         }
2858         if (bin_ofp_buffer) {
2859                 fflush(dump_fp);
2860                 free(bin_ofp_buffer);
2861         }
2862         return ret;
2863 }