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