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