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