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