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