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