c8f9ffb70e1f72418871e0e23f4afaea58e20205
[blktrace.git] / blktrace.c
1 /*
2  * block queue tracing 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 <pthread.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <locale.h>
26 #include <signal.h>
27 #include <fcntl.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/param.h>
31 #include <sys/statfs.h>
32 #include <sys/poll.h>
33 #include <sys/mman.h>
34 #include <sys/socket.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <sched.h>
38 #include <ctype.h>
39 #include <getopt.h>
40 #include <errno.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <netdb.h>
44 #include <sys/sendfile.h>
45
46 #include "blktrace.h"
47 #include "barrier.h"
48
49 static char blktrace_version[] = "0.99";
50
51 /*
52  * You may want to increase this even more, if you are logging at a high
53  * rate and see skipped/missed events
54  */
55 #define BUF_SIZE        (512 * 1024)
56 #define BUF_NR          (4)
57
58 #define OFILE_BUF       (128 * 1024)
59
60 #define RELAYFS_TYPE    0xF0B4A981
61
62 #define S_OPTS  "d:a:A:r:o:kw:Vb:n:D:lh:p:s"
63 static struct option l_opts[] = {
64         {
65                 .name = "dev",
66                 .has_arg = required_argument,
67                 .flag = NULL,
68                 .val = 'd'
69         },
70         {
71                 .name = "act-mask",
72                 .has_arg = required_argument,
73                 .flag = NULL,
74                 .val = 'a'
75         },
76         {
77                 .name = "set-mask",
78                 .has_arg = required_argument,
79                 .flag = NULL,
80                 .val = 'A'
81         },
82         {
83                 .name = "relay",
84                 .has_arg = required_argument,
85                 .flag = NULL,
86                 .val = 'r'
87         },
88         {
89                 .name = "output",
90                 .has_arg = required_argument,
91                 .flag = NULL,
92                 .val = 'o'
93         },
94         {
95                 .name = "kill",
96                 .has_arg = no_argument,
97                 .flag = NULL,
98                 .val = 'k'
99         },
100         {
101                 .name = "stopwatch",
102                 .has_arg = required_argument,
103                 .flag = NULL,
104                 .val = 'w'
105         },
106         {
107                 .name = "version",
108                 .has_arg = no_argument,
109                 .flag = NULL,
110                 .val = 'V'
111         },
112         {
113                 .name = "buffer-size",
114                 .has_arg = required_argument,
115                 .flag = NULL,
116                 .val = 'b'
117         },
118         {
119                 .name = "num-sub-buffers",
120                 .has_arg = required_argument,
121                 .flag = NULL,
122                 .val = 'n'
123         },
124         {
125                 .name = "output-dir",
126                 .has_arg = required_argument,
127                 .flag = NULL,
128                 .val = 'D'
129         },
130         {
131                 .name = "listen",
132                 .has_arg = no_argument,
133                 .flag = NULL,
134                 .val = 'l'
135         },
136         {
137                 .name = "host",
138                 .has_arg = required_argument,
139                 .flag = NULL,
140                 .val = 'h'
141         },
142         {
143                 .name = "port",
144                 .has_arg = required_argument,
145                 .flag = NULL,
146                 .val = 'p'
147         },
148         {
149                 .name = "sendfile",
150                 .has_arg = no_argument,
151                 .flag = NULL,
152                 .val = 's'
153         },
154         {
155                 .name = NULL,
156         }
157 };
158
159 struct tip_subbuf {
160         void *buf;
161         unsigned int len;
162         unsigned int max_len;
163         off_t offset;
164 };
165
166 #define FIFO_SIZE       (1024)  /* should be plenty big! */
167 #define CL_SIZE         (128)   /* cache line, any bigger? */
168
169 struct tip_subbuf_fifo {
170         int tail __attribute__((aligned(CL_SIZE)));
171         int head __attribute__((aligned(CL_SIZE)));
172         struct tip_subbuf *q[FIFO_SIZE];
173 };
174
175 struct thread_information {
176         int cpu;
177         pthread_t thread;
178
179         int fd;
180         void *fd_buf;
181         char fn[MAXPATHLEN + 64];
182
183         int pfd;
184         size_t *pfd_buf;
185
186         FILE *ofile;
187         char *ofile_buffer;
188         off_t ofile_offset;
189         int ofile_stdout;
190         int ofile_mmap;
191
192         int (*get_subbuf)(struct thread_information *, unsigned int);
193         int (*flush_subbuf)(struct thread_information *, struct tip_subbuf *);
194         int (*read_data)(struct thread_information *, void *, unsigned int);
195
196         unsigned long events_processed;
197         unsigned long long data_read;
198         struct device_information *device;
199
200         int exited;
201
202         /*
203          * piped fifo buffers
204          */
205         struct tip_subbuf_fifo fifo;
206         struct tip_subbuf *leftover_ts;
207
208         /*
209          * mmap controlled output files
210          */
211         unsigned long long fs_size;
212         unsigned long long fs_max_size;
213         unsigned long fs_off;
214         void *fs_buf;
215         unsigned long fs_buf_len;
216 };
217
218 struct device_information {
219         int fd;
220         char *path;
221         char buts_name[32];
222         volatile int trace_started;
223         unsigned long drop_count;
224         struct thread_information *threads;
225 };
226
227 static int ncpus;
228 static struct thread_information *thread_information;
229 static int ndevs;
230 static struct device_information *device_information;
231
232 /* command line option globals */
233 static char *relay_path;
234 static char *output_name;
235 static char *output_dir;
236 static int act_mask = ~0U;
237 static int kill_running_trace;
238 static unsigned long buf_size = BUF_SIZE;
239 static unsigned long buf_nr = BUF_NR;
240 static unsigned int page_size;
241
242 #define is_done()       (*(volatile int *)(&done))
243 static volatile int done;
244
245 #define is_trace_stopped()      (*(volatile int *)(&trace_stopped))
246 static volatile int trace_stopped;
247
248 #define is_stat_shown() (*(volatile int *)(&stat_shown))
249 static volatile int stat_shown;
250
251 int data_is_native = -1;
252
253 static void exit_trace(int status);
254
255 #define dip_tracing(dip)        (*(volatile int *)(&(dip)->trace_started))
256 #define dip_set_tracing(dip, v) ((dip)->trace_started = (v))
257
258 #define __for_each_dip(__d, __i, __e)   \
259         for (__i = 0, __d = device_information; __i < __e; __i++, __d++)
260
261 #define for_each_dip(__d, __i)  __for_each_dip(__d, __i, ndevs)
262 #define for_each_tip(__d, __t, __j)     \
263         for (__j = 0, __t = (__d)->threads; __j < ncpus; __j++, __t++)
264
265 /*
266  * networking stuff follows. we include a magic number so we know whether
267  * to endianness convert or not
268  */
269 struct blktrace_net_hdr {
270         u32 magic;              /* same as trace magic */
271         char buts_name[32];     /* trace name */
272         u32 cpu;                /* for which cpu */
273         u32 max_cpus;
274         u32 len;                /* length of following trace data */
275 };
276
277 #define TRACE_NET_PORT          (8462)
278
279 enum {
280         Net_none = 0,
281         Net_server,
282         Net_client,
283 };
284
285 /*
286  * network cmd line params
287  */
288 static char hostname[MAXHOSTNAMELEN];
289 static int net_port = TRACE_NET_PORT;
290 static int net_mode = 0;
291 static int net_sendfile;
292
293 static int net_in_fd = -1;
294 static int net_out_fd = -1;
295
296 static void handle_sigint(__attribute__((__unused__)) int sig)
297 {
298         done = 1;
299 }
300
301 static int get_dropped_count(const char *buts_name)
302 {
303         int fd;
304         char tmp[MAXPATHLEN + 64];
305
306         snprintf(tmp, sizeof(tmp), "%s/block/%s/dropped",
307                  relay_path, buts_name);
308
309         fd = open(tmp, O_RDONLY);
310         if (fd < 0) {
311                 /*
312                  * this may be ok, if the kernel doesn't support dropped counts
313                  */
314                 if (errno == ENOENT)
315                         return 0;
316
317                 fprintf(stderr, "Couldn't open dropped file %s\n", tmp);
318                 return -1;
319         }
320
321         if (read(fd, tmp, sizeof(tmp)) < 0) {
322                 perror(tmp);
323                 close(fd);
324                 return -1;
325         }
326
327         close(fd);
328
329         return atoi(tmp);
330 }
331
332 static size_t get_subbuf_padding(struct thread_information *tip,
333                                  unsigned subbuf)
334 {
335         size_t padding_size = buf_nr * sizeof(size_t);
336         size_t ret;
337
338         if (read(tip->pfd, tip->pfd_buf, padding_size) < 0) {
339                 perror("tip pad read");
340                 ret = -1;
341         } else
342                 ret = tip->pfd_buf[subbuf];
343
344         return ret;
345 }
346
347 static int start_trace(struct device_information *dip)
348 {
349         struct blk_user_trace_setup buts;
350
351         memset(&buts, 0, sizeof(buts));
352         buts.buf_size = buf_size;
353         buts.buf_nr = buf_nr;
354         buts.act_mask = act_mask;
355
356         if (ioctl(dip->fd, BLKTRACESETUP, &buts) < 0) {
357                 perror("BLKTRACESETUP");
358                 return 1;
359         }
360
361         if (ioctl(dip->fd, BLKTRACESTART) < 0) {
362                 perror("BLKTRACESTART");
363                 return 1;
364         }
365
366         memcpy(dip->buts_name, buts.name, sizeof(dip->buts_name));
367         dip_set_tracing(dip, 1);
368         return 0;
369 }
370
371 static void stop_trace(struct device_information *dip)
372 {
373         if (dip_tracing(dip) || kill_running_trace) {
374                 dip_set_tracing(dip, 0);
375
376                 if (ioctl(dip->fd, BLKTRACESTOP) < 0)
377                         perror("BLKTRACESTOP");
378                 if (ioctl(dip->fd, BLKTRACETEARDOWN) < 0)
379                         perror("BLKTRACETEARDOWN");
380
381                 close(dip->fd);
382                 dip->fd = -1;
383         }
384 }
385
386 static void stop_all_traces(void)
387 {
388         struct device_information *dip;
389         int i;
390
391         for_each_dip(dip, i) {
392                 dip->drop_count = get_dropped_count(dip->buts_name);
393                 stop_trace(dip);
394         }
395 }
396
397 static void wait_for_data(struct thread_information *tip)
398 {
399         struct pollfd pfd = { .fd = tip->fd, .events = POLLIN };
400
401         do {
402                 poll(&pfd, 1, 100);
403                 if (pfd.revents & POLLIN)
404                         break;
405                 if (tip->ofile_stdout)
406                         break;
407         } while (!is_done());
408 }
409
410 static int read_data_file(struct thread_information *tip, void *buf,
411                           unsigned int len)
412 {
413         int ret = 0;
414
415         do {
416                 wait_for_data(tip);
417
418                 ret = read(tip->fd, buf, len);
419                 if (!ret)
420                         continue;
421                 else if (ret > 0)
422                         return ret;
423                 else {
424                         if (errno != EAGAIN) {
425                                 perror(tip->fn);
426                                 fprintf(stderr,"Thread %d failed read of %s\n",
427                                         tip->cpu, tip->fn);
428                                 break;
429                         }
430                         continue;
431                 }
432         } while (!is_done());
433
434         return ret;
435
436 }
437
438 static int read_data_net(struct thread_information *tip, void *buf,
439                          unsigned int len)
440 {
441         unsigned int bytes_left = len;
442         int ret = 0;
443
444         do {
445                 ret = recv(net_in_fd, buf, bytes_left, MSG_WAITALL);
446
447                 if (!ret)
448                         continue;
449                 else if (ret < 0) {
450                         if (errno != EAGAIN) {
451                                 perror(tip->fn);
452                                 fprintf(stderr, "server: failed read\n");
453                                 return 0;
454                         }
455                         continue;
456                 } else {
457                         buf += ret;
458                         bytes_left -= ret;
459                 }
460         } while (!is_done() && bytes_left);
461
462         return len - bytes_left;
463 }
464
465 static int read_data(struct thread_information *tip, void *buf,
466                      unsigned int len)
467 {
468         int ret = tip->read_data(tip, buf, len);
469
470         if (ret > 0)
471                 tip->data_read += ret;
472
473         return ret;
474 }
475
476 static inline struct tip_subbuf *
477 subbuf_fifo_dequeue(struct thread_information *tip)
478 {
479         const int head = tip->fifo.head;
480         const int next = (head + 1) & (FIFO_SIZE - 1);
481
482         if (head != tip->fifo.tail) {
483                 struct tip_subbuf *ts = tip->fifo.q[head];
484
485                 store_barrier();
486                 tip->fifo.head = next;
487                 return ts;
488         }
489
490         return NULL;
491 }
492
493 static inline int subbuf_fifo_queue(struct thread_information *tip,
494                                     struct tip_subbuf *ts)
495 {
496         const int tail = tip->fifo.tail;
497         const int next = (tail + 1) & (FIFO_SIZE - 1);
498
499         if (next != tip->fifo.head) {
500                 tip->fifo.q[tail] = ts;
501                 store_barrier();
502                 tip->fifo.tail = next;
503                 return 0;
504         }
505
506         fprintf(stderr, "fifo too small!\n");
507         return 1;
508 }
509
510 /*
511  * For file output, truncate and mmap the file appropriately
512  */
513 static int mmap_subbuf(struct thread_information *tip, unsigned int maxlen)
514 {
515         int ofd = fileno(tip->ofile);
516         int ret;
517
518         /*
519          * extend file, if we have to. use chunks of 16 subbuffers.
520          */
521         if (tip->fs_off + buf_size > tip->fs_buf_len) {
522                 if (tip->fs_buf) {
523                         munlock(tip->fs_buf, tip->fs_buf_len);
524                         munmap(tip->fs_buf, tip->fs_buf_len);
525                         tip->fs_buf = NULL;
526                 }
527
528                 tip->fs_off = tip->fs_size & (page_size - 1);
529                 tip->fs_buf_len = (16 * buf_size) - tip->fs_off;
530                 tip->fs_max_size += tip->fs_buf_len;
531
532                 if (ftruncate(ofd, tip->fs_max_size) < 0) {
533                         perror("ftruncate");
534                         return -1;
535                 }
536
537                 tip->fs_buf = mmap(NULL, tip->fs_buf_len, PROT_WRITE,
538                                    MAP_SHARED, ofd, tip->fs_size - tip->fs_off);
539                 if (tip->fs_buf == MAP_FAILED) {
540                         perror("mmap");
541                         return -1;
542                 }
543                 mlock(tip->fs_buf, tip->fs_buf_len);
544         }
545
546         ret = read_data(tip, tip->fs_buf + tip->fs_off, maxlen);
547         if (ret >= 0) {
548                 tip->fs_size += ret;
549                 tip->fs_off += ret;
550                 return 0;
551         }
552
553         return -1;
554 }
555
556 /*
557  * Use the copy approach for pipes and network
558  */
559 static int get_subbuf(struct thread_information *tip, unsigned int maxlen)
560 {
561         struct tip_subbuf *ts = malloc(sizeof(*ts));
562         int ret;
563
564         ts->buf = malloc(buf_size);
565         ts->max_len = maxlen;
566
567         ret = read_data(tip, ts->buf, ts->max_len);
568         if (ret > 0) {
569                 ts->len = ret;
570                 return subbuf_fifo_queue(tip, ts);
571         }
572
573         return ret;
574 }
575
576 static int get_subbuf_sendfile(struct thread_information *tip,
577                                unsigned int maxlen)
578 {
579         struct tip_subbuf *ts;
580         struct stat sb;
581         unsigned int ready, this_size;
582         int err;
583
584         wait_for_data(tip);
585
586         /*
587          * hack to get last data out, we can't use sendfile for that
588          */
589         if (is_done())
590                 return get_subbuf(tip, maxlen);
591
592         if (fstat(tip->fd, &sb) < 0) {
593                 perror("trace stat");
594                 return 1;
595         }
596
597         ready = sb.st_size - tip->ofile_offset;
598         if (!ready)
599                 return 0;
600
601         this_size = buf_size;
602         while (ready) {
603                 if (this_size > ready)
604                         this_size = ready;
605
606                 ts = malloc(sizeof(*ts));
607
608                 ts->max_len = maxlen;
609                 ts->buf = NULL;
610
611                 ts->len = this_size;
612                 ts->max_len = ts->len;
613                 ts->offset = tip->ofile_offset;
614                 tip->ofile_offset += ts->len;
615
616                 err = subbuf_fifo_queue(tip, ts);
617                 if (err)
618                         return err;
619
620                 ready -= this_size;
621         }
622
623         return 0;
624 }
625
626 static void close_thread(struct thread_information *tip)
627 {
628         if (tip->fd != -1)
629                 close(tip->fd);
630         if (tip->pfd != -1)
631                 close(tip->pfd);
632         if (tip->ofile)
633                 fclose(tip->ofile);
634         if (tip->ofile_buffer)
635                 free(tip->ofile_buffer);
636         if (tip->fd_buf)
637                 free(tip->fd_buf);
638         if (tip->pfd_buf)
639                 free(tip->pfd_buf);
640
641         tip->fd = -1;
642         tip->pfd = -1;
643         tip->ofile = NULL;
644         tip->ofile_buffer = NULL;
645         tip->fd_buf = NULL;
646 }
647
648 static void tip_ftrunc_final(struct thread_information *tip)
649 {
650         /*
651          * truncate to right size and cleanup mmap
652          */
653         if (tip->ofile_mmap) {
654                 int ofd = fileno(tip->ofile);
655
656                 if (tip->fs_buf)
657                         munmap(tip->fs_buf, tip->fs_buf_len);
658
659                 ftruncate(ofd, tip->fs_size);
660         }
661 }
662
663 static void *thread_main(void *arg)
664 {
665         struct thread_information *tip = arg;
666         pid_t pid = getpid();
667         cpu_set_t cpu_mask;
668
669         CPU_ZERO(&cpu_mask);
670         CPU_SET((tip->cpu), &cpu_mask);
671
672         if (sched_setaffinity(pid, sizeof(cpu_mask), &cpu_mask) == -1) {
673                 perror("sched_setaffinity");
674                 exit_trace(1);
675         }
676
677         snprintf(tip->fn, sizeof(tip->fn), "%s/block/%s/trace%d",
678                         relay_path, tip->device->buts_name, tip->cpu);
679         tip->fd = open(tip->fn, O_RDONLY);
680         if (tip->fd < 0) {
681                 perror(tip->fn);
682                 fprintf(stderr,"Thread %d failed open of %s\n", tip->cpu,
683                         tip->fn);
684                 exit_trace(1);
685         }
686
687         if (net_mode == Net_client && net_sendfile) {
688                 char tmp[MAXPATHLEN + 64];
689
690                 snprintf(tmp, sizeof(tmp), "%s/block/%s/trace%d.padding",
691                          relay_path, tip->device->buts_name, tip->cpu);
692
693                 tip->pfd = open(tmp, O_RDONLY);
694                 if (tip->pfd < 0) {
695                         fprintf(stderr, "Couldn't open padding file %s\n", tmp);
696                         exit_trace(1);
697                 }
698
699                 tip->pfd_buf = malloc(buf_nr * sizeof(size_t));
700         }
701
702         while (!is_done()) {
703                 if (tip->get_subbuf(tip, buf_size))
704                         break;
705         }
706
707         tip_ftrunc_final(tip);
708         tip->exited = 1;
709         return NULL;
710 }
711
712 static int write_data_net(int fd, void *buf, unsigned int buf_len)
713 {
714         unsigned int bytes_left = buf_len;
715         int ret;
716
717         while (bytes_left) {
718                 ret = send(fd, buf, bytes_left, 0);
719                 if (ret < 0) {
720                         perror("send");
721                         return 1;
722                 }
723
724                 buf += ret;
725                 bytes_left -= ret;
726         }
727
728         return 0;
729 }
730
731 static int net_send_header(struct thread_information *tip, unsigned int len)
732 {
733         struct blktrace_net_hdr hdr;
734
735         hdr.magic = BLK_IO_TRACE_MAGIC;
736         strcpy(hdr.buts_name, tip->device->buts_name);
737         hdr.cpu = tip->cpu;
738         hdr.max_cpus = ncpus;
739         hdr.len = len;
740
741         return write_data_net(net_out_fd, &hdr, sizeof(hdr));
742 }
743
744 /*
745  * send header with 0 length to signal end-of-run
746  */
747 static void net_client_send_close(void)
748 {
749         struct blktrace_net_hdr hdr;
750
751         hdr.magic = BLK_IO_TRACE_MAGIC;
752         hdr.cpu = 0;
753         hdr.max_cpus = ncpus;
754         hdr.len = 0;
755
756         write_data_net(net_out_fd, &hdr, sizeof(hdr));
757 }
758
759 static int flush_subbuf_net(struct thread_information *tip,
760                             struct tip_subbuf *ts)
761 {
762         if (net_send_header(tip, ts->len))
763                 return 1;
764         if (write_data_net(net_out_fd, ts->buf, ts->len))
765                 return 1;
766
767         tip->data_read += ts->len;
768         free(ts->buf);
769         free(ts);
770         return 0;
771 }
772
773 static int flush_subbuf_sendfile(struct thread_information *tip,
774                                  struct tip_subbuf *ts)
775 {
776         size_t padding;
777         unsigned subbuf;
778         unsigned len;
779
780         /*
781          * currently we cannot use sendfile() on the last bytes read, as they
782          * may not be a full subbuffer. get_subbuf_sendfile() falls back to
783          * the read approach for those, so use send() to ship them out
784          */
785         if (ts->buf)
786                 return flush_subbuf_net(tip, ts);
787         
788         subbuf = (ts->offset / buf_size) % buf_nr;
789         padding = get_subbuf_padding(tip, subbuf);
790         len = ts->len - padding;
791
792         if (net_send_header(tip, len))
793                 return 1;
794         if (sendfile(net_out_fd, tip->fd, &ts->offset, len) < 0) {
795                 perror("sendfile");
796                 return 1;
797         }
798
799         tip->data_read += ts->len;
800         free(ts);
801         return 0;
802 }
803
804 static int write_data(struct thread_information *tip, void *buf,
805                       unsigned int buf_len)
806 {
807         int ret;
808
809         if (!buf_len)
810                 return 0;
811
812         while (1) {
813                 ret = fwrite(buf, buf_len, 1, tip->ofile);
814                 if (ret == 1)
815                         break;
816
817                 if (ret < 0) {
818                         perror("write");
819                         return 1;
820                 }
821         }
822
823         if (tip->ofile_stdout)
824                 fflush(tip->ofile);
825
826         return 0;
827 }
828
829 static int flush_subbuf_file(struct thread_information *tip,
830                              struct tip_subbuf *ts)
831 {
832         unsigned int offset = 0;
833         struct blk_io_trace *t;
834         int pdu_len, events = 0;
835
836         /*
837          * surplus from last run
838          */
839         if (tip->leftover_ts) {
840                 struct tip_subbuf *prev_ts = tip->leftover_ts;
841
842                 if (prev_ts->len + ts->len > prev_ts->max_len) {
843                         prev_ts->max_len += ts->len;
844                         prev_ts->buf = realloc(prev_ts->buf, prev_ts->max_len);
845                 }
846
847                 memcpy(prev_ts->buf + prev_ts->len, ts->buf, ts->len);
848                 prev_ts->len += ts->len;
849
850                 free(ts->buf);
851                 free(ts);
852
853                 ts = prev_ts;
854                 tip->leftover_ts = NULL;
855         }
856
857         while (offset + sizeof(*t) <= ts->len) {
858                 t = ts->buf + offset;
859
860                 if (verify_trace(t)) {
861                         write_data(tip, ts->buf, offset);
862                         return -1;
863                 }
864
865                 pdu_len = t->pdu_len;
866
867                 if (offset + sizeof(*t) + pdu_len > ts->len)
868                         break;
869
870                 offset += sizeof(*t) + pdu_len;
871                 tip->events_processed++;
872                 tip->data_read += sizeof(*t) + pdu_len;
873                 events++;
874         }
875
876         if (write_data(tip, ts->buf, offset))
877                 return -1;
878
879         /*
880          * leftover bytes, save them for next time
881          */
882         if (offset != ts->len) {
883                 tip->leftover_ts = ts;
884                 ts->len -= offset;
885                 memmove(ts->buf, ts->buf + offset, ts->len);
886         } else {
887                 free(ts->buf);
888                 free(ts);
889         }
890
891         return events;
892 }
893
894 static int write_tip_events(struct thread_information *tip)
895 {
896         struct tip_subbuf *ts = subbuf_fifo_dequeue(tip);
897
898         if (ts)
899                 return tip->flush_subbuf(tip, ts);
900
901         return 0;
902 }
903
904 /*
905  * scans the tips we know and writes out the subbuffers we accumulate
906  */
907 static void get_and_write_events(void)
908 {
909         struct device_information *dip;
910         struct thread_information *tip;
911         int i, j, events, ret, tips_running;
912
913         while (!is_done()) {
914                 events = 0;
915
916                 for_each_dip(dip, i) {
917                         for_each_tip(dip, tip, j) {
918                                 ret = write_tip_events(tip);
919                                 if (ret > 0)
920                                         events += ret;
921                         }
922                 }
923
924                 if (!events)
925                         usleep(10);
926         }
927
928         /*
929          * reap stored events
930          */
931         do {
932                 events = 0;
933                 tips_running = 0;
934                 for_each_dip(dip, i) {
935                         for_each_tip(dip, tip, j) {
936                                 ret = write_tip_events(tip);
937                                 if (ret > 0)
938                                         events += ret;
939                                 tips_running += !tip->exited;
940                         }
941                 }
942                 usleep(10);
943         } while (events || tips_running);
944 }
945
946 static void wait_for_threads(void)
947 {
948         /*
949          * for piped or network output, poll and fetch data for writeout.
950          * for files, we just wait around for trace threads to exit
951          */
952         if ((output_name && !strcmp(output_name, "-")) ||
953             net_mode == Net_client)
954                 get_and_write_events();
955         else {
956                 struct device_information *dip;
957                 struct thread_information *tip;
958                 int i, j, tips_running;
959
960                 do {
961                         tips_running = 0;
962                         usleep(1000);
963
964                         for_each_dip(dip, i)
965                                 for_each_tip(dip, tip, j)
966                                         tips_running += !tip->exited;
967                 } while (tips_running);
968         }
969
970         if (net_mode == Net_client)
971                 net_client_send_close();
972 }
973
974 static void fill_ofname(char *dst, char *buts_name, int cpu)
975 {
976         int len = 0;
977
978         if (output_dir)
979                 len = sprintf(dst, "%s/", output_dir);
980
981         if (output_name)
982                 sprintf(dst + len, "%s.blktrace.%d", output_name, cpu);
983         else
984                 sprintf(dst + len, "%s.blktrace.%d", buts_name, cpu);
985 }
986
987 static void fill_ops(struct thread_information *tip)
988 {
989         /*
990          * setup ops
991          */
992         if (net_mode == Net_client) {
993                 if (net_sendfile) {
994                         tip->get_subbuf = get_subbuf_sendfile;
995                         tip->flush_subbuf = flush_subbuf_sendfile;
996                 } else {
997                         tip->get_subbuf = get_subbuf;
998                         tip->flush_subbuf = flush_subbuf_net;
999                 }
1000         } else {
1001                 if (tip->ofile_mmap)
1002                         tip->get_subbuf = mmap_subbuf;
1003                 else
1004                         tip->get_subbuf = get_subbuf;
1005
1006                 tip->flush_subbuf = flush_subbuf_file;
1007         }
1008                         
1009         if (net_mode == Net_server)
1010                 tip->read_data = read_data_net;
1011         else
1012                 tip->read_data = read_data_file;
1013 }
1014
1015 static int tip_open_output(struct device_information *dip,
1016                            struct thread_information *tip)
1017 {
1018         int pipeline = output_name && !strcmp(output_name, "-");
1019         int mode, vbuf_size;
1020         char op[64];
1021
1022         if (net_mode == Net_client) {
1023                 tip->ofile = NULL;
1024                 tip->ofile_stdout = 0;
1025                 tip->ofile_mmap = 0;
1026                 vbuf_size = 0;
1027                 mode = 0; /* gcc 4.x issues a bogus warning */
1028         } else if (pipeline) {
1029                 tip->ofile = fdopen(STDOUT_FILENO, "w");
1030                 tip->ofile_stdout = 1;
1031                 tip->ofile_mmap = 0;
1032                 mode = _IOLBF;
1033                 vbuf_size = 512;
1034         } else {
1035                 fill_ofname(op, dip->buts_name, tip->cpu);
1036                 tip->ofile = fopen(op, "w+");
1037                 tip->ofile_stdout = 0;
1038                 tip->ofile_mmap = 1;
1039                 mode = _IOFBF;
1040                 vbuf_size = OFILE_BUF;
1041         }
1042
1043         if (net_mode != Net_client && tip->ofile == NULL) {
1044                 perror(op);
1045                 return 1;
1046         }
1047
1048         if (vbuf_size) {
1049                 tip->ofile_buffer = malloc(vbuf_size);
1050                 if (setvbuf(tip->ofile, tip->ofile_buffer, mode, vbuf_size)) {
1051                         perror("setvbuf");
1052                         close_thread(tip);
1053                         return 1;
1054                 }
1055         }
1056
1057         fill_ops(tip);
1058         return 0;
1059 }
1060
1061 static int start_threads(struct device_information *dip)
1062 {
1063         struct thread_information *tip;
1064         int j;
1065
1066         for_each_tip(dip, tip, j) {
1067                 tip->cpu = j;
1068                 tip->device = dip;
1069                 tip->events_processed = 0;
1070                 tip->fd = -1;
1071                 tip->pfd = -1;
1072                 memset(&tip->fifo, 0, sizeof(tip->fifo));
1073                 tip->leftover_ts = NULL;
1074
1075                 if (tip_open_output(dip, tip))
1076                         return 1;
1077
1078                 if (pthread_create(&tip->thread, NULL, thread_main, tip)) {
1079                         perror("pthread_create");
1080                         close_thread(tip);
1081                         return 1;
1082                 }
1083         }
1084
1085         return 0;
1086 }
1087
1088 static void stop_threads(struct device_information *dip)
1089 {
1090         struct thread_information *tip;
1091         unsigned long ret;
1092         int i;
1093
1094         for_each_tip(dip, tip, i) {
1095                 (void) pthread_join(tip->thread, (void *) &ret);
1096                 close_thread(tip);
1097         }
1098 }
1099
1100 static void stop_all_threads(void)
1101 {
1102         struct device_information *dip;
1103         int i;
1104
1105         for_each_dip(dip, i)
1106                 stop_threads(dip);
1107 }
1108
1109 static void stop_all_tracing(void)
1110 {
1111         struct device_information *dip;
1112         int i;
1113
1114         for_each_dip(dip, i)
1115                 stop_trace(dip);
1116 }
1117
1118 static void exit_trace(int status)
1119 {
1120         if (!is_trace_stopped()) {
1121                 trace_stopped = 1;
1122                 stop_all_threads();
1123                 stop_all_tracing();
1124         }
1125
1126         exit(status);
1127 }
1128
1129 static int resize_devices(char *path)
1130 {
1131         int size = (ndevs + 1) * sizeof(struct device_information);
1132
1133         device_information = realloc(device_information, size);
1134         if (!device_information) {
1135                 fprintf(stderr, "Out of memory, device %s (%d)\n", path, size);
1136                 return 1;
1137         }
1138         device_information[ndevs].path = path;
1139         ndevs++;
1140         return 0;
1141 }
1142
1143 static int open_devices(void)
1144 {
1145         struct device_information *dip;
1146         int i;
1147
1148         for_each_dip(dip, i) {
1149                 dip->fd = open(dip->path, O_RDONLY | O_NONBLOCK);
1150                 if (dip->fd < 0) {
1151                         perror(dip->path);
1152                         return 1;
1153                 }
1154         }
1155
1156         return 0;
1157 }
1158
1159 static int start_devices(void)
1160 {
1161         struct device_information *dip;
1162         int i, j, size;
1163
1164         size = ncpus * sizeof(struct thread_information);
1165         thread_information = malloc(size * ndevs);
1166         if (!thread_information) {
1167                 fprintf(stderr, "Out of memory, threads (%d)\n", size * ndevs);
1168                 return 1;
1169         }
1170
1171         for_each_dip(dip, i) {
1172                 if (start_trace(dip)) {
1173                         close(dip->fd);
1174                         fprintf(stderr, "Failed to start trace on %s\n",
1175                                 dip->path);
1176                         break;
1177                 }
1178         }
1179
1180         if (i != ndevs) {
1181                 __for_each_dip(dip, j, i)
1182                         stop_trace(dip);
1183
1184                 return 1;
1185         }
1186
1187         for_each_dip(dip, i) {
1188                 dip->threads = thread_information + (i * ncpus);
1189                 if (start_threads(dip)) {
1190                         fprintf(stderr, "Failed to start worker threads\n");
1191                         break;
1192                 }
1193         }
1194
1195         if (i != ndevs) {
1196                 __for_each_dip(dip, j, i)
1197                         stop_threads(dip);
1198                 for_each_dip(dip, i)
1199                         stop_trace(dip);
1200
1201                 return 1;
1202         }
1203
1204         return 0;
1205 }
1206
1207 static void show_stats(void)
1208 {
1209         struct device_information *dip;
1210         struct thread_information *tip;
1211         unsigned long long events_processed, data_read;
1212         unsigned long total_drops;
1213         int i, j, no_stdout = 0;
1214
1215         if (is_stat_shown())
1216                 return;
1217
1218         if (output_name && !strcmp(output_name, "-"))
1219                 no_stdout = 1;
1220
1221         stat_shown = 1;
1222
1223         total_drops = 0;
1224         for_each_dip(dip, i) {
1225                 if (!no_stdout)
1226                         printf("Device: %s\n", dip->path);
1227                 events_processed = 0;
1228                 data_read = 0;
1229                 for_each_tip(dip, tip, j) {
1230                         if (!no_stdout)
1231                                 printf("  CPU%3d: %20lu events, %8llu KiB data\n",
1232                                         tip->cpu, tip->events_processed,
1233                                         (tip->data_read + 1023) >> 10);
1234                         events_processed += tip->events_processed;
1235                         data_read += tip->data_read;
1236                 }
1237                 total_drops += dip->drop_count;
1238                 if (!no_stdout)
1239                         printf("  Total:  %20llu events (dropped %lu), %8llu KiB data\n",
1240                                         events_processed, dip->drop_count,
1241                                         (data_read + 1023) >> 10);
1242         }
1243
1244         if (total_drops)
1245                 fprintf(stderr, "You have dropped events, consider using a larger buffer size (-b)\n");
1246 }
1247
1248 static struct device_information *net_get_dip(char *buts_name)
1249 {
1250         struct device_information *dip;
1251         int i;
1252
1253         for (i = 0; i < ndevs; i++) {
1254                 dip = &device_information[i];
1255
1256                 if (!strcmp(dip->buts_name, buts_name))
1257                         return dip;
1258         }
1259
1260         device_information = realloc(device_information, (ndevs + 1) * sizeof(*dip));
1261         dip = &device_information[ndevs];
1262         strcpy(dip->buts_name, buts_name);
1263         strcpy(dip->path, buts_name);
1264         ndevs++;
1265         dip->threads = malloc(ncpus * sizeof(struct thread_information));
1266         memset(dip->threads, 0, ncpus * sizeof(struct thread_information));
1267
1268         /*
1269          * open all files
1270          */
1271         for (i = 0; i < ncpus; i++) {
1272                 struct thread_information *tip = &dip->threads[i];
1273
1274                 tip->cpu = i;
1275                 tip->device = dip;
1276
1277                 if (tip_open_output(dip, tip))
1278                         return NULL;
1279         }
1280
1281         return dip;
1282 }
1283
1284 static struct thread_information *net_get_tip(struct blktrace_net_hdr *bnh)
1285 {
1286         struct device_information *dip;
1287
1288         ncpus = bnh->max_cpus;
1289         dip = net_get_dip(bnh->buts_name);
1290         return &dip->threads[bnh->cpu];
1291 }
1292
1293 static int net_get_header(struct blktrace_net_hdr *bnh)
1294 {
1295         int fl = fcntl(net_in_fd, F_GETFL);
1296         int bytes_left, ret;
1297         void *p = bnh;
1298
1299         fcntl(net_in_fd, F_SETFL, fl | O_NONBLOCK);
1300         bytes_left = sizeof(*bnh);
1301         while (bytes_left && !is_done()) {
1302                 ret = recv(net_in_fd, p, bytes_left, MSG_WAITALL);
1303                 if (ret < 0) {
1304                         if (errno != EAGAIN) {
1305                                 perror("recv header");
1306                                 return 1;
1307                         }
1308                         usleep(100);
1309                         continue;
1310                 } else if (!ret) {
1311                         usleep(100);
1312                         continue;
1313                 } else {
1314                         p += ret;
1315                         bytes_left -= ret;
1316                 }
1317         }
1318         fcntl(net_in_fd, F_SETFL, fl & ~O_NONBLOCK);
1319         return 0;
1320 }
1321
1322 static int net_server_loop(void)
1323 {
1324         struct thread_information *tip;
1325         struct blktrace_net_hdr bnh;
1326
1327         if (net_get_header(&bnh))
1328                 return 1;
1329
1330         if (data_is_native == -1 && check_data_endianness(bnh.magic)) {
1331                 fprintf(stderr, "server: received data is bad\n");
1332                 return 1;
1333         }
1334
1335         if (!data_is_native) {
1336                 bnh.cpu = be32_to_cpu(bnh.cpu);
1337                 bnh.len = be32_to_cpu(bnh.len);
1338         }
1339
1340         /*
1341          * len == 0 means that the other end signalled end-of-run
1342          */
1343         if (!bnh.len) {
1344                 fprintf(stderr, "server: end of run\n");
1345                 return 1;
1346         }
1347
1348         tip = net_get_tip(&bnh);
1349         if (!tip)
1350                 return 1;
1351
1352         if (mmap_subbuf(tip, bnh.len))
1353                 return 1;
1354
1355         return 0;
1356 }
1357
1358 /*
1359  * Start here when we are in server mode - just fetch data from the network
1360  * and dump to files
1361  */
1362 static int net_server(void)
1363 {
1364         struct device_information *dip;
1365         struct thread_information *tip;
1366         struct sockaddr_in addr;
1367         socklen_t socklen;
1368         int fd, opt, i, j;
1369
1370         fd = socket(AF_INET, SOCK_STREAM, 0);
1371         if (fd < 0) {
1372                 perror("server: socket");
1373                 return 1;
1374         }
1375
1376         opt = 1;
1377         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
1378                 perror("setsockopt");
1379                 return 1;
1380         }
1381
1382         memset(&addr, 0, sizeof(addr));
1383         addr.sin_family = AF_INET;
1384         addr.sin_addr.s_addr = htonl(INADDR_ANY);
1385         addr.sin_port = htons(net_port);
1386
1387         if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1388                 perror("bind");
1389                 return 1;
1390         }
1391
1392         if (listen(fd, 1) < 0) {
1393                 perror("listen");
1394                 return 1;
1395         }
1396
1397 repeat:
1398         signal(SIGINT, NULL);
1399         signal(SIGHUP, NULL);
1400         signal(SIGTERM, NULL);
1401         signal(SIGALRM, NULL);
1402
1403         printf("blktrace: waiting for incoming connection...\n");
1404
1405         socklen = sizeof(addr);
1406         net_in_fd = accept(fd, (struct sockaddr *) &addr, &socklen);
1407         if (net_in_fd < 0) {
1408                 perror("accept");
1409                 return 1;
1410         }
1411
1412         signal(SIGINT, handle_sigint);
1413         signal(SIGHUP, handle_sigint);
1414         signal(SIGTERM, handle_sigint);
1415         signal(SIGALRM, handle_sigint);
1416
1417         printf("blktrace: connection from %s\n", inet_ntoa(addr.sin_addr));
1418
1419         while (!is_done()) {
1420                 if (net_server_loop())
1421                         break;
1422         }
1423
1424         for_each_dip(dip, i)
1425                 for_each_tip(dip, tip, j)
1426                         tip_ftrunc_final(tip);
1427
1428         show_stats();
1429
1430         if (is_done())
1431                 return 0;
1432
1433         /*
1434          * cleanup for next run
1435          */
1436         for_each_dip(dip, i) {
1437                 for_each_tip(dip, tip, j)
1438                         fclose(tip->ofile);
1439
1440                 free(dip->threads);
1441         }
1442
1443         free(device_information);
1444         device_information = NULL;
1445         ncpus = ndevs = 0;
1446
1447         close(net_in_fd);
1448         net_in_fd = -1;
1449         goto repeat;
1450 }
1451
1452 /*
1453  * Setup outgoing network connection where we will transmit data
1454  */
1455 static int net_setup_client(void)
1456 {
1457         struct sockaddr_in addr;
1458         int fd;
1459
1460         fd = socket(AF_INET, SOCK_STREAM, 0);
1461         if (fd < 0) {
1462                 perror("client: socket");
1463                 return 1;
1464         }
1465
1466         memset(&addr, 0, sizeof(addr));
1467         addr.sin_family = AF_INET;
1468         addr.sin_port = htons(net_port);
1469
1470         if (inet_aton(hostname, &addr.sin_addr) != 1) {
1471                 struct hostent *hent = gethostbyname(hostname);
1472                 if (!hent) {
1473                         perror("gethostbyname");
1474                         return 1;
1475                 }
1476
1477                 memcpy(&addr.sin_addr, hent->h_addr, 4);
1478                 strcpy(hostname, hent->h_name);
1479         }
1480
1481         printf("blktrace: connecting to %s\n", hostname);
1482
1483         if (connect(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
1484                 perror("client: connect");
1485                 return 1;
1486         }
1487
1488         printf("blktrace: connected!\n");
1489         net_out_fd = fd;
1490         return 0;
1491 }
1492
1493 static char usage_str[] = \
1494         "-d <dev> [ -r relay path ] [ -o <output> ] [-k ] [ -w time ]\n" \
1495         "[ -a action ] [ -A action mask ] [ -v ]\n\n" \
1496         "\t-d Use specified device. May also be given last after options\n" \
1497         "\t-r Path to mounted relayfs, defaults to /relay\n" \
1498         "\t-o File(s) to send output to\n" \
1499         "\t-D Directory to prepend to output file names\n" \
1500         "\t-k Kill a running trace\n" \
1501         "\t-w Stop after defined time, in seconds\n" \
1502         "\t-a Only trace specified actions. See documentation\n" \
1503         "\t-A Give trace mask as a single value. See documentation\n" \
1504         "\t-b Sub buffer size in KiB\n" \
1505         "\t-n Number of sub buffers\n" \
1506         "\t-l Run in network listen mode (blktrace server)\n" \
1507         "\t-h Run in network client mode, connecting to the given host\n" \
1508         "\t-p Network port to use (default 8462)\n" \
1509         "\t-s Make the network client use sendfile() to transfer data\n" \
1510         "\t-V Print program version info\n\n";
1511
1512 static void show_usage(char *program)
1513 {
1514         fprintf(stderr, "Usage: %s %s %s",program, blktrace_version, usage_str);
1515 }
1516
1517 int main(int argc, char *argv[])
1518 {
1519         static char default_relay_path[] = "/relay";
1520         struct statfs st;
1521         int i, c;
1522         int stop_watch = 0;
1523         int act_mask_tmp = 0;
1524
1525         while ((c = getopt_long(argc, argv, S_OPTS, l_opts, NULL)) >= 0) {
1526                 switch (c) {
1527                 case 'a':
1528                         i = find_mask_map(optarg);
1529                         if (i < 0) {
1530                                 fprintf(stderr,"Invalid action mask %s\n",
1531                                         optarg);
1532                                 return 1;
1533                         }
1534                         act_mask_tmp |= i;
1535                         break;
1536
1537                 case 'A':
1538                         if ((sscanf(optarg, "%x", &i) != 1) || 
1539                                                         !valid_act_opt(i)) {
1540                                 fprintf(stderr,
1541                                         "Invalid set action mask %s/0x%x\n",
1542                                         optarg, i);
1543                                 return 1;
1544                         }
1545                         act_mask_tmp = i;
1546                         break;
1547
1548                 case 'd':
1549                         if (resize_devices(optarg) != 0)
1550                                 return 1;
1551                         break;
1552
1553                 case 'r':
1554                         relay_path = optarg;
1555                         break;
1556
1557                 case 'o':
1558                         output_name = optarg;
1559                         break;
1560                 case 'k':
1561                         kill_running_trace = 1;
1562                         break;
1563                 case 'w':
1564                         stop_watch = atoi(optarg);
1565                         if (stop_watch <= 0) {
1566                                 fprintf(stderr,
1567                                         "Invalid stopwatch value (%d secs)\n",
1568                                         stop_watch);
1569                                 return 1;
1570                         }
1571                         break;
1572                 case 'V':
1573                         printf("%s version %s\n", argv[0], blktrace_version);
1574                         return 0;
1575                 case 'b':
1576                         buf_size = strtoul(optarg, NULL, 10);
1577                         if (buf_size <= 0 || buf_size > 16*1024) {
1578                                 fprintf(stderr,
1579                                         "Invalid buffer size (%lu)\n",buf_size);
1580                                 return 1;
1581                         }
1582                         buf_size <<= 10;
1583                         break;
1584                 case 'n':
1585                         buf_nr = strtoul(optarg, NULL, 10);
1586                         if (buf_nr <= 0) {
1587                                 fprintf(stderr,
1588                                         "Invalid buffer nr (%lu)\n", buf_nr);
1589                                 return 1;
1590                         }
1591                         break;
1592                 case 'D':
1593                         output_dir = optarg;
1594                         break;
1595                 case 'h':
1596                         net_mode = Net_client;
1597                         strcpy(hostname, optarg);
1598                         break;
1599                 case 'l':
1600                         net_mode = Net_server;
1601                         break;
1602                 case 'p':
1603                         net_port = atoi(optarg);
1604                         break;
1605                 case 's':
1606                         net_sendfile = 1;
1607                         break;
1608                 default:
1609                         show_usage(argv[0]);
1610                         return 1;
1611                 }
1612         }
1613
1614         setlocale(LC_NUMERIC, "en_US");
1615
1616         page_size = getpagesize();
1617
1618         if (net_mode == Net_server)
1619                 return net_server();
1620
1621         while (optind < argc) {
1622                 if (resize_devices(argv[optind++]) != 0)
1623                         return 1;
1624         }
1625
1626         if (ndevs == 0) {
1627                 show_usage(argv[0]);
1628                 return 1;
1629         }
1630
1631         if (!relay_path)
1632                 relay_path = default_relay_path;
1633
1634         if (act_mask_tmp != 0)
1635                 act_mask = act_mask_tmp;
1636
1637         if (statfs(relay_path, &st) < 0) {
1638                 perror("statfs");
1639                 fprintf(stderr,"%s does not appear to be a valid path\n",
1640                         relay_path);
1641                 return 1;
1642         } else if (st.f_type != (long) RELAYFS_TYPE) {
1643                 fprintf(stderr,"%s does not appear to be a relay filesystem\n",
1644                         relay_path);
1645                 return 1;
1646         }
1647
1648         if (open_devices() != 0)
1649                 return 1;
1650
1651         if (kill_running_trace) {
1652                 stop_all_traces();
1653                 return 0;
1654         }
1655
1656         ncpus = sysconf(_SC_NPROCESSORS_ONLN);
1657         if (ncpus < 0) {
1658                 fprintf(stderr, "sysconf(_SC_NPROCESSORS_ONLN) failed\n");
1659                 return 1;
1660         }
1661
1662         signal(SIGINT, handle_sigint);
1663         signal(SIGHUP, handle_sigint);
1664         signal(SIGTERM, handle_sigint);
1665         signal(SIGALRM, handle_sigint);
1666
1667         if (net_mode == Net_client && net_setup_client())
1668                 return 1;
1669
1670         if (start_devices() != 0)
1671                 return 1;
1672
1673         atexit(stop_all_tracing);
1674
1675         if (stop_watch)
1676                 alarm(stop_watch);
1677
1678         wait_for_threads();
1679
1680         if (!is_trace_stopped()) {
1681                 trace_stopped = 1;
1682                 stop_all_threads();
1683                 stop_all_traces();
1684         }
1685
1686         show_stats();
1687
1688         return 0;
1689 }
1690