[PATCH] blkparse: fix frontmerge tracking
[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
34 #include "blktrace.h"
35 #include "rbtree.h"
36
37 #define SECONDS(x)              ((unsigned long long)(x) / 1000000000)
38 #define NANO_SECONDS(x)         ((unsigned long long)(x) % 1000000000)
39 #define DOUBLE_TO_NANO_ULL(d)   ((unsigned long long)((d) * 1000000000))
40
41 #define MINORBITS       20
42 #define MINORMASK       ((1U << MINORBITS) - 1)
43 #define MAJOR(dev)      ((unsigned int) ((dev) >> MINORBITS))
44 #define MINOR(dev)      ((unsigned int) ((dev) & MINORMASK))
45
46 #define min(a, b)       ((a) < (b) ? (a) : (b))
47
48 struct io_stats {
49         unsigned long qreads, qwrites, creads, cwrites, mreads, mwrites;
50         unsigned long ireads, iwrites;
51         unsigned long long qread_kb, qwrite_kb, cread_kb, cwrite_kb;
52         unsigned long long iread_kb, iwrite_kb;
53         unsigned long io_unplugs, timer_unplugs;
54 };
55
56 struct per_cpu_info {
57         int cpu;
58         int nelems;
59
60         int fd;
61         char fname[128];
62
63         struct io_stats io_stats;
64 };
65
66 struct per_dev_info {
67         dev_t id;
68         char *name;
69
70         int backwards;
71         unsigned long long events;
72         unsigned long long last_reported_time;
73         struct io_stats io_stats;
74         unsigned long last_sequence;
75
76         int ncpus;
77         struct per_cpu_info *cpus;
78 };
79
80 struct per_process_info {
81         char name[16];
82         __u32 pid;
83         struct io_stats io_stats;
84         struct per_process_info *hash_next, *list_next;
85
86         /*
87          * individual io stats
88          */
89         unsigned long long longest_allocation_wait[2];
90         unsigned long long longest_dispatch_wait[2];
91         unsigned long long longest_completion_wait[2];
92 };
93
94 #define PPI_HASH_SHIFT  (8)
95 static struct per_process_info *ppi_hash[1 << PPI_HASH_SHIFT];
96 static struct per_process_info *ppi_list;
97
98 #define S_OPTS  "i:o:b:stqw:"
99 static struct option l_opts[] = {
100         {
101                 .name = "input",
102                 .has_arg = 1,
103                 .flag = NULL,
104                 .val = 'i'
105         },
106         {
107                 .name = "output",
108                 .has_arg = 1,
109                 .flag = NULL,
110                 .val = 'o'
111         },
112         {
113                 .name = "batch",
114                 .has_arg = 1,
115                 .flag = NULL,
116                 .val = 'b'
117         },
118         {
119                 .name = "per program stats",
120                 .has_arg = 0,
121                 .flag = NULL,
122                 .val = 's'
123         },
124         {
125                 .name = "track ios",
126                 .has_arg = 0,
127                 .flag = NULL,
128                 .val = 't'
129         },
130         {
131                 .name = "quiet",
132                 .has_arg = 0,
133                 .flag = NULL,
134                 .val = 'q'
135         },
136         {
137                 .name = "stopwatch",
138                 .has_arg = 1,
139                 .flag = NULL,
140                 .val = 'w'
141         },
142         {
143                 .name = NULL,
144                 .has_arg = 0,
145                 .flag = NULL,
146                 .val = 0
147         }
148 };
149
150 /*
151  * for sorting the displayed output
152  */
153 struct trace {
154         struct blk_io_trace *bit;
155         struct rb_node rb_node;
156         struct trace *next;
157         int skipped;
158 };
159
160 static struct rb_root rb_sort_root;
161 static struct rb_root rb_track_root;
162
163 static struct trace *trace_list;
164
165 /*
166  * for tracking individual ios
167  */
168 struct io_track {
169         struct rb_node rb_node;
170
171         dev_t device;
172         __u64 sector;
173         __u32 pid;
174         unsigned long long allocation_time;
175         unsigned long long queue_time;
176         unsigned long long dispatch_time;
177         unsigned long long completion_time;
178 };
179
180 static int ndevices;
181 static struct per_dev_info *devices;
182 static char *get_dev_name(struct per_dev_info *, char *, int);
183
184 static FILE *ofp;
185 static char *output_name;
186
187 static unsigned long long genesis_time;
188 static unsigned long long stopwatch_start;      /* start from zero by default */
189 static unsigned long long stopwatch_end = ULONG_LONG_MAX;       /* "infinity" */
190
191 static int per_process_stats;
192 static int track_ios;
193
194 #define RB_BATCH_DEFAULT        (1024)
195 static int rb_batch = RB_BATCH_DEFAULT;
196
197 static int pipeline;
198
199 #define is_done()       (*(volatile int *)(&done))
200 static volatile int done;
201
202 static inline unsigned long hash_long(unsigned long val)
203 {
204 #if __WORDSIZE == 32
205         val *= 0x9e370001UL;
206 #elif __WORDSIZE == 64
207         val *= 0x9e37fffffffc0001UL;
208 #else
209 #error unknown word size
210 #endif
211
212         return val >> (__WORDSIZE - PPI_HASH_SHIFT);
213 }
214
215 static inline void add_process_to_hash(struct per_process_info *ppi)
216 {
217         const int hash_idx = hash_long(ppi->pid);
218
219         ppi->hash_next = ppi_hash[hash_idx];
220         ppi_hash[hash_idx] = ppi;
221 }
222
223 static inline void add_process_to_list(struct per_process_info *ppi)
224 {
225         ppi->list_next = ppi_list;
226         ppi_list = ppi;
227 }
228
229 static struct per_process_info *find_process_by_pid(__u32 pid)
230 {
231         const int hash_idx = hash_long(pid);
232         struct per_process_info *ppi;
233
234         ppi = ppi_hash[hash_idx];
235         while (ppi) {
236                 if (ppi->pid == pid)
237                         return ppi;
238
239                 ppi = ppi->hash_next;
240         }
241
242         return NULL;
243 }
244
245 static inline int trace_rb_insert(struct trace *t)
246 {
247         struct rb_node **p = &rb_sort_root.rb_node;
248         struct rb_node *parent = NULL;
249         struct trace *__t;
250
251         if (genesis_time == 0 || t->bit->time < genesis_time)
252                 genesis_time = t->bit->time;
253
254         while (*p) {
255                 parent = *p;
256                 __t = rb_entry(parent, struct trace, rb_node);
257
258                 if (t->bit->time < __t->bit->time)
259                         p = &(*p)->rb_left;
260                 else if (t->bit->time > __t->bit->time)
261                         p = &(*p)->rb_right;
262                 else if (t->bit->device < __t->bit->device)
263                         p = &(*p)->rb_left;
264                 else if (t->bit->device > __t->bit->device)
265                         p = &(*p)->rb_right;
266                 else if (t->bit->sequence < __t->bit->sequence)
267                         p = &(*p)->rb_left;
268                 else if (t->bit->sequence > __t->bit->sequence)
269                         p = &(*p)->rb_right;
270                 else if (t->bit->device == __t->bit->device) {
271                         fprintf(stderr,
272                                 "sequence alias (%d) on device %d,%d!\n",
273                                 t->bit->sequence,
274                                 MAJOR(t->bit->device), MINOR(t->bit->device));
275                         return 1;
276                 }
277         }
278
279         rb_link_node(&t->rb_node, parent, p);
280         rb_insert_color(&t->rb_node, &rb_sort_root);
281         return 0;
282 }
283
284 static inline int track_rb_insert(struct io_track *iot)
285 {
286         struct rb_node **p = &rb_track_root.rb_node;
287         struct rb_node *parent = NULL;
288         struct io_track *__iot;
289
290         while (*p) {
291                 parent = *p;
292
293                 __iot = rb_entry(parent, struct io_track, rb_node);
294
295                 if (iot->device < __iot->device)
296                         p = &(*p)->rb_left;
297                 else if (iot->device > __iot->device)
298                         p = &(*p)->rb_right;
299                 else if (iot->sector < __iot->sector)
300                         p = &(*p)->rb_left;
301                 else if (iot->sector > __iot->sector)
302                         p = &(*p)->rb_right;
303                 else {
304                         fprintf(stderr,
305                                 "sector alias (%llu) on device %d,%d!\n",
306                                 iot->sector,
307                                 MAJOR(iot->device), MINOR(iot->device));
308                         return 1;
309                 }
310         }
311
312         rb_link_node(&iot->rb_node, parent, p);
313         rb_insert_color(&iot->rb_node, &rb_track_root);
314         return 0;
315 }
316
317 static struct io_track *__find_track(dev_t device, __u64 sector)
318 {
319         struct rb_node **p = &rb_track_root.rb_node;
320         struct rb_node *parent = NULL;
321         struct io_track *__iot;
322
323         while (*p) {
324                 parent = *p;
325                 
326                 __iot = rb_entry(parent, struct io_track, rb_node);
327
328                 if (device < __iot->device)
329                         p = &(*p)->rb_left;
330                 else if (device > __iot->device)
331                         p = &(*p)->rb_right;
332                 else if (sector < __iot->sector)
333                         p = &(*p)->rb_left;
334                 else if (sector > __iot->sector)
335                         p = &(*p)->rb_right;
336                 else
337                         return __iot;
338         }
339
340         return NULL;
341 }
342
343 static struct io_track *find_track(__u32 pid, dev_t device, __u64 sector)
344 {
345         struct io_track *iot;
346
347         iot = __find_track(device, sector);
348         if (!iot) {
349                 iot = malloc(sizeof(*iot));
350                 iot->pid = pid;
351                 iot->device = device;
352                 iot->sector = sector;
353                 track_rb_insert(iot);
354         }
355
356         return iot;
357 }
358
359 static void log_track_frontmerge(struct blk_io_trace *t)
360 {
361         struct io_track *iot;
362
363         if (!track_ios)
364                 return;
365
366         /*
367          * this can happen if we lose events, so don't print an error
368          */
369         iot = __find_track(t->device, t->sector + (t->bytes >> 9));
370         if (!iot) {
371                 fprintf(stderr, "failed to find mergeable event\n");
372                 return;
373         }
374
375         rb_erase(&iot->rb_node, &rb_track_root);
376         iot->sector -= t->bytes >> 9;
377         track_rb_insert(iot);
378 }
379
380 static void log_track_getrq(struct blk_io_trace *t)
381 {
382         struct io_track *iot;
383
384         if (!track_ios)
385                 return;
386
387         iot = find_track(t->pid, t->device, t->sector);
388         iot->allocation_time = t->time;
389 }
390
391
392 /*
393  * return time between rq allocation and queue
394  */
395 static unsigned long long log_track_queue(struct blk_io_trace *t)
396 {
397         unsigned long long elapsed;
398         struct io_track *iot;
399
400         if (!track_ios)
401                 return -1;
402
403         iot = find_track(t->pid, t->device, t->sector);
404         iot->queue_time = t->time;
405         elapsed = iot->queue_time - iot->allocation_time;
406
407         if (per_process_stats) {
408                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
409                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
410
411                 if (ppi && elapsed > ppi->longest_allocation_wait[w])
412                         ppi->longest_allocation_wait[w] = elapsed;
413         }
414
415         return elapsed;
416 }
417
418 /*
419  * return time between queue and issue
420  */
421 static unsigned long long log_track_issue(struct blk_io_trace *t)
422 {
423         unsigned long long elapsed;
424         struct io_track *iot;
425
426         if (!track_ios)
427                 return -1;
428         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
429                 return -1;
430
431         /*
432          * this can happen if we lose events, so don't print an error
433          */
434         iot = __find_track(t->device, t->sector);
435         if (!iot) {
436                 fprintf(stderr, "failed to find issue event\n");
437                 return -1;
438         }
439
440         iot->dispatch_time = t->time;
441         elapsed = iot->dispatch_time - iot->queue_time;
442
443         if (per_process_stats) {
444                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
445                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
446
447                 if (ppi && elapsed > ppi->longest_dispatch_wait[w])
448                         ppi->longest_dispatch_wait[w] = elapsed;
449         }
450
451         return elapsed;
452 }
453
454 /*
455  * return time between dispatch and complete
456  */
457 static unsigned long long log_track_complete(struct blk_io_trace *t)
458 {
459         unsigned long long elapsed;
460         struct io_track *iot;
461
462         if (!track_ios)
463                 return -1;
464         if ((t->action & BLK_TC_ACT(BLK_TC_FS)) == 0)
465                 return -1;
466
467         iot = __find_track(t->device, t->sector);
468         if (!iot) {
469                 fprintf(stderr, "failed to find complete event\n");
470                 return -1;
471         }
472
473         iot->completion_time = t->time;
474         elapsed = iot->completion_time - iot->dispatch_time;
475
476         if (per_process_stats) {
477                 struct per_process_info *ppi = find_process_by_pid(iot->pid);
478                 int w = (t->action & BLK_TC_ACT(BLK_TC_WRITE)) != 0;
479
480                 if (ppi && elapsed > ppi->longest_completion_wait[w])
481                         ppi->longest_completion_wait[w] = elapsed;
482         }
483
484         /*
485          * kill the trace, we don't need it after completion
486          */
487         rb_erase(&iot->rb_node, &rb_track_root);
488         free(iot);
489
490         return elapsed;
491 }
492
493
494 static struct io_stats *find_process_io_stats(__u32 pid, char *name)
495 {
496         struct per_process_info *ppi = find_process_by_pid(pid);
497
498         if (!ppi) {
499                 ppi = malloc(sizeof(*ppi));
500                 memset(ppi, 0, sizeof(*ppi));
501                 strncpy(ppi->name, name, sizeof(ppi->name));
502                 ppi->pid = pid;
503                 add_process_to_hash(ppi);
504                 add_process_to_list(ppi);
505         }
506
507         return &ppi->io_stats;
508 }
509
510
511 static void resize_cpu_info(struct per_dev_info *pdi, int cpu)
512 {
513         struct per_cpu_info *cpus = pdi->cpus;
514         int ncpus = pdi->ncpus;
515         int new_count = cpu + 1;
516         int new_space, size;
517         char *new_start;
518
519         size = new_count * sizeof(struct per_cpu_info);
520         cpus = realloc(cpus, size);
521         if (!cpus) {
522                 char name[20];
523                 fprintf(stderr, "Out of memory, CPU info for device %s (%d)\n",
524                         get_dev_name(pdi, name, sizeof(name)), size);
525                 exit(1);
526         }
527
528         new_start = (char *)cpus + (ncpus * sizeof(struct per_cpu_info));
529         new_space = (new_count - ncpus) * sizeof(struct per_cpu_info);
530         memset(new_start, 0, new_space);
531
532         pdi->ncpus = new_count;
533         pdi->cpus = cpus;
534 }
535
536 static struct per_cpu_info *get_cpu_info(struct per_dev_info *pdi, int cpu)
537 {
538         struct per_cpu_info *pci;
539
540         if (cpu >= pdi->ncpus)
541                 resize_cpu_info(pdi, cpu);
542
543         pci = &pdi->cpus[cpu];
544         pci->cpu = cpu;
545         return pci;
546 }
547
548
549 static int resize_devices(char *name)
550 {
551         int size = (ndevices + 1) * sizeof(struct per_dev_info);
552
553         devices = realloc(devices, size);
554         if (!devices) {
555                 fprintf(stderr, "Out of memory, device %s (%d)\n", name, size);
556                 return 1;
557         }
558         memset(&devices[ndevices], 0, sizeof(struct per_dev_info));
559         devices[ndevices].name = name;
560         ndevices++;
561         return 0;
562 }
563
564 static struct per_dev_info *get_dev_info(dev_t id)
565 {
566         struct per_dev_info *pdi;
567         int i;
568
569         for (i = 0; i < ndevices; i++)
570                 if (devices[i].id == id)
571                         return &devices[i];
572
573         if (resize_devices(NULL) != 0)
574                 return NULL;
575
576         pdi = &devices[ndevices - 1];
577         pdi->id = id;
578         return pdi;
579 }
580
581 static char *get_dev_name(struct per_dev_info *pdi, char *buffer, int size)
582 {
583         if (pdi->name)
584                 snprintf(buffer, size, "%s", pdi->name);
585         else
586                 snprintf(buffer, size, "%d,%d", MAJOR(pdi->id), MINOR(pdi->id));
587         return buffer;
588 }
589
590 static void check_time(struct per_dev_info *pdi, struct blk_io_trace *bit)
591 {
592         unsigned long long this = bit->time;
593         unsigned long long last = pdi->last_reported_time;
594
595         pdi->backwards = (this < last) ? 'B' : ' ';
596         pdi->last_reported_time = this;
597 }
598
599 static inline void __account_m(struct io_stats *ios, struct blk_io_trace *t,
600                                int rw)
601 {
602         if (rw) {
603                 ios->mwrites++;
604                 ios->qwrite_kb += t->bytes >> 10;
605         } else {
606                 ios->mreads++;
607                 ios->qread_kb += t->bytes >> 10;
608         }
609 }
610
611 static inline void account_m(struct blk_io_trace *t, struct per_cpu_info *pci,
612                              int rw)
613 {
614         __account_m(&pci->io_stats, t, rw);
615
616         if (per_process_stats) {
617                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
618
619                 __account_m(ios, t, rw);
620         }
621 }
622
623 static inline void __account_q(struct io_stats *ios, struct blk_io_trace *t,
624                                int rw)
625 {
626         if (rw) {
627                 ios->qwrites++;
628                 ios->qwrite_kb += t->bytes >> 10;
629         } else {
630                 ios->qreads++;
631                 ios->qread_kb += t->bytes >> 10;
632         }
633 }
634
635 static inline void account_q(struct blk_io_trace *t, struct per_cpu_info *pci,
636                              int rw)
637 {
638         __account_q(&pci->io_stats, t, rw);
639
640         if (per_process_stats) {
641                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
642
643                 __account_q(ios, t, rw);
644         }
645 }
646
647 static inline void __account_c(struct io_stats *ios, int rw, unsigned int bytes)
648 {
649         if (rw) {
650                 ios->cwrites++;
651                 ios->cwrite_kb += bytes >> 10;
652         } else {
653                 ios->creads++;
654                 ios->cread_kb += bytes >> 10;
655         }
656 }
657
658 static inline void account_c(struct blk_io_trace *t, struct per_cpu_info *pci,
659                              int rw, int bytes)
660 {
661         __account_c(&pci->io_stats, rw, bytes);
662
663         if (per_process_stats) {
664                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
665
666                 __account_c(ios, rw, bytes);
667         }
668 }
669
670 static inline void __account_i(struct io_stats *ios, int rw, unsigned int bytes)
671 {
672         if (rw) {
673                 ios->iwrites++;
674                 ios->iwrite_kb += bytes >> 10;
675         } else {
676                 ios->ireads++;
677                 ios->iread_kb += bytes >> 10;
678         }
679 }
680
681 static inline void account_i(struct blk_io_trace *t, struct per_cpu_info *pci,
682                              int rw)
683 {
684         __account_i(&pci->io_stats, rw, t->bytes);
685
686         if (per_process_stats) {
687                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
688
689                 __account_i(ios, rw, t->bytes);
690         }
691 }
692
693 static inline void __account_unplug(struct io_stats *ios, int timer)
694 {
695         if (timer)
696                 ios->timer_unplugs++;
697         else
698                 ios->io_unplugs++;
699 }
700
701 static inline void account_unplug(struct blk_io_trace *t,
702                                   struct per_cpu_info *pci, int timer)
703 {
704         __account_unplug(&pci->io_stats, timer);
705
706         if (per_process_stats) {
707                 struct io_stats *ios = find_process_io_stats(t->pid, t->comm);
708
709                 __account_unplug(ios, timer);
710         }
711 }
712
713 static void output(struct per_cpu_info *pci, char *s)
714 {
715         fprintf(ofp, "%s", s);
716 }
717
718 static char hstring[256];
719 static char tstring[256];
720
721 static inline char *setup_header(struct per_cpu_info *pci,
722                                  struct blk_io_trace *t, char *act)
723 {
724         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
725         int b = t->action & BLK_TC_ACT(BLK_TC_BARRIER);
726         int s = t->action & BLK_TC_ACT(BLK_TC_SYNC);
727         char rwbs[4];
728         int i = 0;
729
730         if (w)
731                 rwbs[i++] = 'W';
732         else
733                 rwbs[i++] = 'R';
734         if (b)
735                 rwbs[i++] = 'B';
736         if (s)
737                 rwbs[i++] = 'S';
738
739         rwbs[i] = '\0';
740
741         sprintf(hstring, "%3d,%-3d %2d %8ld %5Lu.%09Lu %5u %2s %3s",
742                 MAJOR(t->device), MINOR(t->device), pci->cpu,
743                 (unsigned long)t->sequence, SECONDS(t->time),
744                 NANO_SECONDS(t->time), t->pid, act, rwbs);
745
746         return hstring;
747 }
748
749 static void log_complete(struct per_cpu_info *pci, struct blk_io_trace *t,
750                          char *act)
751 {
752         unsigned long long elapsed = log_track_complete(t);
753
754         if (elapsed != -1ULL) {
755                 unsigned long usec = elapsed / 1000;
756
757                 sprintf(tstring,"%s %Lu + %u (%8lu) [%d]\n",
758                         setup_header(pci, t, act),
759                         (unsigned long long)t->sector, t->bytes >> 9,
760                         usec, t->error);
761         } else {
762                 sprintf(tstring,"%s %Lu + %u [%d]\n", setup_header(pci, t, act),
763                         (unsigned long long)t->sector, t->bytes >> 9, t->error);
764         }
765         
766         output(pci, tstring);
767 }
768
769 static void log_queue(struct per_cpu_info *pci, struct blk_io_trace *t,
770                       char *act)
771 {
772         unsigned long long elapsed = log_track_queue(t);
773
774         if (elapsed != -1ULL) {
775                 unsigned long usec = elapsed / 1000;
776
777                 sprintf(tstring,"%s %Lu + %u (%8lu) [%s]\n",
778                         setup_header(pci, t, act),
779                         (unsigned long long)t->sector, t->bytes >> 9,
780                         usec, t->comm);
781         } else {
782                 sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
783                         (unsigned long long)t->sector, t->bytes >> 9, t->comm);
784         }
785         output(pci, tstring);
786 }
787
788 static void log_issue(struct per_cpu_info *pci, struct blk_io_trace *t,
789                       char *act)
790 {
791         unsigned long long elapsed = log_track_issue(t);
792
793         if (elapsed != -1ULL) {
794                 double usec = (double) elapsed / 1000;
795
796                 sprintf(tstring,"%s %Lu + %u (%8.2f) [%s]\n",
797                         setup_header(pci, t, act),
798                         (unsigned long long)t->sector, t->bytes >> 9,
799                         usec, t->comm);
800         } else {
801                 sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
802                         (unsigned long long)t->sector, t->bytes >> 9, t->comm);
803         }
804
805         output(pci, tstring);
806 }
807
808 static void log_merge(struct per_cpu_info *pci, struct blk_io_trace *t,
809                       char *act)
810 {
811         if (act[0] == 'F')
812                 log_track_frontmerge(t);
813
814         sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
815                 (unsigned long long)t->sector, t->bytes >> 9, t->comm);
816         output(pci, tstring);
817 }
818
819 static void log_action(struct per_cpu_info *pci, struct blk_io_trace *t,
820                         char *act)
821 {
822         sprintf(tstring,"%s [%s]\n", setup_header(pci, t, act), t->comm);
823         output(pci, tstring);
824 }
825
826 static void log_generic(struct per_cpu_info *pci, struct blk_io_trace *t,
827                         char *act)
828 {
829         sprintf(tstring,"%s %Lu + %u [%s]\n", setup_header(pci, t, act),
830                 (unsigned long long)t->sector, t->bytes >> 9, t->comm);
831         output(pci, tstring);
832 }
833
834 static int log_unplug(struct per_cpu_info *pci, struct blk_io_trace *t,
835                       char *act)
836 {
837         __u64 *depth;
838         int len;
839
840         len = sprintf(tstring,"%s [%s] ", setup_header(pci, t, act), t->comm);
841         depth = (__u64 *) ((char *) t + sizeof(*t));
842         sprintf(tstring + len, "%u\n", (unsigned int) be64_to_cpu(*depth));
843         output(pci, tstring);
844
845         return 0;
846 }
847
848 static int log_pc(struct per_cpu_info *pci, struct blk_io_trace *t, char *act)
849 {
850         unsigned char *buf;
851         int i;
852
853         sprintf(tstring,"%s ", setup_header(pci, t, act));
854         output(pci, tstring);
855
856         buf = (unsigned char *) t + sizeof(*t);
857         for (i = 0; i < t->pdu_len; i++) {
858                 sprintf(tstring,"%02x ", buf[i]);
859                 output(pci, tstring);
860         }
861
862         if (act[0] == 'C') {
863                 sprintf(tstring,"[%d]\n", t->error);
864                 output(pci, tstring);
865         } else {
866                 sprintf(tstring,"[%s]\n", t->comm);
867                 output(pci, tstring);
868         }
869         return 0;
870 }
871
872 static int dump_trace_pc(struct blk_io_trace *t, struct per_cpu_info *pci)
873 {
874         int ret = 0;
875
876         switch (t->action & 0xffff) {
877                 case __BLK_TA_QUEUE:
878                         log_generic(pci, t, "Q");
879                         break;
880                 case __BLK_TA_GETRQ:
881                         log_generic(pci, t, "G");
882                         break;
883                 case __BLK_TA_SLEEPRQ:
884                         log_generic(pci, t, "S");
885                         break;
886                 case __BLK_TA_REQUEUE:
887                         log_generic(pci, t, "R");
888                         break;
889                 case __BLK_TA_ISSUE:
890                         ret = log_pc(pci, t, "D");
891                         break;
892                 case __BLK_TA_COMPLETE:
893                         log_pc(pci, t, "C");
894                         break;
895                 default:
896                         fprintf(stderr, "Bad pc action %x\n", t->action);
897                         ret = 1;
898                         break;
899         }
900         
901         return ret;
902 }
903
904 static void dump_trace_fs(struct blk_io_trace *t, struct per_cpu_info *pci)
905 {
906         int w = t->action & BLK_TC_ACT(BLK_TC_WRITE);
907         int act = t->action & 0xffff;
908
909         switch (act) {
910                 case __BLK_TA_QUEUE:
911                         account_q(t, pci, w);
912                         log_queue(pci, t, "Q");
913                         break;
914                 case __BLK_TA_BACKMERGE:
915                         account_m(t, pci, w);
916                         log_merge(pci, t, "M");
917                         break;
918                 case __BLK_TA_FRONTMERGE:
919                         account_m(t, pci, w);
920                         log_merge(pci, t, "F");
921                         break;
922                 case __BLK_TA_GETRQ:
923                         log_track_getrq(t);
924                         log_generic(pci, t, "G");
925                         break;
926                 case __BLK_TA_SLEEPRQ:
927                         log_generic(pci, t, "S");
928                         break;
929                 case __BLK_TA_REQUEUE:
930                         account_c(t, pci, w, -t->bytes);
931                         log_queue(pci, t, "R");
932                         break;
933                 case __BLK_TA_ISSUE:
934                         account_i(t, pci, w);
935                         log_issue(pci, t, "D");
936                         break;
937                 case __BLK_TA_COMPLETE:
938                         account_c(t, pci, w, t->bytes);
939                         log_complete(pci, t, "C");
940                         break;
941                 case __BLK_TA_PLUG:
942                         log_action(pci, t, "P");
943                         break;
944                 case __BLK_TA_UNPLUG_IO:
945                         account_unplug(t, pci, 0);
946                         log_unplug(pci, t, "U");
947                         break;
948                 case __BLK_TA_UNPLUG_TIMER:
949                         account_unplug(t, pci, 1);
950                         log_unplug(pci, t, "UT");
951                         break;
952                 default:
953                         fprintf(stderr, "Bad fs action %x\n", t->action);
954                         break;
955         }
956 }
957
958 static int dump_trace(struct blk_io_trace *t, struct per_cpu_info *pci,
959                         struct per_dev_info *pdi)
960 {
961         int ret = 0;
962
963         if (t->action & BLK_TC_ACT(BLK_TC_PC))
964                 ret = dump_trace_pc(t, pci);
965         else
966                 dump_trace_fs(t, pci);
967
968         pdi->events++;
969         return ret;
970 }
971
972 static void dump_io_stats(struct io_stats *ios, char *msg)
973 {
974         fprintf(ofp, "%s\n", msg);
975
976         fprintf(ofp, " Reads Queued:    %'8lu, %'8LuKiB\t", ios->qreads, ios->qread_kb);
977         fprintf(ofp, " Writes Queued:    %'8lu, %'8LuKiB\n", ios->qwrites,ios->qwrite_kb);
978
979         fprintf(ofp, " Read Dispatches: %'8lu, %'8LuKiB\t", ios->ireads, ios->iread_kb);
980         fprintf(ofp, " Write Dispatches: %'8lu, %'8LuKiB\n", ios->iwrites,ios->iwrite_kb);
981         fprintf(ofp, " Reads Completed: %'8lu, %'8LuKiB\t", ios->creads, ios->cread_kb);
982         fprintf(ofp, " Writes Completed: %'8lu, %'8LuKiB\n", ios->cwrites,ios->cwrite_kb);
983         fprintf(ofp, " Read Merges:     %'8lu%8c\t", ios->mreads, ' ');
984         fprintf(ofp, " Write Merges:     %'8lu\n", ios->mwrites);
985         fprintf(ofp, " IO unplugs:      %'8lu%8c\t", ios->io_unplugs, ' ');
986         fprintf(ofp, " Timer unplugs:    %'8lu\n", ios->timer_unplugs);
987 }
988
989 static void dump_wait_stats(struct per_process_info *ppi)
990 {
991         unsigned long rawait = ppi->longest_allocation_wait[0] / 1000;
992         unsigned long rdwait = ppi->longest_dispatch_wait[0] / 1000;
993         unsigned long rcwait = ppi->longest_completion_wait[0] / 1000;
994         unsigned long wawait = ppi->longest_allocation_wait[1] / 1000;
995         unsigned long wdwait = ppi->longest_dispatch_wait[1] / 1000;
996         unsigned long wcwait = ppi->longest_completion_wait[1] / 1000;
997
998         fprintf(ofp, " Allocation wait: %'8lu%8c\t", rawait, ' ');
999         fprintf(ofp, " Allocation wait:  %'8lu\n", wawait);
1000         fprintf(ofp, " Dispatch wait:   %'8lu%8c\t", rdwait, ' ');
1001         fprintf(ofp, " Dispatch wait:    %'8lu\n", wdwait);
1002         fprintf(ofp, " Completion wait: %'8lu%8c\t", rcwait, ' ');
1003         fprintf(ofp, " Completion wait:  %'8lu\n", wcwait);
1004 }
1005
1006 static void show_process_stats(void)
1007 {
1008         struct per_process_info *ppi;
1009
1010         ppi = ppi_list;
1011         while (ppi) {
1012                 dump_io_stats(&ppi->io_stats, ppi->name);
1013                 dump_wait_stats(ppi);
1014                 ppi = ppi->list_next;
1015         }
1016
1017         fprintf(ofp, "\n");
1018 }
1019
1020 static void show_device_and_cpu_stats(void)
1021 {
1022         struct per_dev_info *pdi;
1023         struct per_cpu_info *pci;
1024         struct io_stats total, *ios;
1025         int i, j, pci_events;
1026         char line[3 + 8/*cpu*/ + 2 + 32/*dev*/ + 3];
1027         char name[32];
1028
1029         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1030
1031                 memset(&total, 0, sizeof(total));
1032                 pci_events = 0;
1033
1034                 if (i > 0)
1035                         fprintf(ofp, "\n");
1036
1037                 for (pci = pdi->cpus, j = 0; j < pdi->ncpus; j++, pci++) {
1038                         if (!pci->nelems)
1039                                 continue;
1040
1041                         ios = &pci->io_stats;
1042                         total.qreads += ios->qreads;
1043                         total.qwrites += ios->qwrites;
1044                         total.creads += ios->creads;
1045                         total.cwrites += ios->cwrites;
1046                         total.mreads += ios->mreads;
1047                         total.mwrites += ios->mwrites;
1048                         total.ireads += ios->ireads;
1049                         total.iwrites += ios->iwrites;
1050                         total.qread_kb += ios->qread_kb;
1051                         total.qwrite_kb += ios->qwrite_kb;
1052                         total.cread_kb += ios->cread_kb;
1053                         total.cwrite_kb += ios->cwrite_kb;
1054                         total.iread_kb += ios->iread_kb;
1055                         total.iwrite_kb += ios->iwrite_kb;
1056                         total.timer_unplugs += ios->timer_unplugs;
1057                         total.io_unplugs += ios->io_unplugs;
1058
1059                         snprintf(line, sizeof(line) - 1, "CPU%d (%s):",
1060                                  j, get_dev_name(pdi, name, sizeof(name)));
1061                         dump_io_stats(ios, line);
1062                         pci_events++;
1063                 }
1064
1065                 if (pci_events > 1) {
1066                         fprintf(ofp, "\n");
1067                         snprintf(line, sizeof(line) - 1, "Total (%s):",
1068                                  get_dev_name(pdi, name, sizeof(name)));
1069                         dump_io_stats(&total, line);
1070                 }
1071
1072                 fprintf(ofp, "Events (%s): %'Lu\n",
1073                         get_dev_name(pdi, line, sizeof(line)), pdi->events);
1074         }
1075 }
1076
1077 static struct blk_io_trace *find_trace(void *p, unsigned long offset)
1078 {
1079         unsigned long max_offset = offset;
1080         unsigned long off;
1081         struct blk_io_trace *bit;
1082         __u32 magic;
1083
1084         for (off = 0; off < max_offset; off++) {
1085                 bit = p + off;
1086
1087                 magic = be32_to_cpu(bit->magic);
1088                 if ((magic & 0xffffff00) == BLK_IO_TRACE_MAGIC)
1089                         return bit;
1090         }
1091
1092         return NULL;
1093 }
1094
1095 static int sort_entries(void)
1096 {
1097         struct per_dev_info *pdi;
1098         struct per_cpu_info *pci;
1099         struct blk_io_trace *bit;
1100         struct trace *t;
1101         int nr = 0;
1102
1103         while ((t = trace_list) != NULL) {
1104
1105                 trace_list = t->next;
1106                 bit = t->bit;
1107
1108                 memset(&t->rb_node, 0, sizeof(t->rb_node));
1109
1110                 trace_to_cpu(bit);
1111
1112                 if (verify_trace(bit))
1113                         break;
1114                 if (trace_rb_insert(t))
1115                         return -1;
1116
1117                 pdi = get_dev_info(bit->device);
1118                 pci = get_cpu_info(pdi, bit->cpu);
1119                 pci->nelems++;
1120
1121                 nr++;
1122         }
1123
1124         return nr;
1125 }
1126
1127 static void show_entries_rb(void)
1128 {
1129         struct per_dev_info *pdi;
1130         struct blk_io_trace *bit;
1131         struct rb_node *n;
1132         struct trace *t;
1133         int cpu;
1134
1135         while ((n = rb_first(&rb_sort_root)) != NULL) {
1136
1137                 t = rb_entry(n, struct trace, rb_node);
1138                 bit = t->bit;
1139
1140                 pdi = get_dev_info(bit->device);
1141                 if (!pdi) {
1142                         fprintf(stderr, "Unknown device ID? (%d,%d)\n",
1143                                 MAJOR(bit->device), MINOR(bit->device));
1144                         break;
1145                 }
1146                 cpu = bit->cpu;
1147                 if (cpu > pdi->ncpus) {
1148                         fprintf(stderr, "Unknown CPU ID? (%d, device %d,%d)\n",
1149                                 cpu, MAJOR(bit->device), MINOR(bit->device));
1150                         break;
1151                 }
1152
1153                 /*
1154                  * back off displaying more info if we are out of sync
1155                  * on SMP systems. to prevent stalling on lost events,
1156                  * only allow an event to skip us once
1157                  */
1158                 if (bit->sequence != (pdi->last_sequence + 1)) {
1159                         if (!t->skipped) {
1160                                 t->skipped = 1;
1161                                 break;
1162                         }
1163                 }
1164
1165                 pdi->last_sequence = bit->sequence;
1166
1167                 bit->time -= genesis_time;
1168                 if (bit->time < stopwatch_start)
1169                         continue;
1170                 if (bit->time >= stopwatch_end)
1171                         break;
1172
1173                 check_time(pdi, bit);
1174
1175                 if (dump_trace(bit, &pdi->cpus[cpu], pdi))
1176                         break;
1177
1178                 rb_erase(&t->rb_node, &rb_sort_root);
1179                 free(bit);
1180                 free(t);
1181         }
1182 }
1183
1184 static int read_data(int fd, void *buffer, int bytes, int block)
1185 {
1186         int ret, bytes_left, fl;
1187         void *p;
1188
1189         fl = fcntl(fd, F_GETFL);
1190
1191         if (!block)
1192                 fcntl(fd, F_SETFL, fl | O_NONBLOCK);
1193         else
1194                 fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
1195
1196         bytes_left = bytes;
1197         p = buffer;
1198         while (bytes_left > 0) {
1199                 ret = read(fd, p, bytes_left);
1200                 if (!ret)
1201                         return 1;
1202                 else if (ret < 0) {
1203                         if (errno != EAGAIN)
1204                                 perror("read");
1205                         return -1;
1206                 } else {
1207                         p += ret;
1208                         bytes_left -= ret;
1209                 }
1210         }
1211
1212         return 0;
1213 }
1214
1215 /*
1216  * Find the traces in 'tb' and add them to the list for sorting and
1217  * displaying
1218  */
1219 static int find_entries(void *tb, unsigned long size)
1220 {
1221         struct blk_io_trace *bit;
1222         struct trace *t;
1223         void *start = tb;
1224
1225         while (tb - start <= size - sizeof(*bit)) {
1226                 bit = find_trace(tb, size - (tb - start));
1227                 if (!bit)
1228                         break;
1229
1230                 t = malloc(sizeof(*t));
1231                 memset(t, 0, sizeof(*t));
1232                 t->bit = bit;
1233
1234                 t->next = trace_list;
1235                 trace_list = t;
1236
1237                 tb += sizeof(*bit) + bit->pdu_len;
1238         }
1239
1240         return 0;
1241 }
1242
1243 static int do_file(void)
1244 {
1245         struct per_dev_info *pdi;
1246         int i, j, nfiles = 0, nelems;
1247
1248         for (pdi = devices, i = 0; i < ndevices; i++, pdi++) {
1249                 for (j = 0;; j++, nfiles++) {
1250                         struct per_cpu_info *pci;
1251                         struct stat st;
1252                         void *tb;
1253
1254                         pci = get_cpu_info(pdi, j);
1255                         pci->cpu = j;
1256
1257                         snprintf(pci->fname, sizeof(pci->fname)-1,
1258                                  "%s_out.%d", pdi->name, j);
1259                         if (stat(pci->fname, &st) < 0)
1260                                 break;
1261                         if (!st.st_size)
1262                                 continue;
1263
1264                         printf("Processing %s\n", pci->fname);
1265
1266                         tb = malloc(st.st_size);
1267                         if (!tb) {
1268                                 fprintf(stderr, "Out of memory, skip file %s\n",
1269                                         pci->fname);
1270                                 continue;
1271                         }
1272
1273                         pci->fd = open(pci->fname, O_RDONLY);
1274                         if (pci->fd < 0) {
1275                                 perror(pci->fname);
1276                                 free(tb);
1277                                 continue;
1278                         }
1279
1280                         if (read_data(pci->fd, tb, st.st_size, 1)) {
1281                                 close(pci->fd);
1282                                 free(tb);
1283                                 continue;
1284                         }
1285
1286                         if (find_entries(tb, st.st_size)) {
1287                                 close(pci->fd);
1288                                 free(tb);
1289                         }
1290
1291                         nelems = sort_entries();
1292                         if (nelems == -1) {
1293                                 close(pci->fd);
1294                                 free(tb);
1295                                 continue;
1296                         }
1297
1298                         printf("Completed %s (CPU%d %d, entries)\n",
1299                                 pci->fname, j, nelems);
1300                         close(pci->fd);
1301                 }
1302         }
1303
1304         if (!nfiles) {
1305                 fprintf(stderr, "No files found\n");
1306                 return 1;
1307         }
1308
1309         show_entries_rb();
1310         return 0;
1311 }
1312
1313 static int read_sort_events(int fd)
1314 {
1315         int events = 0;
1316
1317         do {
1318                 struct blk_io_trace *bit;
1319                 struct trace *t;
1320                 int pdu_len;
1321                 __u32 magic;
1322
1323                 bit = malloc(sizeof(*bit));
1324
1325                 if (read_data(fd, bit, sizeof(*bit), !events))
1326                         break;
1327
1328                 magic = be32_to_cpu(bit->magic);
1329                 if ((magic & 0xffffff00) != BLK_IO_TRACE_MAGIC) {
1330                         fprintf(stderr, "Bad magic %x\n", magic);
1331                         break;
1332                 }
1333
1334                 pdu_len = be16_to_cpu(bit->pdu_len);
1335                 if (pdu_len) {
1336                         void *ptr = realloc(bit, sizeof(*bit) + pdu_len);
1337
1338                         if (read_data(fd, ptr + sizeof(*bit), pdu_len, 1))
1339                                 break;
1340
1341                         bit = ptr;
1342                 }
1343
1344                 t = malloc(sizeof(*t));
1345                 memset(t, 0, sizeof(*t));
1346                 t->bit = bit;
1347                 t->next = trace_list;
1348                 trace_list = t;
1349
1350                 events++;
1351         } while (!is_done() && events < rb_batch);
1352
1353         return events;
1354 }
1355
1356 static int do_stdin(void)
1357 {
1358         int fd;
1359
1360         fd = dup(STDIN_FILENO);
1361         do {
1362                 int events;
1363
1364                 events = read_sort_events(fd);
1365                 if (!events)
1366                         break;
1367         
1368                 if (sort_entries() == -1)
1369                         break;
1370
1371                 show_entries_rb();
1372         } while (1);
1373
1374         close(fd);
1375         return 0;
1376 }
1377
1378 static void flush_output(void)
1379 {
1380         fflush(ofp);
1381 }
1382
1383 static void handle_sigint(int sig)
1384 {
1385         done = 1;
1386         flush_output();
1387 }
1388
1389 /*
1390  * Extract start and duration times from a string, allowing
1391  * us to specify a time interval of interest within a trace.
1392  * Format: "duration" (start is zero) or "start:duration".
1393  */
1394 static int find_stopwatch_interval(char *string)
1395 {
1396         double value;
1397         char *sp;
1398
1399         value = strtod(string, &sp);
1400         if (sp == string) {
1401                 fprintf(stderr,"Invalid stopwatch timer: %s\n", string);
1402                 return 1;
1403         }
1404         if (*sp == ':') {
1405                 stopwatch_start = DOUBLE_TO_NANO_ULL(value);
1406                 string = sp + 1;
1407                 value = strtod(string, &sp);
1408                 if (sp == string || *sp != '\0') {
1409                         fprintf(stderr,"Invalid stopwatch duration time: %s\n",
1410                                 string);
1411                         return 1;
1412                 }
1413         } else if (*sp != '\0') {
1414                 fprintf(stderr,"Invalid stopwatch start timer: %s\n", string);
1415                 return 1;
1416         }
1417         stopwatch_end = stopwatch_start + DOUBLE_TO_NANO_ULL(value);
1418         return 0;
1419 }
1420
1421 static void usage(char *prog)
1422 {
1423         fprintf(stderr, "Usage: %s "
1424                 "[-i <name>] [-o <output>] [-s] [-w N[:n]] <name>...\n",
1425                 prog);
1426 }
1427
1428 int main(int argc, char *argv[])
1429 {
1430         char *ofp_buffer;
1431         int c, ret, mode;
1432         int per_device_and_cpu_stats = 1;
1433
1434         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) != -1) {
1435                 switch (c) {
1436                 case 'i':
1437                         if (!strcmp(optarg, "-") && !pipeline)
1438                                 pipeline = 1;
1439                         else if (resize_devices(optarg) != 0)
1440                                 return 1;
1441                         break;
1442                 case 'o':
1443                         output_name = optarg;
1444                         break;
1445                 case 'b':
1446                         rb_batch = atoi(optarg);
1447                         if (rb_batch <= 0)
1448                                 rb_batch = RB_BATCH_DEFAULT;
1449                         break;
1450                 case 's':
1451                         per_process_stats = 1;
1452                         break;
1453                 case 't':
1454                         track_ios = 1;
1455                         break;
1456                 case 'q':
1457                         per_device_and_cpu_stats = 0;
1458                         break;
1459                 case 'w':
1460                         if (find_stopwatch_interval(optarg) != 0)
1461                                 return 1;
1462                         break;
1463                 default:
1464                         usage(argv[0]);
1465                         return 1;
1466                 }
1467         }
1468
1469         while (optind < argc) {
1470                 if (!strcmp(argv[optind], "-") && !pipeline)
1471                         pipeline = 1;
1472                 else if (resize_devices(argv[optind]) != 0)
1473                         return 1;
1474                 optind++;
1475         }
1476
1477         if (!pipeline && !ndevices) {
1478                 usage(argv[0]);
1479                 return 1;
1480         }
1481
1482         memset(&rb_sort_root, 0, sizeof(rb_sort_root));
1483         memset(&rb_track_root, 0, sizeof(rb_track_root));
1484
1485         signal(SIGINT, handle_sigint);
1486         signal(SIGHUP, handle_sigint);
1487         signal(SIGTERM, handle_sigint);
1488
1489         setlocale(LC_NUMERIC, "en_US");
1490
1491         if (!output_name) {
1492                 ofp = fdopen(STDOUT_FILENO, "w");
1493                 mode = _IOLBF;
1494         } else {
1495                 char ofname[128];
1496
1497                 snprintf(ofname, sizeof(ofname) - 1, "%s.log", output_name);
1498                 ofp = fopen(ofname, "w");
1499                 mode = _IOFBF;
1500         }
1501
1502         if (!ofp) {
1503                 perror("fopen");
1504                 return 1;
1505         }
1506
1507         ofp_buffer = malloc(4096);      
1508         if (setvbuf(ofp, ofp_buffer, mode, 4096)) {
1509                 perror("setvbuf");
1510                 return 1;
1511         }
1512
1513         if (pipeline)
1514                 ret = do_stdin();
1515         else
1516                 ret = do_file();
1517
1518         if (per_process_stats)
1519                 show_process_stats();
1520
1521         if (per_device_and_cpu_stats)
1522                 show_device_and_cpu_stats();
1523
1524         flush_output();
1525         return ret;
1526 }