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