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