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