]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
bf0eff0f8f4845b001c988347f01ba3ee58889f1
[can-benchmark.git] / latester / latester.c
1 /**************************************************************************/
2 /* CAN latency tester                                                     */
3 /* Copyright (C) 2010, 2011 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         char *name;
63         int length;
64         int userhist;
65         int quiet;
66
67         /* Temporary variables */
68         FILE *f_msgs;
69         FILE *f_hist;
70         FILE *f_stat;
71 };
72
73 struct options opt = {
74         .id = 10,
75         .period_us = 0,
76         .timeout_ms = 1000,
77         .length = 2,
78 };
79
80 struct {
81         unsigned enobufs;
82         unsigned overrun;
83         unsigned lost;
84         struct timespec tic, tac;
85         unsigned timeouts;
86         unsigned invalid_frame;
87 } stats;
88
89 int num_interfaces = 0;
90 int count = 0;                  /* Number of sent messages */
91 unsigned msg_in_progress = 0;
92 int completion_pipe[2];
93
94 struct msg_info {
95         canid_t id;
96         uint8_t length;
97         struct timespec ts_sent, ts_sent_kern;
98         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
99         struct timespec ts_rx_final, ts_rx_final_kern;
100         struct can_frame sent, received;
101 };
102
103 #define MAX_INFOS 10000
104 struct msg_info msg_infos[MAX_INFOS];
105
106 struct histogram histogram;
107
108 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
109         /* documentation see lib.h */
110
111         int i,offset;
112         int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
113
114         if (cf->can_id & CAN_ERR_FLAG) {
115                 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
116                 offset = 9;
117         } else if (cf->can_id & CAN_EFF_FLAG) {
118                 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
119                 offset = 9;
120         } else {
121                 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
122                 offset = 4;
123         }
124
125         if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
126                 sprintf(buf+offset, "R");
127         else
128                 for (i = 0; i < dlc; i++) {
129                         sprintf(buf+offset, "%02X", cf->data[i]);
130                         offset += 2;
131                         if (sep && (i+1 < dlc))
132                                 sprintf(buf+offset++, ".");
133                 }
134 }
135
136 static inline uint16_t frame_index(struct can_frame *frame)
137 {
138         uint16_t idx;
139         if (frame->can_dlc >= 2) {
140                 memcpy(&idx, frame->data, sizeof(idx));
141                 if (idx >= MAX_INFOS)
142                         error(1, 0, "%s idx too high", __FUNCTION__);
143         } else {
144
145                 error(1, 0, "%s error", __FUNCTION__);
146         }
147         return idx;
148 }
149
150 static inline struct msg_info *frame2info(struct can_frame *frame)
151 {
152         return &msg_infos[frame_index(frame)];
153 }
154
155 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
156 {
157         return talloc_asprintf(ctx, "%ld.%06ld",
158                                tstamp->tv_sec, tstamp->tv_nsec/1000);
159 }
160
161 unsigned calc_stuff_bits(struct can_frame *frame) {
162         uint32_t bitmap[4];
163         unsigned start = 0, end;
164         uint32_t mask, ones = 0, basemask = 0xf0000000;
165         unsigned stuffed = 0;
166         memset(bitmap, 0, sizeof(bitmap));
167
168         if (frame->can_id & CAN_EFF_FLAG) {
169                 bitmap[0] =
170                         (frame->can_id >> 25);
171                 bitmap[1] =
172                         (frame->can_id >> 18) << 25             |
173                         3 << 23                                 |
174                         (frame->can_id & 0x3ffff) << 7          |
175                         (!!(frame->can_id & CAN_RTR_FLAG)) << 6 |
176                         0 << 4                                  |
177                         frame->can_dlc & 0xf;
178                 bitmap[2] = htonl(((uint32_t*)frame->data)[0]);
179                 bitmap[3] = htonl(((uint32_t*)frame->data)[1]);
180                 start = 28;
181                 end = 64 + 8*frame->can_dlc;
182         } else {
183                 bitmap[0] =
184                         (frame->can_id << 7) |
185                         (!!(frame->can_id & CAN_RTR_FLAG)) << 6 |
186                         0 << 4                                  |
187                         frame->can_dlc & 0xf;
188                 bitmap[1] = htonl(((uint32_t*)frame->data)[0]);
189                 bitmap[2] = htonl(((uint32_t*)frame->data)[1]);
190                 start = 14;
191                 end = 32 + 8*frame->can_dlc;
192         }
193         /* TODO: Calc stuff bits in CRC */
194         while (start < end) {
195                 mask = basemask >> (start & 0x1f);
196                 while (1) {
197                         ones = ones ? mask : 0;
198                         uint32_t chunk = (bitmap[start >> 5] & mask) ^ ones;
199                         //printf("start=%d  bitmap=0x%08x  mask=0x%08x  ones=0x%08x  chunk=0x%08x\n", start, bitmap[start >> 5], mask, ones, chunk);
200                         if (chunk) {
201                                 unsigned change = __builtin_clz(chunk);
202                                 start = start & ~0x1f | change;
203                                 basemask = 0xf8000000;
204                         } else {
205                                 unsigned oldstart = start;
206                                 start += __builtin_popcount(mask);
207                                 mask = (oldstart & 0x1f) ? basemask << (-oldstart & 0x1f) : 0;
208                                 //printf("oldstart=%d  shl=%d  mask=0x%08x\n", oldstart, -oldstart & 0x1f, mask);
209                                 if (mask && start < end)
210                                         continue;
211                                 if (start <= end && !mask) {
212                                         stuffed++;
213                                         basemask = 0xf0000000;
214                                         printf("stuffed %d\n", !ones);
215                                 }
216                         }
217                         break;
218                 }
219                 ones = !ones;
220         }
221         printf ("STUFFED %d BITS\n", stuffed);
222 }
223
224 unsigned calc_frame_txtime(struct can_frame *frame) {
225         return calc_stuff_bits(frame) +
226                 1 +             /* SOF */
227                 11 +            /* ID A */
228                 ((frame->can_id & CAN_EFF_FLAG) ?
229                  1 +            /* SRR */
230                  1 +            /* IDE */
231                  18 +           /* ID B */
232                  1 +            /* RTR */
233                  2              /* r1, r0 */
234                  :
235                  1 +            /* rtr */
236                  2) +           /* ide, r0 */
237                 4 +             /* dlc */
238                 8*frame->can_dlc +
239                 15 +            /* CRC */
240                 3 +             /* CRC del, ACK, ACK del */
241                 7;              /* EOF */
242 }
243
244 void msg_info_print(FILE *f, struct msg_info *mi)
245 {
246         struct timespec diff;
247         void *local = talloc_new (NULL);
248         static long num = 0;
249         char sent[64], received[64];
250
251         sprint_canframe(sent, &mi->sent, true);
252         sprint_canframe(received, &mi->received, true);
253
254 #define S(ts) tstamp_str(local, &ts)
255 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
256
257         switch (num_interfaces) {
258         case 2:
259                 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s) %d\n",
260                         num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
261                         DIFF(mi->ts_sent, mi->ts_rx_final_kern),
262                         DIFF(mi->ts_sent, mi->ts_rx_final),
263                         calc_frame_txtime(mi->received));
264                 break;
265         case 3:
266                 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s) %d\n",
267                         num, S(mi->ts_sent), sent,
268                         S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
269                         S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
270                         DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
271                         DIFF(mi->ts_sent, mi->ts_rx_onwire),
272                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
273                         DIFF(mi->ts_rx_onwire, mi->ts_rx_final),
274                         calc_frame_txtime(mi->received));
275                 break;
276         }
277 #undef S
278 #undef DIFF
279         num++;
280         talloc_free (local);
281 }
282
283 /* Subtract the `struct timespec' values X and Y, storing the result in
284    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
285
286 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
287 {
288         struct timespec ylocal = *yy, *y = &ylocal;
289         /* Perform the carry for the later subtraction by updating Y. */
290         if (x->tv_nsec < y->tv_nsec) {
291                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
292                 y->tv_nsec -= 1000000000 * nsec;
293                 y->tv_sec += nsec;
294         }
295         if (x->tv_nsec - y->tv_nsec > 1000000000) {
296                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
297                 y->tv_nsec += 1000000000 * nsec;
298                 y->tv_sec -= nsec;
299         }
300
301         /* Compute the time remaining to wait.
302            `tv_nsec' is certainly positive. */
303         result->tv_sec = x->tv_sec - y->tv_sec;
304         result->tv_nsec = x->tv_nsec - y->tv_nsec;
305
306         /* Return 1 if result is negative. */
307         return x->tv_sec < y->tv_sec;
308 }
309
310 void dbg_print_timespec(char *msg, struct timespec *tv)
311 {
312
313         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
314 }
315
316 static inline unsigned get_msg_latency_us(struct msg_info *mi)
317 {
318         struct timespec diff;
319         switch (num_interfaces) {
320         case 3:
321                 if (opt.userhist)
322                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
323                 else
324                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
325                 break;
326         case 2:
327                 if (opt.userhist)
328                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
329                 else
330                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
331                 break;
332         default:
333                 return 0;
334         }
335         return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
336 }
337
338 void set_sched_policy_and_prio(int policy, int rtprio)
339 {
340         struct sched_param scheduling_parameters;
341         int maxprio=sched_get_priority_max(policy);
342         int minprio=sched_get_priority_min(policy);
343
344         if((rtprio < minprio) || (rtprio > maxprio))
345                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
346                       minprio, maxprio);
347
348         scheduling_parameters.sched_priority = rtprio;
349
350         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
351                 error(1, errno, "pthread_setschedparam error");
352 }
353
354 void term_handler(int signum)
355 {
356         finish_flag = 1;
357 }
358
359 static inline int sock_get_if_index(int s, const char *if_name)
360 {
361         struct ifreq ifr;
362         MEMSET_ZERO(ifr);
363
364         strcpy(ifr.ifr_name, if_name);
365         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
366                 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
367         return ifr.ifr_ifindex;
368 }
369
370 static inline get_tstamp(struct timespec *ts)
371 {
372         clock_gettime(CLOCK_REALTIME, ts);
373 }
374
375
376 int trace_fd = -1;
377 int marker_fd = -1;
378
379 int init_ftrace()
380 {
381 #ifdef FTRACE
382         char *debugfs;
383         char path[256];
384         FILE *f;
385
386         debugfs = "/sys/kernel/debug";
387         if (debugfs) {
388                 strcpy(path, debugfs);
389                 strcat(path,"/tracing/tracing_on");
390                 trace_fd = open(path, O_WRONLY);
391                 if (trace_fd >= 0)
392                         write(trace_fd, "1", 1);
393
394                 strcpy(path, debugfs);
395                 strcat(path,"/tracing/trace_marker");
396                 marker_fd = open(path, O_WRONLY);
397
398                 strcpy(path, debugfs);
399                 strcat(path,"/tracing/set_ftrace_pid");
400                 f = fopen(path, "w");
401                 fprintf(f, "%d\n", getpid());
402                 fclose(f);
403                 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
404                 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
405                 system("echo > /sys/kernel/debug/tracing/trace");
406                 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
407         }
408 #endif  /* FTRACE */
409 }
410
411 static inline void trace_on()
412 {
413         if (trace_fd >= 0)
414                 write(trace_fd, "1", 1);
415 }
416
417 static inline void trace_off(int ret)
418 {
419         if (marker_fd >= 0) {
420                 char marker[100];
421                 sprintf(marker, "write returned %d\n", ret);
422                 write(marker_fd, marker, strlen(marker));
423         }
424         if (trace_fd >= 0)
425                 write(trace_fd, "0", 1);
426 }
427
428 static inline void msg_info_free(struct msg_info *mi)
429 {
430         mi->id = -1;
431 }
432
433 static inline bool msg_info_used(struct msg_info *mi)
434 {
435         return mi->id != -1;
436 }
437
438 int send_frame(int socket)
439 {
440         struct can_frame frame;
441         struct msg_info *mi;
442         int ret;
443         static int curr_msg = -1;
444         int i;
445         uint16_t idx;
446
447         MEMSET_ZERO(frame);
448         i = curr_msg+1;
449         while (msg_info_used(&msg_infos[i]) && i != curr_msg) {
450                 i++;
451                 if (i >= MAX_INFOS)
452                         i = 0;
453         }
454         if (i == curr_msg)
455                 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
456         else
457                 curr_msg = i;
458
459         frame.can_id = opt.id;
460         if (opt.length < 2)
461                 error(1, 0, "Length < 2 is not yet supported");
462         frame.can_dlc = opt.length;
463         idx = curr_msg;
464         memcpy(frame.data, &idx, sizeof(idx));
465         mi = frame2info(&frame);
466
467         mi->id = frame.can_id;
468         mi->length = frame.can_dlc;
469         get_tstamp(&mi->ts_sent);
470         mi->sent = frame;
471
472         trace_on();
473         ret = write(socket, &frame, sizeof(frame));
474         trace_off(ret);
475
476         if (ret == -1 || num_interfaces == 1)
477                 msg_info_free(mi);
478         return ret;
479 }
480
481 static inline send_and_check(int s)
482 {
483         int ret;
484         ret = send_frame(s);
485         if (ret != sizeof(struct can_frame)) {
486 /*              if (ret == -1 && errno == ENOBUFS && opt.period_us == 0 && !opt.oneattime) { */
487 /*                      stats.enobufs++; */
488 /*                      /\* Ignore this error - pfifo_fast qeuue is full *\/ */
489 /*              } else */
490                         error(1, errno, "send_frame (line %d)", __LINE__);
491         } else {
492                 count++;
493                 msg_in_progress++;
494         }
495 }
496
497 static inline void get_next_timeout(struct timespec *timeout)
498 {
499         struct timespec now;
500         static struct timespec last = {-1, 0 };
501
502         clock_gettime(CLOCK_MONOTONIC, &now);
503
504         if (last.tv_sec == -1)
505                 last = now;
506         if (opt.period_us != 0) {
507                 last.tv_sec += opt.period_us/1000000;
508                 last.tv_nsec += (opt.period_us%1000000)*1000;
509                 while (last.tv_nsec >= 1000000000) {
510                         last.tv_nsec -= 1000000000;
511                         last.tv_sec++;
512                 }
513                 if (timespec_subtract(timeout, &last, &now) /* is negative */) {
514                         stats.overrun++;
515                         memset(timeout, 0, sizeof(*timeout));
516                 }
517         } else if (opt.timeout_ms != 0) {
518                 timeout->tv_sec = opt.timeout_ms/1000;
519                 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
520         } else
521                 error(1, 0, "Timeout and period cannot be both zero");
522 }
523
524 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
525 {
526         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
527         struct iovec iov;
528         struct msghdr msg;
529         struct cmsghdr *cmsg;
530         struct sockaddr_can addr;
531         int nbytes;
532         static uint64_t dropcnt = 0;
533
534         iov.iov_base = frame;
535         msg.msg_name = &addr;
536         msg.msg_iov = &iov;
537         msg.msg_iovlen = 1;
538         msg.msg_control = &ctrlmsg;
539
540         /* these settings may be modified by recvmsg() */
541         iov.iov_len = sizeof(*frame);
542         msg.msg_namelen = sizeof(addr);
543         msg.msg_controllen = sizeof(ctrlmsg);
544         msg.msg_flags = 0;
545
546         nbytes = recvmsg(s, &msg, 0);
547         if (nbytes < 0)
548                 error(1, errno, "recvmsg");
549
550         if (nbytes < sizeof(struct can_frame))
551                 error(1, 0, "recvmsg: incomplete CAN frame\n");
552
553         get_tstamp(ts_user);
554         MEMSET_ZERO(*ts_kern);
555         for (cmsg = CMSG_FIRSTHDR(&msg);
556              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
557              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
558                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
559                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
560                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
561                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
562         }
563
564 }
565
566 void process_tx(int s)
567 {
568         error(1, 0, "%s: not implemented", __FUNCTION__);
569 }
570
571 void process_on_wire_rx(int s)
572 {
573         struct timespec ts_kern, ts_user, ts_diff;
574         struct can_frame frame;
575         struct msg_info *mi;
576         receive(s, &frame, &ts_kern, &ts_user);
577         mi = frame2info(&frame);
578         if (msg_info_used(mi)) {
579                 mi->ts_rx_onwire_kern = ts_kern;
580                 mi->ts_rx_onwire = ts_user;
581         } else
582                 stats.invalid_frame++;
583 }
584
585
586 void process_final_rx(int s)
587 {
588         struct timespec ts_kern, ts_user, ts_diff;
589         struct can_frame frame;
590         struct msg_info *mi;
591         int ret;
592
593         receive(s, &frame, &ts_kern, &ts_user);
594         mi = frame2info(&frame);
595         mi->ts_rx_final_kern = ts_kern;
596         mi->ts_rx_final = ts_user;
597         mi->received = frame;
598
599         histogram_add(&histogram, get_msg_latency_us(mi));
600
601         ret = write(completion_pipe[1], &mi, sizeof(mi));
602         if (ret == -1)
603                 error(1, errno, "completion_pipe write");
604 }
605
606 void *measure_thread(void *arg)
607 {
608         int s, i, ret;
609         struct pollfd pfd[3];
610         struct timespec timeout;
611         struct sockaddr_can addr;
612         sigset_t set;
613         int consecutive_timeouts = 0;
614
615         MEMSET_ZERO(pfd);
616
617         for (i=0; i<num_interfaces; i++) {
618                 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
619                         error(1, errno, "socket");
620
621                 addr.can_family = AF_CAN;
622                 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
623
624                 if (i == 0) {   /* TX socket */
625                         /* disable default receive filter on this RAW socket */
626                         /* This is obsolete as we do not read from the socket at all, but for */
627                         /* this reason we can remove the receive list in the Kernel to save a */
628                         /* little (really a very little!) CPU usage.                          */
629                         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
630                                 error(1, errno, "SOL_CAN_RAW");
631                 }
632
633                 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
634                         error(1, errno, "bind");
635
636                 const int timestamp_on = 1;
637                 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
638                                &timestamp_on, sizeof(timestamp_on)) < 0)
639                         error(1, errno, "setsockopt SO_TIMESTAMP");
640
641                 const int dropmonitor_on = 1;
642                 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
643                                &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
644                         error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
645
646                 pfd[i].fd = s;
647                 if (i == 0)
648                         pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
649                 else
650                         pfd[i].events = POLLIN;
651         }
652
653         set_sched_policy_and_prio(SCHED_FIFO, 40);
654
655 #define SEND() send_and_check(pfd[0].fd)
656
657         if (opt.oneattime)
658                 SEND();
659
660         get_tstamp(&stats.tic);
661
662         while (!finish_flag &&
663                (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
664
665                 get_next_timeout(&timeout);
666                 //printf("ppoll"); fflush(stdout);
667                 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
668                 //printf("=%d\n", ret);
669                 switch (ret) {
670                 case -1: // Error
671                         if (!INTERRUPTED_SYSCALL(errno))
672                                 error(1, errno, "ppoll");
673                         break;
674                 case 0: // Timeout
675                         if (opt.period_us) {
676                                 if (opt.count == 0 || count < opt.count) {
677                                         SEND();
678                                 }
679                         } else {
680                                 /* Lost message - send a new one */
681                                 stats.timeouts++;
682                                 consecutive_timeouts++;
683                                 if (consecutive_timeouts < 10)
684                                         SEND();
685                                 else /* Something is really broken */
686                                         finish_flag = 1;
687                         }
688                         break;
689                 default: // Event
690                         if (pfd[0].revents & (POLLIN|POLLERR)) {
691                                 process_tx(pfd[0].fd);
692                         }
693                         if (pfd[0].revents & POLLOUT) {
694                                 if (opt.count == 0 || count < opt.count)
695                                         SEND();
696                         }
697                         pfd[0].revents = 0;
698
699                         if (num_interfaces == 3 && pfd[1].revents & POLLIN) {
700                                 process_on_wire_rx(pfd[1].fd);
701                                 pfd[1].revents = 0;
702                         }
703                         if (num_interfaces == 3 && pfd[1].revents & ~POLLIN)
704                                 error(1, 0, "Unexpected pfd[1].revents: 0x%04x\n", pfd[1].revents);
705
706                         i = (num_interfaces == 2) ? 1 : 2;
707                         if (pfd[i].revents & POLLIN) {
708                                 consecutive_timeouts = 0;
709                                 process_final_rx(pfd[i].fd);
710                                 msg_in_progress--;
711                                 pfd[i].revents = 0;
712                                 if ((opt.count == 0 || count < opt.count) &&
713                                     opt.oneattime) {
714                                         SEND();
715                                 }
716                         }
717                         if (pfd[i].revents & ~POLLIN)
718                                 error(1, 0, "Unexpected pfd[%d].revents: 0x%04x\n", pfd[i].revents);
719                 }
720         }
721
722         get_tstamp(&stats.tac);
723
724         for (i=0; i<num_interfaces; i++)
725                 close(pfd[i].fd);
726
727         return NULL;
728 }
729
730 struct poptOption optionsTable[] = {
731         { "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" },
732         { "count",  'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.count,   0,   "The count of messages to send, zero corresponds to infinity", "num"},
733         { "id",     'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.id,      0,   "CAN ID of sent messages", "id"},
734         { "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"},
735         { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
736         { "oneattime",'o', POPT_ARG_NONE,                         &opt.oneattime,0,  "Send the next message only when the previous was finally received"},
737         { "verbose",'v', POPT_ARG_NONE,                           NULL, 'v',         "Send the next message only when the previous was finally received"},
738         { "name",   'n', POPT_ARG_STRING,                         &opt.name, 0,      "Prefix of the generated files"},
739         { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.length, 0,    "The length of generated messages", "bytes"},
740         { "userhist", 'u', POPT_ARG_NONE,                         &opt.userhist, 0,  "Generate histogram from userspace timestamps"},
741         { "quiet",  'q', POPT_ARG_NONE,                           &opt.quiet, 0,     "Do not print progress and statistics"},
742         POPT_AUTOHELP
743         { NULL, 0, 0, NULL, 0 }
744 };
745
746 int parse_options(int argc, const char *argv[])
747 {
748         int c;
749         poptContext optCon;   /* context for parsing command-line options */
750         void *local = talloc_new (NULL);
751
752         optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
753         //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
754
755         /* Now do options processing */
756         while ((c = poptGetNextOpt(optCon)) >= 0) {
757                 switch (c) {
758                 case 'd':
759                         num_interfaces++;
760                         break;
761                 }
762         }
763         if (c < -1)
764                 error(1, 0, "%s: %s\n",
765                       poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
766                       poptStrerror(c));
767
768         if (num_interfaces < 1 || num_interfaces > 3)
769                 error(1, 0, "-d option must only be given one, two or three times");
770
771         if (opt.oneattime && opt.period_us)
772                 error(1, 0, "oneattime and period cannot be specified at the same time");
773
774         if (opt.name) {
775                 char *f = talloc_asprintf(local, "%s-msgs.txt", opt.name);
776                 opt.f_msgs = fopen(f, "w");
777                 if (!opt.f_msgs)
778                         error(1, errno, "fopen: %s", f);
779         }
780
781         if (opt.name) {
782                 char *f = talloc_asprintf(local, "%s-hist.txt", opt.name);
783                 opt.f_hist = fopen(f, "w");
784                 if (!opt.f_hist)
785                         error(1, errno, "fopen: %s", f);
786         }
787
788         if (opt.name) {
789                 char *f = talloc_asprintf(local, "%s-stat.txt", opt.name);
790                 opt.f_stat = fopen(f, "w");
791                 if (!opt.f_stat)
792                         error(1, errno, "fopen: %s", f);
793         }
794
795         poptFreeContext(optCon);
796         talloc_free(local);
797         return 0;
798 }
799
800 void print_progress()
801 {
802         if (! opt.quiet) {
803                 if (num_interfaces > 1)
804                         printf("\rSent %5d, in progress %5d", count, msg_in_progress);
805                 else
806                         printf("\rSent %5d", count);
807                 fflush(stdout);
808         }
809 }
810
811 int main(int argc, const char *argv[])
812 {
813         pthread_t thread;
814         sigset_t set;
815         int ret, i;
816
817         parse_options(argc, argv);
818
819         mlockall(MCL_CURRENT | MCL_FUTURE);
820
821         signal(SIGINT, term_handler);
822         signal(SIGTERM, term_handler);
823
824         for (i=0; i<MAX_INFOS; i++)
825                 msg_infos[i].id = -1;
826
827         histogram_init(&histogram, 5000000, 1);
828
829         ret = pipe(completion_pipe);
830         if (ret == -1)
831                 error(1, errno, "pipe");
832         ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
833         if (ret == -1)
834                 error(1, errno, "pipe fcntl");
835
836         init_ftrace();
837
838         pthread_create(&thread, 0, measure_thread, NULL);
839
840         struct timespec next, now, diff, allsent = {0,0};
841         clock_gettime(CLOCK_MONOTONIC, &next);
842         int completed = 0;
843         while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
844                 struct pollfd pfd[1];
845                 pfd[0].fd = completion_pipe[0];
846                 pfd[0].events = POLLIN;
847                 ret = poll(pfd, 1, 100);
848                 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
849                         error(1, errno, "poll main");
850                 if (ret > 0 && (pfd[0].revents & POLLIN)) {
851                         struct msg_info *mi;
852                         int ret;
853                         ret = read(completion_pipe[0], &mi, sizeof(mi));
854                         if (ret < sizeof(mi))
855                                 error(1, errno, "read completion returned %d", ret);
856                         msg_info_print(opt.f_msgs, mi);
857                         msg_info_free(mi);
858                         completed++;
859                 }
860
861                 clock_gettime(CLOCK_MONOTONIC, &now);
862                 if (timespec_subtract(&diff, &next, &now)) {
863                         print_progress();
864                         next.tv_nsec += 100000000;
865                         while (next.tv_nsec >= 1000000000) {
866                                 next.tv_nsec -= 1000000000;
867                                 next.tv_sec++;
868                         }
869                 }
870                 if (opt.count != 0 && count >= opt.count) {
871                         if (allsent.tv_sec == 0)
872                                 allsent = now;
873                         timespec_subtract(&diff, &now, &allsent);
874                         if (diff.tv_sec >= 1)
875                                 finish_flag = 1;
876                 }
877         }
878         print_progress();
879         if (!opt.quiet)
880                 printf("\n");
881
882         stats.lost = msg_in_progress;
883
884         pthread_join(thread, NULL);
885
886         close(completion_pipe[0]);
887         close(completion_pipe[1]);
888
889         histogram_fprint(&histogram, opt.f_hist);
890         fclose(opt.f_hist);
891         fclose(opt.f_msgs);
892
893
894         fprintf(opt.f_stat, "cmdline='");
895         for (i=0; i<argc; i++)
896                 fprintf(opt.f_stat, "%s%s", argv[i], i < argc-1 ? " " : "");
897         fprintf(opt.f_stat, "'\n");
898
899         timespec_subtract(&diff, &stats.tac, &stats.tic);
900         fprintf(opt.f_stat, "duration=%s # seconds\n", tstamp_str(NULL, &diff));
901         
902         fprintf(opt.f_stat, "sent=%d\n", count);
903         fprintf(opt.f_stat, "overrun=%d\n", stats.overrun);
904         if (stats.overrun && !opt.quiet)
905                 printf("overrun=%d\n", stats.overrun);
906         fprintf(opt.f_stat, "enobufs=%d\n", stats.enobufs);
907         if (stats.enobufs && !opt.quiet)
908                 printf("enobufs=%d\n", stats.enobufs);
909         fprintf(opt.f_stat, "lost=%d\n", stats.lost);
910         if (stats.lost && !opt.quiet)
911                 printf("lost=%d\n", stats.lost);
912         fprintf(opt.f_stat, "timeouts=%d\n", stats.timeouts);
913         if (stats.timeouts && !opt.quiet)
914                 printf("timeouts=%d\n", stats.timeouts);
915         fprintf(opt.f_stat, "invalid_frame=%d\n", stats.timeouts);
916         if (stats.timeouts && !opt.quiet)
917                 printf("invalid_frame=%d\n", stats.timeouts);
918
919         fclose(opt.f_stat);
920
921         return 0;
922 }