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