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