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