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