]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
9f0a46654f00ba98ed1ee007ecd07520e6315571
[can-benchmark.git] / latester / latester.c
1 /**************************************************************************/
2 /* CAN latency tester                                                     */
3 /* Copyright (C) 2010 Michal Sojka, DCE FEE CTU Prague                    */
4 /* License: GPLv2                                                         */
5 /**************************************************************************/
6
7 #include <ctype.h>
8 #include <errno.h>
9 #include <error.h>
10 #include <fcntl.h>
11 #include <math.h>
12 #include <net/if.h>
13 #include <poll.h>
14 #include <popt.h>
15 #include <pthread.h>
16 #include <semaphore.h>
17 #include <sched.h>
18 #include <signal.h>
19 #include <stdbool.h>
20 #include <stdint.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/ioctl.h>
25 #include <sys/mman.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <talloc.h>
31 #include <unistd.h>
32
33 #include <linux/can.h>
34 #include <linux/can/raw.h>
35
36 #include "histogram.h"
37
38 //#define FTRACE
39
40 #ifndef DEBUG
41 #define dbg(level, fmt, arg...) do {} while (0)
42 #else
43 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
44 #endif
45
46 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
47
48 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
49
50 /* Global variables */
51 volatile sig_atomic_t finish_flag = 0;  /* Threads should terminate. */
52 sem_t finish_sem;               /* Thread signals a termination */
53
54 /* Command line options */
55 struct options {
56         char **interface;
57         canid_t id;
58         unsigned period_us;
59         unsigned timeout_ms;
60         unsigned count;
61         unsigned oneattime;
62         FILE *file;
63         FILE *histogram;
64         int length;
65         int userhist;
66 };
67
68 struct options opt = {
69         .id = 10,
70         .period_us = 0,
71         .timeout_ms = 1000,
72         .length = 2,
73 };
74
75 int num_interfaces = 0;
76 int count = 0;                  /* Number of sent messages */
77 int completion_pipe[2];
78
79 struct msg_info {
80         canid_t id;
81         uint8_t length;
82         struct timespec ts_sent, ts_sent_kern;
83         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
84         struct timespec ts_rx_final, ts_rx_final_kern;
85         struct can_frame sent, received;
86 };
87
88 #define MAX_INFOS 10000
89 struct msg_info msg_infos[MAX_INFOS];
90
91 struct histogram histogram;
92
93 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
94         /* documentation see lib.h */
95
96         int i,offset;
97         int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
98
99         if (cf->can_id & CAN_ERR_FLAG) {
100                 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
101                 offset = 9;
102         } else if (cf->can_id & CAN_EFF_FLAG) {
103                 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
104                 offset = 9;
105         } else {
106                 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
107                 offset = 4;
108         }
109
110         if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
111                 sprintf(buf+offset, "R");
112         else
113                 for (i = 0; i < dlc; i++) {
114                         sprintf(buf+offset, "%02X", cf->data[i]);
115                         offset += 2;
116                         if (sep && (i+1 < dlc))
117                                 sprintf(buf+offset++, ".");
118                 }
119 }
120
121 static inline struct msg_info *frame2info(struct can_frame *frame)
122 {
123         uint16_t idx;
124         if (frame->can_dlc >= 2) {
125                 memcpy(&idx, frame->data, sizeof(idx));
126                 if (idx >= MAX_INFOS)
127                         error(1, 0, "%s idx too high", __FUNCTION__);
128         } else {
129                 
130                 error(1, 0, "%s error", __FUNCTION__);
131         }
132         return &msg_infos[idx];
133 }
134
135 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
136 {
137         return talloc_asprintf(ctx, "%ld.%06ld",
138                                tstamp->tv_sec, tstamp->tv_nsec/1000);
139 }
140
141 void msg_info_print(FILE *f, struct msg_info *mi)
142 {
143         struct timespec diff;
144         void *local = talloc_new (NULL);
145         static long num = 0;
146         char sent[64], received[64];
147
148         sprint_canframe(sent, &mi->sent, true);
149         sprint_canframe(received, &mi->received, true);
150
151 #define S(ts) tstamp_str(local, &ts)
152 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
153
154         if (num_interfaces == 2)
155                 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s)\n",
156                         num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
157                        DIFF(mi->ts_sent, mi->ts_rx_final_kern),
158                        DIFF(mi->ts_sent, mi->ts_rx_final));
159         else
160                 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s)\n",
161                         num, S(mi->ts_sent), sent,
162                         S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
163                         S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
164                         DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
165                         DIFF(mi->ts_sent, mi->ts_rx_onwire),
166                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
167                         DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
168 #undef S
169 #undef DIFF
170         num++;
171         talloc_free (local);
172 }
173
174 int msg_info_store(FILE *f, struct msg_info *mi)
175 {
176         struct timespec diff;
177         void *local = talloc_new (NULL);
178         static long num = 0;
179
180 #define S(ts) tstamp_str(local, &ts)
181 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
182
183         if (num_interfaces == 2)
184                 fprintf(f, "%ld %d %d %s\n",
185                         num, mi->id, mi->length,
186                         DIFF(mi->ts_sent, mi->ts_rx_final_kern));
187         else
188                 fprintf(f, "%ld %d %d %s\n",
189                         num, mi->id, mi->length,
190                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
191 #undef S
192 #undef DIFF
193         talloc_free (local);
194 }
195
196
197 /* Subtract the `struct timespec' values X and Y, storing the result in
198    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
199
200 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
201 {
202         struct timespec ylocal = *yy, *y = &ylocal;
203         /* Perform the carry for the later subtraction by updating Y. */
204         if (x->tv_nsec < y->tv_nsec) {
205                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
206                 y->tv_nsec -= 1000000000 * nsec;
207                 y->tv_sec += nsec;
208         }
209         if (x->tv_nsec - y->tv_nsec > 1000000000) {
210                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
211                 y->tv_nsec += 1000000000 * nsec;
212                 y->tv_sec -= nsec;
213         }
214
215         /* Compute the time remaining to wait.
216            `tv_nsec' is certainly positive. */
217         result->tv_sec = x->tv_sec - y->tv_sec;
218         result->tv_nsec = x->tv_nsec - y->tv_nsec;
219
220         /* Return 1 if result is negative. */
221         return x->tv_sec < y->tv_sec;
222 }
223
224 void dbg_print_timespec(char *msg, struct timespec *tv)
225 {
226
227         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
228 }
229
230 static inline unsigned get_msg_latency_us(struct msg_info *mi)
231 {
232         struct timespec diff;
233         if (num_interfaces == 3)
234                 if (opt.userhist)
235                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
236                 else
237                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
238         else
239                 if (opt.userhist)
240                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
241                 else
242                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
243         return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
244 }
245
246 void set_sched_policy_and_prio(int policy, int rtprio)
247 {
248         struct sched_param scheduling_parameters;
249         int maxprio=sched_get_priority_max(policy);
250         int minprio=sched_get_priority_min(policy);
251
252         if((rtprio < minprio) || (rtprio > maxprio))
253                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
254                       minprio, maxprio);
255
256         scheduling_parameters.sched_priority = rtprio;
257
258         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
259                 error(1, errno, "pthread_setschedparam error");
260 }
261
262 void term_handler(int signum)
263 {
264         finish_flag = 1;
265 }
266
267 static inline int sock_get_if_index(int s, const char *if_name)
268 {
269         struct ifreq ifr;
270         MEMSET_ZERO(ifr);
271
272         strcpy(ifr.ifr_name, if_name);
273         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
274                 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
275         return ifr.ifr_ifindex;
276 }
277
278 static inline get_tstamp(struct timespec *ts)
279 {
280         clock_gettime(CLOCK_REALTIME, ts);
281 }
282
283
284 int trace_fd = -1;
285 int marker_fd = -1;
286
287 int init_ftrace()
288 {
289 #ifdef FTRACE
290         char *debugfs;
291         char path[256];
292         FILE *f;
293         
294         debugfs = "/sys/kernel/debug";
295         if (debugfs) {
296                 strcpy(path, debugfs);
297                 strcat(path,"/tracing/tracing_on");
298                 trace_fd = open(path, O_WRONLY);
299                 if (trace_fd >= 0)
300                         write(trace_fd, "1", 1);
301
302                 strcpy(path, debugfs);
303                 strcat(path,"/tracing/trace_marker");
304                 marker_fd = open(path, O_WRONLY);
305
306                 strcpy(path, debugfs);
307                 strcat(path,"/tracing/set_ftrace_pid");
308                 f = fopen(path, "w");
309                 fprintf(f, "%d\n", getpid());
310                 fclose(f);
311                 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
312                 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
313                 system("echo > /sys/kernel/debug/tracing/trace");
314                 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
315         }
316 #endif  /* FTRACE */
317 }
318
319 int send_frame(int socket)
320 {
321         struct can_frame frame;
322         struct msg_info *mi;
323         int ret;
324         static int curr_msg = -1;
325         int i;
326         uint16_t idx;
327
328         MEMSET_ZERO(frame);
329         i = curr_msg+1;
330         while (msg_infos[i].id != -1 && i != curr_msg) {
331                 i++;
332                 if (i >= MAX_INFOS)
333                         i = 0;
334         }
335         if (i == curr_msg)
336                 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
337         else
338                 curr_msg = i;
339
340         frame.can_id = opt.id;
341         if (opt.length < 2)
342                 error(1, 0, "Length < 2 is not yet supported");
343         frame.can_dlc = opt.length;
344         idx = curr_msg;
345         memcpy(frame.data, &idx, sizeof(idx));
346         mi = frame2info(&frame);
347
348         mi->id = frame.can_id;
349         mi->length = frame.can_dlc;
350         get_tstamp(&mi->ts_sent);
351         mi->sent = frame;
352         
353         if (trace_fd >= 0)
354                 write(trace_fd, "1", 1);
355         ret = write(socket, &frame, sizeof(frame));
356         if (marker_fd >= 0) {
357                 char marker[100];
358                 sprintf(marker, "write returned %d\n", ret);
359                 write(marker_fd, marker, strlen(marker));
360         }
361         if (trace_fd >= 0)
362                 write(trace_fd, "0", 1);
363         return ret;
364 }
365
366 void msg_info_free(struct msg_info *mi)
367 {
368         mi->id = -1;
369 }
370
371 static inline void get_next_timeout(struct timespec *timeout)
372 {
373         struct timespec now;
374         static struct timespec last = {-1, 0 };
375
376         clock_gettime(CLOCK_MONOTONIC, &now);
377
378         if (last.tv_sec == -1)
379                 last = now;
380         if (opt.period_us != 0) {
381                 last.tv_sec += opt.period_us/1000000;
382                 last.tv_nsec += (opt.period_us%1000000)*1000;
383                 while (last.tv_nsec >= 1000000000) {
384                         last.tv_nsec -= 1000000000;
385                         last.tv_sec++;
386                 }
387                 timespec_subtract(timeout, &last, &now);
388         } else if (opt.timeout_ms != 0) {
389                 timeout->tv_sec = opt.timeout_ms/1000;
390                 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
391         } else
392                 error(1, 0, "Timeout and period cannot be both zero");
393 }
394
395 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
396 {
397         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
398         struct iovec iov;
399         struct msghdr msg;
400         struct cmsghdr *cmsg;
401         struct sockaddr_can addr;
402         int nbytes;
403         static uint64_t dropcnt = 0;
404
405         iov.iov_base = frame;
406         msg.msg_name = &addr;
407         msg.msg_iov = &iov;
408         msg.msg_iovlen = 1;
409         msg.msg_control = &ctrlmsg;
410
411         /* these settings may be modified by recvmsg() */
412         iov.iov_len = sizeof(*frame);
413         msg.msg_namelen = sizeof(addr);
414         msg.msg_controllen = sizeof(ctrlmsg);
415         msg.msg_flags = 0;
416
417         nbytes = recvmsg(s, &msg, 0);
418         if (nbytes < 0)
419                 error(1, errno, "recvmsg");
420
421         if (nbytes < sizeof(struct can_frame))
422                 error(1, 0, "recvmsg: incomplete CAN frame\n");
423
424         get_tstamp(ts_user);
425         MEMSET_ZERO(*ts_kern);
426         for (cmsg = CMSG_FIRSTHDR(&msg);
427              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
428              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
429                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
430                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
431                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
432                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
433         }
434
435 }
436
437 void process_tx(int s)
438 {
439         error(1, 0, "%s: not implemented", __FUNCTION__);
440 }
441
442 void process_on_wire_rx(int s)
443 {
444         struct timespec ts_kern, ts_user, ts_diff;
445         struct can_frame frame;
446         struct msg_info *mi;
447         receive(s, &frame, &ts_kern, &ts_user);
448         mi = frame2info(&frame);
449         mi->ts_rx_onwire_kern = ts_kern;
450         mi->ts_rx_onwire = ts_user;
451 }
452
453
454 void process_final_rx(int s)
455 {
456         struct timespec ts_kern, ts_user, ts_diff;
457         struct can_frame frame;
458         struct msg_info *mi;
459         int ret;
460         
461         receive(s, &frame, &ts_kern, &ts_user);
462         mi = frame2info(&frame);
463         mi->ts_rx_final_kern = ts_kern;
464         mi->ts_rx_final = ts_user;
465         mi->received = frame;
466
467         if (opt.histogram)
468                 histogram_add(&histogram, get_msg_latency_us(mi));
469
470         ret = write(completion_pipe[1], &mi, sizeof(mi));
471         if (ret == -1)
472                 error(1, errno, "completion_pipe write");
473 }
474
475 void *measure_thread(void *arg)
476 {
477         int s, i, ret;
478         struct pollfd pfd[3];
479         struct timespec timeout;
480         struct sockaddr_can addr;
481         sigset_t set;
482         unsigned msg_in_progress = 0;
483
484         MEMSET_ZERO(pfd);
485
486         for (i=0; i<num_interfaces; i++) {
487                 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
488                         error(1, errno, "socket");
489
490                 addr.can_family = AF_CAN;
491                 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
492
493                 if (i == 0) {   /* TX socket */
494                         /* disable default receive filter on this RAW socket */
495                         /* This is obsolete as we do not read from the socket at all, but for */
496                         /* this reason we can remove the receive list in the Kernel to save a */
497                         /* little (really a very little!) CPU usage.                          */
498                         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
499                                 error(1, errno, "SOL_CAN_RAW");
500                 }
501
502                 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
503                         error(1, errno, "bind");
504
505                 const int timestamp_on = 1;
506                 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
507                                &timestamp_on, sizeof(timestamp_on)) < 0)
508                         error(1, errno, "setsockopt SO_TIMESTAMP");
509
510                 const int dropmonitor_on = 1;
511                 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
512                                &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
513                         error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
514
515                 pfd[i].fd = s;
516                 if (i == 0)
517                         pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
518                 else
519                         pfd[i].events = POLLIN;
520         }
521
522         set_sched_policy_and_prio(SCHED_FIFO, 99);
523
524 #define SEND()                                          \
525         do {                                            \
526                 ret = send_frame(pfd[0].fd);            \
527                 if (ret != sizeof(struct can_frame))    \
528                         error(1, errno, "send_frame (line %d)", __LINE__); \
529                 count++;                                \
530                 msg_in_progress++;                      \
531         } while (0)
532
533         if (opt.oneattime) {
534                 SEND();
535                 count = 1;
536         }
537
538         while (!finish_flag &&
539                (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
540
541                 get_next_timeout(&timeout);
542                 //printf("ppoll"); fflush(stdout);
543                 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
544                 //printf("=%d\n", ret);
545                 switch (ret) {
546                 case -1: // Error
547                         if (!INTERRUPTED_SYSCALL(errno))
548                                 error(1, errno, "ppoll");
549                         break;
550                 case 0: // Timeout
551                         if (opt.period_us) {
552                                 if (opt.count == 0 || count < opt.count) {
553                                         SEND();
554                                 }
555                         } else {
556                                 error(1, 0, "poll timeout");
557                         }
558                         break;
559                 default: // Event
560                         if (pfd[0].revents & (POLLIN|POLLERR)) {
561                                 process_tx(pfd[0].fd);
562                         }
563                         if (pfd[0].revents & POLLOUT) {
564                                 if (opt.count == 0 || count < opt.count)
565                                         SEND();
566                         }
567                         pfd[0].revents = 0;
568
569                         if (num_interfaces == 3 && pfd[1].revents != 0) {
570                                 process_on_wire_rx(pfd[1].fd);
571                                 pfd[1].revents = 0;
572                         }
573
574                         i = (num_interfaces == 2) ? 1 : 2;
575                         if (pfd[i].revents != 0) {
576                                 process_final_rx(pfd[i].fd);
577                                 msg_in_progress--;
578                                 pfd[i].revents = 0;
579                                 if ((opt.count == 0 || count < opt.count) &&
580                                     opt.oneattime) {
581                                         SEND();
582                                 }
583                         }
584                 }
585         }
586
587         for (i=0; i<num_interfaces; i++)
588                 close(pfd[i].fd);
589
590         return NULL;
591 }
592
593 struct poptOption optionsTable[] = {
594         { "device", 'd', POPT_ARG_ARGV, &opt.interface, 'd', "Interface to use. Must be given two times (tx, rx) or three times (tx, rx1, rx2)", "interface" },
595         { "count",  'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.count,   0,   "The count of messages to send, zero corresponds to infinity", "num"},
596         { "id",     'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.id,      0,   "CAN ID of sent messages", "id"},
597         { "period", 'p', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.period_us, 0, "Period for sending messages or zero (default) to send as fast as possible", "us"},
598         { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
599         { "oneattime",'o', POPT_ARG_NONE,                         &opt.oneattime,0,  "Send the next message only when the previous was finally received"},
600         { "verbose",'v', POPT_ARG_NONE,                           NULL, 'v',         "Send the next message only when the previous was finally received"},
601         { "file",   'f', POPT_ARG_STRING,                         NULL, 'f',         "File where to store results", "filename"},
602         { "histogram", 'h', POPT_ARG_STRING,                      NULL, 'h',         "Store histogram in file", "filename"},
603         { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.length, 0,    "The length of generated messages", "bytes"},
604         { "userhist", 'u', POPT_ARG_NONE,                         &opt.userhist, 0,  "Generate histogram from userspace timestamps"},
605         POPT_AUTOHELP
606         { NULL, 0, 0, NULL, 0 }
607 };
608
609 int parse_options(int argc, const char *argv[])
610 {
611         int c;
612         poptContext optCon;   /* context for parsing command-line options */
613
614         optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
615         //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
616
617         /* Now do options processing */
618         while ((c = poptGetNextOpt(optCon)) >= 0) {
619                 switch (c) {
620                 case 'd':
621                         num_interfaces++;
622                         break;
623                 case 'f':
624                         opt.file = fopen(poptGetOptArg(optCon), "w");
625                         if (!opt.file)
626                                 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
627                         break;
628                 case 'h':
629                         opt.histogram = fopen(poptGetOptArg(optCon), "w");
630                         if (!opt.histogram)
631                                 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
632                         break;
633                 }
634         }
635         if (c < -1)
636                 error(1, 0, "%s: %s\n",
637                       poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
638                       poptStrerror(c));
639
640         if (num_interfaces < 2 || num_interfaces > 3)
641                 error(1, 0, "-d option must be given exactly 2 or 3 times");
642
643         if (opt.oneattime && opt.period_us)
644                 error(1, 0, "oneattime and period cannot be specified at the same time");
645
646         poptFreeContext(optCon);
647
648         return 0;
649 }
650
651
652 int main(int argc, const char *argv[])
653 {
654         pthread_t thread;
655         sigset_t set;
656         int ret, i;
657
658         parse_options(argc, argv);
659
660         mlockall(MCL_CURRENT | MCL_FUTURE);
661
662         signal(SIGINT, term_handler);
663         signal(SIGTERM, term_handler);
664
665         for (i=0; i<MAX_INFOS; i++)
666                 msg_infos[i].id = -1;
667
668         if (opt.histogram) {
669                 histogram_init(&histogram, 5000000, 1);
670         }
671
672         ret = pipe(completion_pipe);
673         if (ret == -1)
674                 error(1, errno, "pipe");
675         ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
676         if (ret == -1)
677                 error(1, errno, "pipe fcntl");
678
679         init_ftrace();
680         
681         pthread_create(&thread, 0, measure_thread, NULL);
682
683         struct timespec next, now, diff;
684         clock_gettime(CLOCK_MONOTONIC, &next);
685         int completed = 0;
686         while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
687                 struct pollfd pfd[1];
688                 pfd[0].fd = completion_pipe[0];
689                 pfd[0].events = POLLIN;
690                 ret = poll(pfd, 1, 100);
691                 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
692                         error(1, errno, "poll main");
693                 if (ret > 0 && (pfd[0].revents & POLLIN)) {
694                         struct msg_info *mi;
695                         int ret;
696                         ret = read(completion_pipe[0], &mi, sizeof(mi));
697                         if (ret < sizeof(mi))
698                                 error(1, errno, "read completion returned %d", ret);
699                         if (opt.file)
700                                 msg_info_print(opt.file, mi);
701                         msg_info_free(mi);
702                         completed++;
703                 }
704
705                 clock_gettime(CLOCK_MONOTONIC, &now);
706                 if (timespec_subtract(&diff, &next, &now)) {
707                         printf("\rMessage %d", count);
708                         fflush(stdout);
709                         next.tv_nsec += 100000000;
710                         while (next.tv_nsec >= 1000000000) {
711                                 next.tv_nsec -= 1000000000;
712                                 next.tv_sec++;
713                         }
714                 }
715         }
716         printf("\rMessage %d\n", count);
717
718         pthread_join(thread, NULL);
719
720         close(completion_pipe[0]);
721         close(completion_pipe[1]);
722
723         if (opt.histogram) {
724                 histogram_fprint(&histogram, opt.histogram);
725                 fclose(opt.histogram);
726         }
727         if (opt.file)
728                 fclose(opt.file);
729
730         return 0;
731 }