[PATCH] blkparse: fix sorting of file events regardless of batch size
[blktrace.git] / blkparse.c
1 /*
2  * block queue tracing parse application
3  *
4  * Copyright (C) 2005 Jens Axboe <axboe@suse.de>
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  */
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24 #include <stdio.h>
25 #include <fcntl.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <getopt.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <locale.h>
32 #include <limits.h>
33 #include <ctype.h>
34
35 #include "blktrace.h"
36 #include "rbtree.h"
37
38 static char blkparse_version[] = "0.90";
39
40 #define SECONDS(x)              ((unsigned long long)(x) / 1000000000)
41 #define NANO_SECONDS(x)         ((unsigned long long)(x) % 1000000000)
42 #define DOUBLE_TO_NANO_ULL(d)   ((unsigned long long)((d) * 1000000000))
43
44 #define MINORBITS       20
45 #define MINORMASK       ((1U << MINORBITS) - 1)
46 #define MAJOR(dev)      ((unsigned int) ((dev) >> MINORBITS))
47 #define MINOR(dev)      ((unsigned int) ((dev) & MINORMASK))
48
49 #define min(a, b)       ((a) < (b) ? (a) : (b))
50
51 #define HEADER          "%D %2c %8s %5T.%9t %5p %2a %3d "
52
53 struct io_stats {
54         unsigned long qreads, qwrites, creads, cwrites, mreads, mwrites;
55         unsigned long ireads, iwrites;
56         unsigned long long qread_kb, qwrite_kb, cread_kb, cwrite_kb;
57         unsigned long long iread_kb, iwrite_kb;
58         unsigned long io_unplugs, timer_unplugs;
59 };
60
61 struct per_cpu_info {
62         int cpu;
63         int nelems;
64
65         int fd;
66         char fname[128];
67
68         struct io_stats io_stats;
69 };
70
71 struct per_dev_info {
72         dev_t id;
73         char *name;
74
75         int backwards;
76         unsigned long long events;
77         unsigned long long last_reported_time;
78         unsigned long long last_read_time;
79         struct io_stats io_stats;
80         unsigned long last_sequence;
81         unsigned long skips;
82
83         int nfiles;
84         int ncpus;
85         struct per_cpu_info *cpus;
86 };
87
88 struct per_process_info {
89         char name[16];
90         __u32 pid;
91         struct io_stats io_stats;
92         struct per_process_info *hash_next, *list_next;
93
94         /*
95          * individual io stats
96          */
97         unsigned long long longest_allocation_wait[2];
98         unsigned long long longest_dispatch_wait[2];
99         unsigned long long longest_completion_wait[2];
100 };
101
102 #define PPI_HASH_SHIFT  (8)
103 static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
104 static struct per_process_info *ppi_list;
105 static int ppi_list_entries;
106
107 #define S_OPTS  "i:o:b:stqw:f:F:v"
108 static struct option l_opts[] = {
109         {
110                 .name = "input",
111                 .has_arg = required_argument,
112                 .flag = NULL,
113                 .val = 'i'
114         },
115         {
116                 .name = "output",
117                 .has_arg = required_argument,
118                 .flag = NULL,
119                 .val = 'o'
120         },
121         {
122                 .name = "batch",
123                 .has_arg = required_argument,
124                 .flag = NULL,
125                 .val = 'b'
126         },
127         {
128                 .name = "per program stats",
129                 .has_arg = no_argument,
130                 .flag = NULL,
131                 .val = 's'
132         },
133         {
134                 .name = "track ios",
135                 .has_arg = no_argument,
136                 .flag = NULL,
137                 .val = 't'
138         },
139         {
140                 .name = "quiet",
141                 .has_arg = no_argument,
142                 .flag = NULL,
143                 .val = 'q'
144         },
145         {
146                 .name = "stopwatch",
147                 .has_arg = required_argument,
148                 .flag = NULL,
149                 .val = 'w'
150         },
151         {
152                 .name = "format",
153                 .has_arg = required_argument,
154                 .flag = NULL,
155                 .val = 'f'
156         },
157         {
158                 .name = "format-spec",
159                 .has_arg = required_argument,
160                 .flag = NULL,
161                 .val = 'F'
162         },
163         {
164                 .name = "version",
165                 .has_arg = no_argument,
166                 .flag = NULL,
167                 .val = 'v'
168         },
169 };
170
171 /*
172  * for sorting the displayed output
173  */
174 struct trace {
175         struct blk_io_trace *bit;
176         struct rb_node rb_node;
177         struct trace *next;
178         int skipped;
179 };
180
181 static struct rb_root rb_sort_root;
182 static struct rb_root rb_track_root;
183
184 static struct trace *trace_list;
185
186 /*
187  * allocation cache
188  */
189 static struct blk_io_trace *bit_alloc_list;
190 static struct trace *t_alloc_list;
191
192 /*
193  * for tracking individual ios
194  */
195 struct io_track {
196         struct rb_node rb_node;
197
198         dev_t device;
199         __u64 sector;
200         __u32 pid;
201         unsigned long long allocation_time;
202         unsigned long long queue_time;
203         unsigned long long dispatch_time;
204         unsigned long long completion_time;
205 };
206
207 static int ndevices;
208 static struct per_dev_info *devices;
209 static char *get_dev_name(struct per_dev_info *, char *, int);
210
211 static FILE *ofp;
212 static char *output_name;
213
214 static unsigned long long genesis_time;
215 static unsigned long long last_allowed_time;
216 static unsigned long long stopwatch_start;      /* start from zero by default */
217 static unsigned long long stopwatch_end = ULONG_LONG_MAX;       /* "infinity" */
218
219 static int per_process_stats;
220 static int track_ios;
221
222 #define RB_BATCH_DEFAULT        (512)
223 static int rb_batch = RB_BATCH_DEFAULT;
224
225 static int pipeline;
226
227 #define is_done()       (*(volatile int *)(&done))
228 static volatile int done;
229
230 static inline unsigned long hash_long(unsigned long val)
231 {
232 #if __WORDSIZE == 32
233         val *= 0x9e370001UL;
234 #elif __WORDSIZE == 64
235         val *= 0x9e37fffffffc0001UL;
236 #else
237 #error unknown word size
238 #endif
239
240         return val >> (__WORDSIZE - PPI_HASH_SHIFT);
241 }
242
243 static inline void add_process_to_hash(struct per_process_info *ppi)
244 {
245         const int hash_idx = hash_long(ppi->pid);
246
247         ppi->hash_next = ppi_hash[hash_idx];
248         ppi_hash[hash_idx] = ppi;
249 }
250
251 static inline void add_process_to_list(struct per_process_info *ppi)
252 {
253         ppi->list_next = ppi_list;
254         ppi_list = ppi;
255         ppi_list_entries++;
256 }
257
258 static struct per_process_info *find_process_by_pid(__u32 pid)
259 {
260         const int hash_idx = hash_long(pid);
261         struct per_process_info *ppi;
262
263         ppi = ppi_hash[hash_idx];
264         while (ppi) {
265                 if (ppi->pid == pid)
266                         return ppi;
267
268                 ppi = ppi->hash_next;
269         }
270
271         return NULL;
272 }
273
274 static inline int trace_rb_insert(struct trace *t)
275 {
276         struct rb_node **p = &rb_sort_root.rb_node;
277         struct rb_node *parent = NULL;
278         struct trace *__t;
279
280         while (*p) {
281                 parent = *p;
282                 __t = rb_entry(parent, struct trace, rb_node);
283
284                 if (t->bit->time < __t->bit->time)
285                         p = &(*p)->rb_left;
286                 else if (t->bit->time > __t->bit->time)
287                         p = &(*p)->rb_right;
288                 else if (t->bit->device < __t->bit->device)
289                         p = &(*p)->rb_left;
290                 else if (t->bit->device > __t->bit->device)
291                         p = &(*p)->rb_right;
292                 else if (t->bit->sequence < __t->bit->sequence)
293                         p = &(*p)->rb_left;
294                 else if (t->bit->sequence > __t->bit->sequence)
295                         p = &(*p)->rb_right;
296                 else if (t->bit->device == __t->bit->device) {
297                         fprintf(stderr,
298                                 "sequence alias (%d) on device %d,%d!\n",
299                                 t->bit->sequence,
300                                 MAJOR(t->bit->device), MINOR(t->bit->device));
301                         return 1;
302                 }
303         }
304
305         rb_link_node(&t->rb_node, parent, p);
306         rb_insert_color(&t->rb_node, &rb_sort_root);
307         return 0;
308 }
309
310 static inline int track_rb_insert(struct io_track *iot)
311 {
312         struct rb_node **p = &rb_track_root.rb_node;
313         struct rb_node *parent = NULL;
314         struct io_track *__iot;
315
316         while (*p) {
317                 parent = *p;
318
319                 __iot = rb_entry(parent, struct io_track, rb_node);
320
321                 if (iot->device < __iot->device)
322                         p = &(*p)->rb_left;
323                 else if (iot->device > __iot->device)
324                         p = &(*p)->rb_right;
325                 else if (iot->sector < __iot->sector)
326                         p = &(*p)->rb_left;
327                 else if (iot->sector > __iot->sector)
328                         p = &(*p)->rb_right;
329                 else {
330                         fprintf(stderr,
331                                 "sector alias (%Lu) on device %d,%d!\n",
332                                 (unsigned long long) iot->sector,
333                                 MAJOR(iot->device), MINOR(iot->device));
334                         return 1;
335                 }
336         }
337
338         rb_link_node(&iot->rb_node, parent, p);
339         rb_insert_color(&iot->rb_node, &rb_track_root);
340         return 0;
341 }
342
343 static struct io_track *__find_track(dev_t device, __u64 sector)
344 {
345         struct rb_node **p = &rb_track_root.rb_node;
346         struct rb_node *parent = NULL;
347         struct io_track *__iot;
348
349         while (*p) {
350                 parent = *p;
351                 
352                 __iot = rb_entry(parent, struct io_track, rb_node);
353
354                 if (device < __iot->device)
355                         p = &(*p)->rb_left;
356                 else if (device > __iot->device)
357                         p = &(*p)->rb_right;
358                 else if (sector < __iot->sector)
359                         p = &(*p)->rb_left;
360                 else if (sector > __iot->sector)
361                         p = &(*p)->rb_right;
362                 else
363                         return __iot;
364         }
365
366         return NULL;
367 }
368
369 static struct io_track *find_track(__u32 pid, dev_t device, __u64 sector)
370 {
371         struct io_track *iot;
372
373         iot = __find_track(device, sector);
374         if (!iot) {
375                 iot = malloc(sizeof(*iot));
376                 iot->pid = pid;
377                 iot->device = device;
378                 iot->sector = sector;
379                 track_rb_insert(iot);
380         }
381
382         return iot;
383 }
384
385 static void log_track_frontmerge(struct blk_io_trace *t)
386 {
387         struct io_track *iot;
388
389         if (!track_ios)
390                 return;
391
392         iot = __find_track(t->device, t->sector + (t->bytes >> 9));
393         if (!iot) {
394                 fprintf(stderr, "failed to find mergeable event\n");
395                 return;
396         }
397
398         rb_erase(&iot->rb_node, &rb_track_root);
399         iot->sector -= t->bytes >> 9;
400         track_rb_insert(iot);
401 }
402
403 static void log_track_getrq(struct blk_io_trace *t)
404 {
405         struct io_track *iot;
406
407         if (!track_ios)
408                 return;
409
410         iot = find_track(t->pid, t->device, t->sector);
411         iot->allocation_time = t->time;
412 }
413
414
415 /*
416  * return time between rq allocation and insertion
417  */
418 static unsigned long long log_track_insert(struct blk_io_trace *t)
419 {
420         unsigned long long elapsed;
421         struct io_track *iot;
422
423         if (!track_ios)
424                 return -1;
425
426         iot = find_track(t->pid, t->device, t->sector);
427         iot->queue_time = t->time;
428         elapsed = iot->queue_time - iot->allocation_time;
429
430         if (per_process_stats) {
431                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
432                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
433
434                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
435                         ppi->longest_allocation_wait[w] = elapsed;
436         }
437
438         return elapsed;
439 }
440
441 /*
442  * return time between queue and issue
443  */
444 static unsigned long long log_track_issue(struct blk_io_trace *t)
445 {
446         unsigned long long elapsed;
447         struct io_track *iot;
448
449         if (!track_ios)
450                 return -1;
451         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
452                 return -1;
453
454         iot = __find_track(t->device, t->sector);
455         if (!iot) {
456                 fprintf(stderr, "failed to find issue event\n");
457                 return -1;
458         }
459
460         iot->dispatch_time = t->time;
461         elapsed = iot->dispatch_time - iot->queue_time;
462
463         if (per_process_stats) {
464                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
465                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
466
467                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
468                         ppi->longest_dispatch_wait[w] = elapsed;
469         }
470
471         return elapsed;
472 }
473
474 /*
475  * return time between dispatch and complete
476  */
477 static unsigned long long log_track_complete(struct blk_io_trace *t)
478 {
479         unsigned long long elapsed;
480         struct io_track *iot;
481
482         if (!track_ios)
483                 return -1;
484         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
485                 return -1;
486
487         iot = __find_track(t->device, t->sector);
488         if (!iot) {
489                 fprintf(stderr, "failed to find complete event\n");
490                 return -1;
491         }
492
493         iot->completion_time = t->time;
494         elapsed = iot->completion_time - iot->dispatch_time;
495
496         if (per_process_stats) {
497                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
498                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
499
500                 if (ppi && elapsed > ppi->longest_completion_wait[w])
501                         ppi->longest_completion_wait[w] = elapsed;
502         }
503
504         /*
505          * kill the trace, we don't need it after completion
506          */
507         rb_erase(&iot->rb_node, &rb_track_root);
508         free(iot);
509
510         return elapsed;
511 }
512
513
514 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
515 {
516         struct per_process_info *ppi = find_process_by_pid(pid);
517
518         if (!ppi) {
519                 ppi = malloc(sizeof(*ppi));
520                 memset(ppi, 0, sizeof(*ppi));
521                 strncpy(ppi->name, name, sizeof(ppi->name));
522                 ppi->pid = pid;
523                 add_process_to_hash(ppi);
524                 add_process_to_list(ppi);
525         }
526
527         return &ppi->io_stats;
528 }
529
530
531 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
532 {
533         struct per_cpu_info *cpus = pdi->cpus;
534         int ncpus = pdi->ncpus;
535         int new_count = cpu + 1;
536         int new_space, size;
537         char *new_start;
538
539         size = new_count * sizeof(struct per_cpu_info);
540         cpus = realloc(cpus, size);
541         if (!cpus) {
542                 char name[20];
543                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
544                         get_dev_name(pdi, name, sizeof(name)), size);
545                 exit(1);
546         }
547
548         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
549         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
550         memset(new_start, 0, new_space);
551
552         pdi->ncpus = new_count;
553         pdi->cpus = cpus;
554 }
555
556 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
557 {
558         struct per_cpu_info *pci;
559
560         if (cpu >= pdi->ncpus)
561                 resize_cpu_info(pdi, cpu);
562
563         pci = &pdi->cpus[cpu];
564         pci->cpu = cpu;
565         return pci;
566 }
567
568
569 static int resize_devices(char *name)
570 {
571         int size = (ndevices + 1) * sizeof(struct per_dev_info);
572
573         devices = realloc(devices, size);
574         if (!devices) {
575                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
576                 return 1;
577         }
578         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
579         devices[ndevices].name = name;
580         ndevices++;
581         return 0;
582 }
583
584 static struct per_dev_info *get_dev_info(dev_t id)
585 {
586         struct per_dev_info *pdi;
587         int i;
588
589         for (i = 0; i < ndevices; i++) {
590                 if (!devices[i].id)
591                         devices[i].id = id;
592                 if (devices[i].id == id)
593                         return &devices[i];
594         }
595
596         if (resize_devices(NULL) != 0)
597                 return NULL;
598
599         pdi = &devices[ndevices - 1];
600         pdi->id = id;
601         pdi->last_sequence = -1;
602         pdi->last_read_time = 0;
603         return pdi;
604 }
605
606 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
607 {
608         if (pdi->name)
609                 snprintf(buffer, size, "%s", pdi->name);
610         else
611                 snprintf(buffer, size, "%d,%d", MAJOR(pdi->id), MINOR(pdi->id));
612         return buffer;
613 }
614
615 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
616 {
617         unsigned long long this = bit->time;
618         unsigned long long last = pdi->last_reported_time;
619
620         pdi->backwards = (this < last) ? 'B' : ' ';
621         pdi->last_reported_time = this;
622 }
623
624 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
625                                int rw)
626 {
627         if (rw) {
628                 ios->mwrites++;
629                 ios->qwrite_kb += t->bytes >> 10;
630         } else {
631                 ios->mreads++;
632                 ios->qread_kb += t->bytes >> 10;
633         }
634 }
635
636 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
637                              int rw)
638 {
639         __account_m(&pci->io_stats, t, rw);
640
641         if (per_process_stats) {
642                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
643
644                 __account_m(ios, t, rw);
645         }
646 }
647
648 static inline void __account_queue(struct io_stats *ios, struct blk_io_trace *t,
649                                    int rw)
650 {
651         if (rw) {
652                 ios->qwrites++;
653                 ios->qwrite_kb += t->bytes >> 10;
654         } else {
655                 ios->qreads++;
656                 ios->qread_kb += t->bytes >> 10;
657         }
658 }
659
660 static inline void account_queue(struct blk_io_trace *t,
661                                  struct per_cpu_info *pci, int rw)
662 {
663         __account_queue(&pci->io_stats, t, rw);
664
665         if (per_process_stats) {
666                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
667
668                 __account_queue(ios, t, rw);
669         }
670 }
671
672 static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
673 {
674         if (rw) {
675                 ios->cwrites++;
676                 ios->cwrite_kb += bytes >> 10;
677         } else {
678                 ios->creads++;
679                 ios->cread_kb += bytes >> 10;
680         }
681 }
682
683 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
684                              int rw, int bytes)
685 {
686         __account_c(&pci->io_stats, rw, bytes);
687
688         if (per_process_stats) {
689                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
690
691                 __account_c(ios, rw, bytes);
692         }
693 }
694
695 static inline void __account_issue(struct io_stats *ios, int rw,
696                                    unsigned int bytes)
697 {
698         if (rw) {
699                 ios->iwrites++;
700                 ios->iwrite_kb += bytes >> 10;
701         } else {
702                 ios->ireads++;
703                 ios->iread_kb += bytes >> 10;
704         }
705 }
706
707 static inline void account_issue(struct blk_io_trace *t,
708                                  struct per_cpu_info *pci, int rw)
709 {
710         __account_issue(&pci->io_stats, rw, t->bytes);
711
712         if (per_process_stats) {
713                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
714
715                 __account_issue(ios, rw, t->bytes);
716         }
717 }
718
719 static inline void __account_unplug(struct io_stats *ios, int timer)
720 {
721         if (timer)
722                 ios->timer_unplugs++;
723         else
724                 ios->io_unplugs++;
725 }
726
727 static inline void account_unplug(struct blk_io_trace *t,
728                                   struct per_cpu_info *pci, int timer)
729 {
730         __account_unplug(&pci->io_stats, timer);
731
732         if (per_process_stats) {
733                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
734
735                 __account_unplug(ios, timer);
736         }
737 }
738
739 #define VALID_SPECS     "BCDFGMPQRSTU"
740 static char *override_format[256];
741 static inline int valid_spec(int spec)
742 {
743         return strchr(VALID_SPECS, spec) != NULL;
744 }
745
746 static void set_all_format_specs(char *optarg)
747 {
748         char *p;
749
750         for (p = VALID_SPECS; *p; p++)
751                 if (override_format[(int)(*p)] == NULL)
752                         override_format[(int)(*p)] = strdup(optarg);
753 }
754
755 static int add_format_spec(char *optarg)
756 {
757         int spec = optarg[0];
758
759         if (!valid_spec(spec)) {
760                 fprintf(stderr,"Bad format specifier %c\n", spec);
761                 return 1;
762         }
763         if (optarg[1] != ',') {
764                 fprintf(stderr,"Bad format specifier - need ',' %s\n", optarg);
765                 return 1;
766         }
767         optarg += 2;
768         if (*optarg == '\0') {
769                 fprintf(stderr,"Bad format specifier - need fmt %s\n", optarg);
770                 return 1;
771         }
772
773         /*
774          * Set both merges (front and back)
775          */
776         if (spec == 'M') {
777                 override_format['B'] = strdup(optarg);
778                 override_format['M'] = strdup(optarg);
779         } else
780                 override_format[spec] = strdup(optarg);
781
782         return 0;
783 }
784
785 static void print_field(char *act, struct per_cpu_info *pci,
786                         struct blk_io_trace *t, unsigned long long elapsed,
787                         int pdu_len, unsigned char *pdu_buf, char field,
788                         int minus, int has_w, int width)
789 {
790         char format[64];
791
792         if (has_w) {
793                 if (minus)
794                         sprintf(format, "%%-%d", width);
795                 else
796                         sprintf(format, "%%%d", width);
797         } else
798                 sprintf(format, "%%");
799
800         switch (field) {
801         case 'a':
802                 fprintf(ofp, strcat(format, "s"), act);
803                 break;
804         case 'c':
805                 fprintf(ofp, strcat(format, "d"), pci->cpu);
806                 break;
807         case 'C':
808                 fprintf(ofp, strcat(format, "s"), t->comm);
809                 break;
810         case 'd': {
811                 char rwbs[4];
812                 int i = 0;
813                 int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
814                 int b = t->action & BLK_TC_ACT(BLK_TC_BARRIER);
815                 int s = t->action & BLK_TC_ACT(BLK_TC_SYNC);
816                 if (w)
817                         rwbs[i++] = 'W';
818                 else
819                         rwbs[i++] = 'R';
820                 if (b)
821                         rwbs[i++] = 'B';
822                 if (s)
823                         rwbs[i++] = 'S';
824                 rwbs[i] = '\0';
825                 fprintf(ofp, strcat(format, "s"), rwbs);
826                 break;
827         }
828         case 'D':       /* format width ignored */
829                 fprintf(ofp,"%3d,%-3d", MAJOR(t->device), MINOR(t->device));
830                 break;
831         case 'e':
832                 fprintf(ofp, strcat(format, "d"), t->error);
833                 break;
834         case 'M':
835                 fprintf(ofp, strcat(format, "d"), MAJOR(t->device));
836                 break;
837         case 'm':
838                 fprintf(ofp, strcat(format, "d"), MINOR(t->device));
839                 break;
840         case 'n':
841                 fprintf(ofp, strcat(format, "u"), t->bytes >> 9);
842                 break;
843         case 'p':
844                 fprintf(ofp, strcat(format, "u"), t->pid);
845                 break;
846         case 'P':       /* format width ignored */
847                 if ((pdu_len > 0) && (pdu_buf != NULL)) {
848                         int i;
849                         unsigned char *p = pdu_buf;
850                         for (i = 0; i < pdu_len; i++) {
851                                 if (i)
852                                         fprintf(ofp, " ");
853
854                                 fprintf(ofp, "%02x", *p++);
855                         }
856                 }
857                 break;
858         case 's':
859                 fprintf(ofp, strcat(format, "ld"), t->sequence);
860                 break;
861         case 'S':
862                 fprintf(ofp, strcat(format, "lu"), t->sector);
863                 break;
864         case 't':
865                 sprintf(format, "%%0%dlu", has_w ? width : 9);
866                 fprintf(ofp, format, NANO_SECONDS(t->time));
867                 break;
868         case 'T':
869                 fprintf(ofp, strcat(format, "d"), SECONDS(t->time));
870                 break;
871         case 'u':
872                 if (elapsed == -1ULL) {
873                         fprintf(stderr, "Expecting elapsed value\n");
874                         exit(1);
875                 }
876                 fprintf(ofp, strcat(format, "llu"), elapsed / 1000);
877                 break;
878         case 'U': {
879                 __u64 *depth = (__u64 *) ((char *) t + sizeof(*t));
880                 fprintf(ofp, strcat(format, "u"),
881                                         (unsigned int) be64_to_cpu(*depth));
882                 break;
883         }
884         default:
885                 fprintf(ofp,strcat(format, "c"), field);
886                 break;
887         }
888 }
889
890 static char *parse_field(char *act, struct per_cpu_info *pci, 
891                          struct blk_io_trace *t, unsigned long long elapsed, 
892                          int pdu_len, unsigned char *pdu_buf, 
893                          char *master_format)
894 {
895         int minus = 0;
896         int has_w = 0;
897         int width = 0;
898         char *p = master_format;
899
900         if (*p == '-') {
901                 minus = 1;
902                 p++;
903         }
904         if (isdigit(*p)) {
905                 has_w = 1;
906                 do {
907                         width = (width * 10) + (*p++ - '0');
908                 } while ((*p) && (isdigit(*p)));
909         }
910         if (*p) {
911                 print_field(act, pci, t, elapsed, pdu_len, pdu_buf, *p++,
912                             minus, has_w, width);
913         }
914         return p;
915 }
916
917 static char *fmt_select(int fmt_spec, struct blk_io_trace *t,
918                         unsigned long long elapsed)
919 {
920         char *fmt;
921         static char scratch_format[1024];
922
923         if (override_format[fmt_spec] != NULL)
924                 return override_format[fmt_spec];
925
926         switch (fmt_spec) {
927         case 'C':       /* Complete */
928                 if (t->action & BLK_TC_ACT(BLK_TC_PC))
929                         strcpy(scratch_format, HEADER "(%P) [%e]\n");
930                 else {
931                         if (elapsed != -1ULL) {
932                                 strcpy(scratch_format,
933                                         HEADER "%S +%n (%8u) [%e]\n");
934                         } else
935                                 strcpy(scratch_format, HEADER "%S + %n [%e]\n");
936                 }
937                 fmt = scratch_format;
938                 break;
939
940         case 'D':       /* Issue */
941                 if (t->action & BLK_TC_ACT(BLK_TC_PC))
942                         strcpy(scratch_format, HEADER "%n (%P) [%C]\n");
943                 else {
944                         if (elapsed != -1ULL) {
945                                 strcpy(scratch_format,
946                                         HEADER "%S + %n (%8u) [%C]\n");
947                         } else
948                                 strcpy(scratch_format, HEADER "%S + %n [%C]\n");
949                 }
950                 fmt = scratch_format;
951                 break;
952
953         case 'I':       /* Insert */
954                 if (t->action & BLK_TC_ACT(BLK_TC_PC))
955                         strcpy(scratch_format, HEADER "%n (%P) [%C]\n");
956                 else {
957                         if (elapsed != -1ULL) {
958                                 strcpy(scratch_format,
959                                         HEADER "%S + %n (%8u) [%C]\n");
960                         } else
961                                 strcpy(scratch_format, HEADER "%S + %n [%C]\n");
962                 }
963                 fmt = scratch_format;
964                 break;
965
966         case 'Q':       /* Queue */
967         case 'W':       /* Bounce */
968                 if (elapsed != -1ULL) {
969                         strcpy(scratch_format, HEADER "%S + %n (%8u) [%C]\n");
970                 } else
971                         strcpy(scratch_format, HEADER "%S + %n [%C]\n");
972                 fmt = scratch_format;
973                 break;
974
975         case 'B':       /* Back merge */
976         case 'F':       /* Front merge */
977         case 'M':       /* Front or back merge */
978                 fmt = HEADER "%S + %n [%C]\n";
979                 break;
980
981         case 'P':       /* Plug */
982                 fmt = HEADER "[%C]\n";
983                 break;
984
985         case 'G':       /* Get request */
986         case 'S':       /* Sleep request */
987                 fmt = HEADER "%S + %n [%C]\n";
988                 break;
989
990         case 'U':       /* Unplug IO */
991         case 'T':       /* Unplug timer */
992                 fmt = HEADER "[%C] %U\n";
993                 break;
994
995         case 'X':       /* Split */
996                 strcpy(scratch_format, HEADER "%S / %U [%C]\n");
997                 fmt = scratch_format;
998                 break;
999
1000         default:
1001                 fprintf(stderr,"FATAL: Invalid format spec %c\n", fmt_spec);
1002                 exit(1);
1003                 /*NOTREACHED*/
1004         }
1005
1006         return fmt;
1007 }
1008
1009 static void process_fmt(char *act, struct per_cpu_info *pci,
1010                            struct blk_io_trace *t, unsigned long long elapsed,
1011                            int pdu_len, unsigned char *pdu_buf)
1012 {
1013         char *p = fmt_select(act[0], t, elapsed);
1014
1015         while (*p) {
1016                 switch (*p) {
1017                 case '%':       /* Field specifier */
1018                         p++;
1019                         if (*p == '%')
1020                                 fprintf(ofp, "%c", *p++);
1021                         else if (!*p)
1022                                 fprintf(ofp, "%c", '%');
1023                         else
1024                                 p = parse_field(act, pci, t, elapsed,
1025                                                 pdu_len, pdu_buf, p);
1026                         break;
1027                 case '\\': {    /* escape */
1028                         switch (p[1]) {
1029                         case 'b': fprintf(ofp, "\b"); break;
1030                         case 'n': fprintf(ofp, "\n"); break;
1031                         case 'r': fprintf(ofp, "\r"); break;
1032                         case 't': fprintf(ofp, "\t"); break;
1033                         default:
1034                                 fprintf(stderr, 
1035                                         "Invalid escape char in format %c\n",
1036                                         p[1]);
1037                                 exit(1);
1038                                 /*NOTREACHED*/
1039                         }
1040                         p += 2;
1041                         break;
1042                 }
1043                 default:
1044                         fprintf(ofp, "%c", *p++);
1045                         break;
1046                 }
1047         }
1048 }
1049
1050 static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
1051                          char *act)
1052 {
1053         process_fmt(act, pci, t, log_track_complete(t), 0, NULL);
1054 }
1055
1056 static void log_insert(struct per_cpu_info *pci, struct blk_io_trace *t,
1057                       char *act)
1058 {
1059         process_fmt(act, pci, t, log_track_insert(t), 0, NULL);
1060 }
1061
1062 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
1063                       char *act)
1064 {
1065         process_fmt(act, pci, t, -1, 0, NULL);
1066 }
1067
1068 static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
1069                       char *act)
1070 {
1071         process_fmt(act, pci, t, log_track_issue(t), 0, NULL);
1072 }
1073
1074 static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
1075                       char *act)
1076 {
1077         if (act[0] == 'F')
1078                 log_track_frontmerge(t);
1079
1080         process_fmt(act, pci, t, -1ULL, 0, NULL);
1081 }
1082
1083 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
1084                         char *act)
1085 {
1086         process_fmt(act, pci, t, -1ULL, 0, NULL);
1087 }
1088
1089 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
1090                         char *act)
1091 {
1092         process_fmt(act, pci, t, -1ULL, 0, NULL);
1093 }
1094
1095 static void log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
1096                       char *act)
1097 {
1098         process_fmt(act, pci, t, -1ULL, 0, NULL);
1099 }
1100
1101 static void log_split(struct per_cpu_info *pci, struct blk_io_trace *t,
1102                       char *act)
1103 {
1104         process_fmt(act, pci, t, -1ULL, 0, NULL);
1105 }
1106
1107 static void log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
1108 {
1109         unsigned char *buf = (unsigned char *) t + sizeof(*t);
1110
1111         process_fmt(act, pci, t, -1ULL, t->pdu_len, buf);
1112 }
1113
1114 static void dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
1115 {
1116         int act = t->action & 0xffff;
1117
1118         switch (act) {
1119                 case __BLK_TA_QUEUE:
1120                         log_generic(pci, t, "Q");
1121                         break;
1122                 case __BLK_TA_GETRQ:
1123                         log_generic(pci, t, "G");
1124                         break;
1125                 case __BLK_TA_SLEEPRQ:
1126                         log_generic(pci, t, "S");
1127                         break;
1128                 case __BLK_TA_REQUEUE:
1129                         log_generic(pci, t, "R");
1130                         break;
1131                 case __BLK_TA_ISSUE:
1132                         log_pc(pci, t, "D");
1133                         break;
1134                 case __BLK_TA_COMPLETE:
1135                         log_pc(pci, t, "C");
1136                         break;
1137                 case __BLK_TA_INSERT:
1138                         log_pc(pci, t, "I");
1139                         break;
1140                 default:
1141                         fprintf(stderr, "Bad pc action %x\n", act);
1142                         break;
1143         }
1144 }
1145
1146 static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
1147 {
1148         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
1149         int act = t->action & 0xffff;
1150
1151         switch (act) {
1152                 case __BLK_TA_QUEUE:
1153                         account_queue(t, pci, w);
1154                         log_queue(pci, t, "Q");
1155                         break;
1156                 case __BLK_TA_INSERT:
1157                         log_insert(pci, t, "I");
1158                         break;
1159                 case __BLK_TA_BACKMERGE:
1160                         account_m(t, pci, w);
1161                         log_merge(pci, t, "M");
1162                         break;
1163                 case __BLK_TA_FRONTMERGE:
1164                         account_m(t, pci, w);
1165                         log_merge(pci, t, "F");
1166                         break;
1167                 case __BLK_TA_GETRQ:
1168                         log_track_getrq(t);
1169                         log_generic(pci, t, "G");
1170                         break;
1171                 case __BLK_TA_SLEEPRQ:
1172                         log_generic(pci, t, "S");
1173                         break;
1174                 case __BLK_TA_REQUEUE:
1175                         account_c(t, pci, w, -t->bytes);
1176                         log_queue(pci, t, "R");
1177                         break;
1178                 case __BLK_TA_ISSUE:
1179                         account_issue(t, pci, w);
1180                         log_issue(pci, t, "D");
1181                         break;
1182                 case __BLK_TA_COMPLETE:
1183                         account_c(t, pci, w, t->bytes);
1184                         log_complete(pci, t, "C");
1185                         break;
1186                 case __BLK_TA_PLUG:
1187                         log_action(pci, t, "P");
1188                         break;
1189                 case __BLK_TA_UNPLUG_IO:
1190                         account_unplug(t, pci, 0);
1191                         log_unplug(pci, t, "U");
1192                         break;
1193                 case __BLK_TA_UNPLUG_TIMER:
1194                         account_unplug(t, pci, 1);
1195                         log_unplug(pci, t, "UT");
1196                         break;
1197                 case __BLK_TA_SPLIT:
1198                         log_split(pci, t, "X");
1199                         break;
1200                 case __BLK_TA_BOUNCE:
1201                         log_generic(pci, t, "B");
1202                         break;
1203                 default:
1204                         fprintf(stderr, "Bad fs action %x\n", t->action);
1205                         break;
1206         }
1207 }
1208
1209 static void dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
1210                        struct per_dev_info *pdi)
1211 {
1212         if (t->action & BLK_TC_ACT(BLK_TC_PC))
1213                 dump_trace_pc(t, pci);
1214         else
1215                 dump_trace_fs(t, pci);
1216
1217         pdi->events++;
1218 }
1219
1220 static void dump_io_stats(struct io_stats *ios, char *msg)
1221 {
1222         fprintf(ofp, "%s\n", msg);
1223
1224         fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
1225         fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
1226
1227         fprintf(ofp, " Read Dispatches: %'8lu, %'8LuKiB\t", ios->ireads, ios->iread_kb);
1228         fprintf(ofp, " Write Dispatches: %'8lu, %'8LuKiB\n", ios->iwrites,ios->iwrite_kb);
1229         fprintf(ofp, " Reads Completed: %'8lu, %'8LuKiB\t", ios->creads, ios->cread_kb);
1230         fprintf(ofp, " Writes Completed: %'8lu, %'8LuKiB\n", ios->cwrites,ios->cwrite_kb);
1231         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
1232         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
1233         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
1234         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
1235 }
1236
1237 static void dump_wait_stats(struct per_process_info *ppi)
1238 {
1239         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
1240         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
1241         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
1242         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
1243         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
1244         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
1245
1246         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
1247         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1248         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1249         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1250         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1251         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1252 }
1253
1254 static int ppi_name_compare(const void *p1, const void *p2)
1255 {
1256         struct per_process_info *ppi1 = *((struct per_process_info **) p1);
1257         struct per_process_info *ppi2 = *((struct per_process_info **) p2);
1258         int res;
1259
1260         res = strverscmp(ppi1->name, ppi2->name);
1261         if (!res)
1262                 res = ppi1->pid > ppi2->pid;
1263
1264         return res;
1265 }
1266
1267 static void sort_process_list(void)
1268 {
1269         struct per_process_info **ppis;
1270         struct per_process_info *ppi;
1271         int i = 0;
1272
1273         ppis = malloc(ppi_list_entries * sizeof(struct per_process_info *));
1274
1275         ppi = ppi_list;
1276         while (ppi) {
1277                 ppis[i++] = ppi;
1278                 ppi = ppi->list_next;
1279         }
1280
1281         qsort(ppis, ppi_list_entries, sizeof(ppi), ppi_name_compare);
1282
1283         i = ppi_list_entries - 1;
1284         ppi_list = NULL;
1285         while (i >= 0) {
1286                 ppi = ppis[i];
1287
1288                 ppi->list_next = ppi_list;
1289                 ppi_list = ppi;
1290                 i--;
1291         }
1292
1293         free(ppis);
1294 }
1295
1296 static void show_process_stats(void)
1297 {
1298         struct per_process_info *ppi;
1299
1300         sort_process_list();
1301
1302         ppi = ppi_list;
1303         while (ppi) {
1304                 char name[64];
1305
1306                 snprintf(name, sizeof(name)-1, "%s (%u)", ppi->name, ppi->pid);
1307                 dump_io_stats(&ppi->io_stats, name);
1308                 dump_wait_stats(ppi);
1309                 ppi = ppi->list_next;
1310         }
1311
1312         fprintf(ofp, "\n");
1313 }
1314
1315 static void show_device_and_cpu_stats(void)
1316 {
1317         struct per_dev_info *pdi;
1318         struct per_cpu_info *pci;
1319         struct io_stats total, *ios;
1320         int i, j, pci_events;
1321         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1322         char name[32];
1323
1324         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1325
1326                 memset(&total, 0, sizeof(total));
1327                 pci_events = 0;
1328
1329                 if (i > 0)
1330                         fprintf(ofp, "\n");
1331
1332                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1333                         if (!pci->nelems)
1334                                 continue;
1335
1336                         ios = &pci->io_stats;
1337                         total.qreads += ios->qreads;
1338                         total.qwrites += ios->qwrites;
1339                         total.creads += ios->creads;
1340                         total.cwrites += ios->cwrites;
1341                         total.mreads += ios->mreads;
1342                         total.mwrites += ios->mwrites;
1343                         total.ireads += ios->ireads;
1344                         total.iwrites += ios->iwrites;
1345                         total.qread_kb += ios->qread_kb;
1346                         total.qwrite_kb += ios->qwrite_kb;
1347                         total.cread_kb += ios->cread_kb;
1348                         total.cwrite_kb += ios->cwrite_kb;
1349                         total.iread_kb += ios->iread_kb;
1350                         total.iwrite_kb += ios->iwrite_kb;
1351                         total.timer_unplugs += ios->timer_unplugs;
1352                         total.io_unplugs += ios->io_unplugs;
1353
1354                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1355                                  j, get_dev_name(pdi, name, sizeof(name)));
1356                         dump_io_stats(ios, line);
1357                         pci_events++;
1358                 }
1359
1360                 if (pci_events > 1) {
1361                         fprintf(ofp, "\n");
1362                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1363                                  get_dev_name(pdi, name, sizeof(name)));
1364                         dump_io_stats(&total, line);
1365                 }
1366
1367                 fprintf(ofp, "\nEvents (%s): %'Lu entries, %'lu skips\n",
1368                         get_dev_name(pdi, line, sizeof(line)), pdi->events,
1369                         pdi->skips);
1370         }
1371 }
1372
1373 static int sort_entries(void)
1374 {
1375         struct trace *t;
1376         int nr = 0;
1377
1378         while ((t = trace_list) != NULL) {
1379                 trace_list = t->next;
1380
1381                 if (verify_trace(t->bit))
1382                         continue;
1383                 if (trace_rb_insert(t))
1384                         break;
1385                 nr++;
1386         }
1387
1388         return nr;
1389 }
1390
1391 /*
1392  * struct trace and blktrace allocation cache, we do potentially
1393  * millions of mallocs for these structures while only using at most
1394  * a few thousand at the time
1395  */
1396 static inline void t_free(struct trace *t)
1397 {
1398         t->next = t_alloc_list;
1399         t_alloc_list = t;
1400 }
1401
1402 static inline struct trace *t_alloc(void)
1403 {
1404         struct trace *t = t_alloc_list;
1405
1406         if (t) {
1407                 t_alloc_list = t->next;
1408                 return t;
1409         }
1410
1411         return malloc(sizeof(*t));
1412 }
1413
1414 static inline void bit_free(struct blk_io_trace *bit)
1415 {
1416         /*
1417          * abuse a 64-bit field for a next pointer for the free item
1418          */
1419         bit->time = (__u64) (unsigned long) bit_alloc_list;
1420         bit_alloc_list = (struct blk_io_trace *) bit;
1421 }
1422
1423 static inline struct blk_io_trace *bit_alloc(void)
1424 {
1425         struct blk_io_trace *bit = bit_alloc_list;
1426
1427         if (bit) {
1428                 bit_alloc_list = (struct blk_io_trace *) (unsigned long) \
1429                                  bit->time;
1430                 return bit;
1431         }
1432
1433         return malloc(sizeof(*bit));
1434 }
1435
1436 static void show_entries_rb(void)
1437 {
1438         struct per_dev_info *pdi = NULL;
1439         struct per_cpu_info *pci = NULL;
1440         struct blk_io_trace *bit;
1441         struct rb_node *n;
1442         struct trace *t;
1443
1444         while ((n = rb_first(&rb_sort_root)) != NULL) {
1445
1446                 if (done)
1447                         break;
1448
1449                 t = rb_entry(n, struct trace, rb_node);
1450                 bit = t->bit;
1451
1452                 if (!pdi || pdi->id != bit->device)
1453                         pdi = get_dev_info(bit->device);
1454
1455                 if (!pdi) {
1456                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1457                                 MAJOR(bit->device), MINOR(bit->device));
1458                         break;
1459                 }
1460
1461                 if (bit->cpu > pdi->ncpus) {
1462                         fprintf(stderr, "Unknown CPU ID? (%d, device %d,%d)\n",
1463                                 bit->cpu, MAJOR(bit->device),
1464                                 MINOR(bit->device));
1465                         break;
1466                 }
1467
1468                 /*
1469                  * back off displaying more info if we are out of sync
1470                  * on SMP systems. to prevent stalling on lost events,
1471                  * only allow an event to skip us a few times
1472                  */
1473                 if (bit->sequence != (pdi->last_sequence + 1)
1474                     && pdi->last_sequence != -1) {
1475                         if (t->skipped < 5) {
1476                                 t->skipped++;
1477                                 break;
1478                         } else {
1479                                 fprintf(stderr, "skipping from %lu to %u\n", pdi->last_sequence, bit->sequence);
1480                                 pdi->skips++;
1481                         }
1482                 }
1483
1484                 pdi->last_sequence = bit->sequence;
1485
1486                 if (bit->time >= stopwatch_end || bit->time > last_allowed_time)
1487                         break;
1488
1489                 if (bit->time >= stopwatch_start) {
1490                         check_time(pdi, bit);
1491
1492                         if (!pci || pci->cpu != bit->cpu)
1493                                 pci = get_cpu_info(pdi, bit->cpu);
1494
1495                         dump_trace(bit, pci, pdi);
1496                 }
1497
1498                 rb_erase(&t->rb_node, &rb_sort_root);
1499                 bit_free(bit);
1500                 t_free(t);
1501         }
1502 }
1503
1504 static int read_data(int fd, void *buffer, int bytes, int block)
1505 {
1506         int ret, bytes_left, fl;
1507         void *p;
1508
1509         fl = fcntl(fd, F_GETFL);
1510
1511         if (!block)
1512                 fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1513         else
1514                 fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1515
1516         bytes_left = bytes;
1517         p = buffer;
1518         while (bytes_left > 0) {
1519                 ret = read(fd, p, bytes_left);
1520                 if (!ret)
1521                         return 1;
1522                 else if (ret < 0) {
1523                         if (errno != EAGAIN)
1524                                 perror("read");
1525                         return -1;
1526                 } else {
1527                         p += ret;
1528                         bytes_left -= ret;
1529                 }
1530         }
1531
1532         return 0;
1533 }
1534
1535 static int read_events(int fd)
1536 {
1537         struct per_dev_info *pdi = NULL;
1538         int events = 0;
1539
1540         while (!is_done() && events < rb_batch) {
1541                 struct blk_io_trace *bit;
1542                 struct trace *t;
1543                 int pdu_len;
1544                 __u32 magic;
1545
1546                 bit = bit_alloc();
1547
1548                 if (read_data(fd, bit, sizeof(*bit), !events))
1549                         break;
1550
1551                 magic = be32_to_cpu(bit->magic);
1552                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1553                         fprintf(stderr, "Bad magic %x\n", magic);
1554                         break;
1555                 }
1556
1557                 pdu_len = be16_to_cpu(bit->pdu_len);
1558                 if (pdu_len) {
1559                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1560
1561                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1))
1562                                 break;
1563
1564                         bit = ptr;
1565                 }
1566
1567                 t = t_alloc();
1568                 memset(t, 0, sizeof(*t));
1569                 t->bit = bit;
1570
1571                 trace_to_cpu(bit);
1572                 t->next = trace_list;
1573                 trace_list = t;
1574
1575                 if (genesis_time == 0 || t->bit->time < genesis_time)
1576                         genesis_time = t->bit->time;
1577
1578                 bit->time -= genesis_time;
1579
1580                 if (!pdi || pdi->id != bit->device)
1581                         pdi = get_dev_info(bit->device);
1582
1583                 if (bit->time > pdi->last_read_time)
1584                         pdi->last_read_time = bit->time;
1585
1586                 events++;
1587         }
1588
1589         return events;
1590 }
1591
1592 static int do_file(void)
1593 {
1594         struct per_cpu_info *pci;
1595         struct per_dev_info *pdi;
1596         int i, j, events, events_added;
1597
1598         /*
1599          * first prepare all files for reading
1600          */
1601         for (i = 0; i < ndevices; i++) {
1602                 pdi = &devices[i];
1603                 pdi->nfiles = 0;
1604                 pdi->last_sequence = -1;
1605
1606                 for (j = 0;; j++) {
1607                         struct stat st;
1608
1609                         pci = get_cpu_info(pdi, j);
1610                         pci->cpu = j;
1611                         pci->fd = -1;
1612
1613                         snprintf(pci->fname, sizeof(pci->fname)-1,
1614                                  "%s.blktrace.%d", pdi->name, pci->cpu);
1615                         if (stat(pci->fname, &st) < 0)
1616                                 break;
1617                         if (st.st_size) {
1618                                 pci->fd = open(pci->fname, O_RDONLY);
1619                                 if (pci->fd < 0) {
1620                                         perror(pci->fname);
1621                                         continue;
1622                                 }
1623                         }
1624
1625                         printf("Input file %s added\n", pci->fname);
1626                         pdi->nfiles++;
1627                 }
1628         }
1629
1630         /*
1631          * now loop over the files reading in the data
1632          */
1633         do {
1634                 events_added = 0;
1635                 last_allowed_time = -1ULL;
1636
1637                 for (i = 0; i < ndevices; i++) {
1638                         pdi = &devices[i];
1639
1640                         for (j = 0; j < pdi->nfiles; j++) {
1641
1642                                 pci = get_cpu_info(pdi, j);
1643
1644                                 if (pci->fd == -1)
1645                                         continue;
1646
1647                                 events = read_events(pci->fd);
1648                                 if (!events) {
1649                                         close(pci->fd);
1650                                         pci->fd = -1;
1651                                         continue;
1652                                 }
1653
1654                                 if (pdi->last_read_time < last_allowed_time)
1655                                         last_allowed_time = pdi->last_read_time;
1656
1657                                 events_added += events;
1658                         }
1659                 }
1660
1661                 if (sort_entries() == -1)
1662                         break;
1663
1664                 show_entries_rb();
1665
1666         } while (events_added);
1667
1668         return 0;
1669 }
1670
1671 static int do_stdin(void)
1672 {
1673         int fd;
1674
1675         fd = dup(STDIN_FILENO);
1676         do {
1677                 int events;
1678
1679                 events = read_events(fd);
1680                 if (!events)
1681                         break;
1682         
1683                 if (sort_entries() == -1)
1684                         break;
1685
1686                 show_entries_rb();
1687         } while (1);
1688
1689         close(fd);
1690         return 0;
1691 }
1692
1693 static void flush_output(void)
1694 {
1695         fflush(ofp);
1696 }
1697
1698 static void handle_sigint(int sig)
1699 {
1700         done = 1;
1701         flush_output();
1702 }
1703
1704 /*
1705  * Extract start and duration times from a string, allowing
1706  * us to specify a time interval of interest within a trace.
1707  * Format: "duration" (start is zero) or "start:duration".
1708  */
1709 static int find_stopwatch_interval(char *string)
1710 {
1711         double value;
1712         char *sp;
1713
1714         value = strtod(string, &sp);
1715         if (sp == string) {
1716                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
1717                 return 1;
1718         }
1719         if (*sp == ':') {
1720                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
1721                 string = sp + 1;
1722                 value = strtod(string, &sp);
1723                 if (sp == string || *sp != '\0') {
1724                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
1725                                 string);
1726                         return 1;
1727                 }
1728         } else if (*sp != '\0') {
1729                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
1730                 return 1;
1731         }
1732         stopwatch_end = DOUBLE_TO_NANO_ULL(value);
1733         if (stopwatch_end <= stopwatch_start) {
1734                 fprintf(stderr, "Invalid stopwatch interval: %Lu -> %Lu\n",
1735                         stopwatch_start, stopwatch_end);
1736                 return 1;
1737         }
1738
1739         return 0;
1740 }
1741
1742 static char usage_str[] = \
1743         "[ -i <input name> ] [-o <output name> [ -s ] [ -t ] [ -q ]\n" \
1744         "[ -w start:stop ] [ -f output format ] [ -F format spec ] [ -v] \n\n" \
1745         "\t-i Input file containing trace data, or '-' for stdin\n" \
1746         "\t-o Output file. If not given, output is stdout\n" \
1747         "\t-b stdin read batching\n" \
1748         "\t-s Show per-program io statistics\n" \
1749         "\t-t Track individual ios. Will tell you the time a request took\n" \
1750         "\t   to get queued, to get dispatched, and to get completed\n" \
1751         "\t-q Quiet. Don't display any stats at the end of the trace\n" \
1752         "\t-w Only parse data between the given time interval in seconds.\n" \
1753         "\t   If 'start' isn't given, blkparse defaults the start time to 0\n" \
1754         "\t -f Output format. Customize the output format. The format field\n" \
1755         "\t    identifies can be found in the documentation\n" \
1756         "\t-F Format specification. Can be found in the documentation\n" \
1757         "\t-v Print program version info\n\n";
1758
1759 static void usage(char *prog)
1760 {
1761         fprintf(stderr, "Usage: %s %s %s", prog, blkparse_version, usage_str);
1762 }
1763
1764 int main(int argc, char *argv[])
1765 {
1766         char *ofp_buffer;
1767         int c, ret, mode;
1768         int per_device_and_cpu_stats = 1;
1769
1770         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
1771                 switch (c) {
1772                 case 'i':
1773                         if (!strcmp(optarg, "-") && !pipeline)
1774                                 pipeline = 1;
1775                         else if (resize_devices(optarg) != 0)
1776                                 return 1;
1777                         break;
1778                 case 'o':
1779                         output_name = optarg;
1780                         break;
1781                 case 'b':
1782                         rb_batch = atoi(optarg);
1783                         if (rb_batch <= 0)
1784                                 rb_batch = RB_BATCH_DEFAULT;
1785                         break;
1786                 case 's':
1787                         per_process_stats = 1;
1788                         break;
1789                 case 't':
1790                         track_ios = 1;
1791                         break;
1792                 case 'q':
1793                         per_device_and_cpu_stats = 0;
1794                         break;
1795                 case 'w':
1796                         if (find_stopwatch_interval(optarg) != 0)
1797                                 return 1;
1798                         break;
1799                 case 'f':
1800                         set_all_format_specs(optarg);
1801                         break;
1802                 case 'F':
1803                         if (add_format_spec(optarg) != 0)
1804                                 return 1;
1805                         break;
1806                 case 'v':
1807                         printf("%s version %s\n", argv[0], blkparse_version);
1808                         return 0;
1809                 default:
1810                         usage(argv[0]);
1811                         return 1;
1812                 }
1813         }
1814
1815         while (optind < argc) {
1816                 if (!strcmp(argv[optind], "-") && !pipeline)
1817                         pipeline = 1;
1818                 else if (resize_devices(argv[optind]) != 0)
1819                         return 1;
1820                 optind++;
1821         }
1822
1823         if (!pipeline && !ndevices) {
1824                 usage(argv[0]);
1825                 return 1;
1826         }
1827
1828         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
1829         memset(&rb_track_root, 0, sizeof(rb_track_root));
1830
1831         signal(SIGINT, handle_sigint);
1832         signal(SIGHUP, handle_sigint);
1833         signal(SIGTERM, handle_sigint);
1834
1835         setlocale(LC_NUMERIC, "en_US");
1836
1837         if (!output_name) {
1838                 ofp = fdopen(STDOUT_FILENO, "w");
1839                 mode = _IOLBF;
1840         } else {
1841                 char ofname[128];
1842
1843                 snprintf(ofname, sizeof(ofname) - 1, "%s", output_name);
1844                 ofp = fopen(ofname, "w");
1845                 mode = _IOFBF;
1846         }
1847
1848         if (!ofp) {
1849                 perror("fopen");
1850                 return 1;
1851         }
1852
1853         ofp_buffer = malloc(4096);      
1854         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
1855                 perror("setvbuf");
1856                 return 1;
1857         }
1858
1859         if (pipeline)
1860                 ret = do_stdin();
1861         else
1862                 ret = do_file();
1863
1864         if (per_process_stats)
1865                 show_process_stats();
1866
1867         if (per_device_and_cpu_stats)
1868                 show_device_and_cpu_stats();
1869
1870         flush_output();
1871         return ret;
1872 }