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