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