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