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