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