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