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