]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
More appropriate graph titles
[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 int completion_pipe[2];
83
84 struct msg_info {
85         canid_t id;
86         uint8_t length;
87         struct timespec ts_sent, ts_sent_kern;
88         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
89         struct timespec ts_rx_final, ts_rx_final_kern;
90         struct can_frame sent, received;
91 };
92
93 #define MAX_INFOS 10000
94 struct msg_info msg_infos[MAX_INFOS];
95
96 struct histogram histogram;
97
98 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
99         /* documentation see lib.h */
100
101         int i,offset;
102         int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
103
104         if (cf->can_id & CAN_ERR_FLAG) {
105                 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
106                 offset = 9;
107         } else if (cf->can_id & CAN_EFF_FLAG) {
108                 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
109                 offset = 9;
110         } else {
111                 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
112                 offset = 4;
113         }
114
115         if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
116                 sprintf(buf+offset, "R");
117         else
118                 for (i = 0; i < dlc; i++) {
119                         sprintf(buf+offset, "%02X", cf->data[i]);
120                         offset += 2;
121                         if (sep && (i+1 < dlc))
122                                 sprintf(buf+offset++, ".");
123                 }
124 }
125
126 static inline struct msg_info *frame2info(struct can_frame *frame)
127 {
128         uint16_t idx;
129         if (frame->can_dlc >= 2) {
130                 memcpy(&idx, frame->data, sizeof(idx));
131                 if (idx >= MAX_INFOS)
132                         error(1, 0, "%s idx too high", __FUNCTION__);
133         } else {
134                 
135                 error(1, 0, "%s error", __FUNCTION__);
136         }
137         return &msg_infos[idx];
138 }
139
140 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
141 {
142         return talloc_asprintf(ctx, "%ld.%06ld",
143                                tstamp->tv_sec, tstamp->tv_nsec/1000);
144 }
145
146 void msg_info_print(FILE *f, struct msg_info *mi)
147 {
148         struct timespec diff;
149         void *local = talloc_new (NULL);
150         static long num = 0;
151         char sent[64], received[64];
152
153         sprint_canframe(sent, &mi->sent, true);
154         sprint_canframe(received, &mi->received, true);
155
156 #define S(ts) tstamp_str(local, &ts)
157 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
158
159         if (num_interfaces == 2)
160                 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s)\n",
161                         num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
162                        DIFF(mi->ts_sent, mi->ts_rx_final_kern),
163                        DIFF(mi->ts_sent, mi->ts_rx_final));
164         else
165                 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s)\n",
166                         num, S(mi->ts_sent), sent,
167                         S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
168                         S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
169                         DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
170                         DIFF(mi->ts_sent, mi->ts_rx_onwire),
171                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
172                         DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
173 #undef S
174 #undef DIFF
175         num++;
176         talloc_free (local);
177 }
178
179 int msg_info_store(FILE *f, struct msg_info *mi)
180 {
181         struct timespec diff;
182         void *local = talloc_new (NULL);
183         static long num = 0;
184
185 #define S(ts) tstamp_str(local, &ts)
186 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
187
188         if (num_interfaces == 2)
189                 fprintf(f, "%ld %d %d %s\n",
190                         num, mi->id, mi->length,
191                         DIFF(mi->ts_sent, mi->ts_rx_final_kern));
192         else
193                 fprintf(f, "%ld %d %d %s\n",
194                         num, mi->id, mi->length,
195                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
196 #undef S
197 #undef DIFF
198         talloc_free (local);
199 }
200
201
202 /* Subtract the `struct timespec' values X and Y, storing the result in
203    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
204
205 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
206 {
207         struct timespec ylocal = *yy, *y = &ylocal;
208         /* Perform the carry for the later subtraction by updating Y. */
209         if (x->tv_nsec < y->tv_nsec) {
210                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
211                 y->tv_nsec -= 1000000000 * nsec;
212                 y->tv_sec += nsec;
213         }
214         if (x->tv_nsec - y->tv_nsec > 1000000000) {
215                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
216                 y->tv_nsec += 1000000000 * nsec;
217                 y->tv_sec -= nsec;
218         }
219
220         /* Compute the time remaining to wait.
221            `tv_nsec' is certainly positive. */
222         result->tv_sec = x->tv_sec - y->tv_sec;
223         result->tv_nsec = x->tv_nsec - y->tv_nsec;
224
225         /* Return 1 if result is negative. */
226         return x->tv_sec < y->tv_sec;
227 }
228
229 void dbg_print_timespec(char *msg, struct timespec *tv)
230 {
231
232         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
233 }
234
235 static inline unsigned get_msg_latency_us(struct msg_info *mi)
236 {
237         struct timespec diff;
238         if (num_interfaces == 3)
239                 if (opt.userhist)
240                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
241                 else
242                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
243         else
244                 if (opt.userhist)
245                         timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
246                 else
247                         timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
248         return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
249 }
250
251 void set_sched_policy_and_prio(int policy, int rtprio)
252 {
253         struct sched_param scheduling_parameters;
254         int maxprio=sched_get_priority_max(policy);
255         int minprio=sched_get_priority_min(policy);
256
257         if((rtprio < minprio) || (rtprio > maxprio))
258                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
259                       minprio, maxprio);
260
261         scheduling_parameters.sched_priority = rtprio;
262
263         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
264                 error(1, errno, "pthread_setschedparam error");
265 }
266
267 void term_handler(int signum)
268 {
269         finish_flag = 1;
270 }
271
272 static inline int sock_get_if_index(int s, const char *if_name)
273 {
274         struct ifreq ifr;
275         MEMSET_ZERO(ifr);
276
277         strcpy(ifr.ifr_name, if_name);
278         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
279                 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
280         return ifr.ifr_ifindex;
281 }
282
283 static inline get_tstamp(struct timespec *ts)
284 {
285         clock_gettime(CLOCK_REALTIME, ts);
286 }
287
288
289 int trace_fd = -1;
290 int marker_fd = -1;
291
292 int init_ftrace()
293 {
294 #ifdef FTRACE
295         char *debugfs;
296         char path[256];
297         FILE *f;
298         
299         debugfs = "/sys/kernel/debug";
300         if (debugfs) {
301                 strcpy(path, debugfs);
302                 strcat(path,"/tracing/tracing_on");
303                 trace_fd = open(path, O_WRONLY);
304                 if (trace_fd >= 0)
305                         write(trace_fd, "1", 1);
306
307                 strcpy(path, debugfs);
308                 strcat(path,"/tracing/trace_marker");
309                 marker_fd = open(path, O_WRONLY);
310
311                 strcpy(path, debugfs);
312                 strcat(path,"/tracing/set_ftrace_pid");
313                 f = fopen(path, "w");
314                 fprintf(f, "%d\n", getpid());
315                 fclose(f);
316                 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
317                 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
318                 system("echo > /sys/kernel/debug/tracing/trace");
319                 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
320         }
321 #endif  /* FTRACE */
322 }
323
324 static inline void trace_on()
325 {
326         if (trace_fd >= 0)
327                 write(trace_fd, "1", 1);
328 }
329
330 static inline void trace_off(int ret)
331 {
332         if (marker_fd >= 0) {
333                 char marker[100];
334                 sprintf(marker, "write returned %d\n", ret);
335                 write(marker_fd, marker, strlen(marker));
336         }
337         if (trace_fd >= 0)
338                 write(trace_fd, "0", 1);
339 }
340
341 void msg_info_free(struct msg_info *mi)
342 {
343         mi->id = -1;
344 }
345
346 int send_frame(int socket)
347 {
348         struct can_frame frame;
349         struct msg_info *mi;
350         int ret;
351         static int curr_msg = -1;
352         int i;
353         uint16_t idx;
354
355         MEMSET_ZERO(frame);
356         i = curr_msg+1;
357         while (msg_infos[i].id != -1 && i != curr_msg) {
358                 i++;
359                 if (i >= MAX_INFOS)
360                         i = 0;
361         }
362         if (i == curr_msg)
363                 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
364         else
365                 curr_msg = i;
366
367         frame.can_id = opt.id;
368         if (opt.length < 2)
369                 error(1, 0, "Length < 2 is not yet supported");
370         frame.can_dlc = opt.length;
371         idx = curr_msg;
372         memcpy(frame.data, &idx, sizeof(idx));
373         mi = frame2info(&frame);
374
375         mi->id = frame.can_id;
376         mi->length = frame.can_dlc;
377         get_tstamp(&mi->ts_sent);
378         mi->sent = frame;
379         
380         trace_on();
381         ret = write(socket, &frame, sizeof(frame));
382         trace_off(ret);
383
384         if (ret == -1)
385                 msg_info_free(mi);
386         return ret;
387 }
388
389 static inline void get_next_timeout(struct timespec *timeout)
390 {
391         struct timespec now;
392         static struct timespec last = {-1, 0 };
393
394         clock_gettime(CLOCK_MONOTONIC, &now);
395
396         if (last.tv_sec == -1)
397                 last = now;
398         if (opt.period_us != 0) {
399                 last.tv_sec += opt.period_us/1000000;
400                 last.tv_nsec += (opt.period_us%1000000)*1000;
401                 while (last.tv_nsec >= 1000000000) {
402                         last.tv_nsec -= 1000000000;
403                         last.tv_sec++;
404                 }
405                 if (timespec_subtract(timeout, &last, &now) /* is negative */) {
406                         stats.overrun++;
407                         memset(timeout, 0, sizeof(*timeout));
408                 }
409         } else if (opt.timeout_ms != 0) {
410                 timeout->tv_sec = opt.timeout_ms/1000;
411                 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
412         } else
413                 error(1, 0, "Timeout and period cannot be both zero");
414 }
415
416 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
417 {
418         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
419         struct iovec iov;
420         struct msghdr msg;
421         struct cmsghdr *cmsg;
422         struct sockaddr_can addr;
423         int nbytes;
424         static uint64_t dropcnt = 0;
425
426         iov.iov_base = frame;
427         msg.msg_name = &addr;
428         msg.msg_iov = &iov;
429         msg.msg_iovlen = 1;
430         msg.msg_control = &ctrlmsg;
431
432         /* these settings may be modified by recvmsg() */
433         iov.iov_len = sizeof(*frame);
434         msg.msg_namelen = sizeof(addr);
435         msg.msg_controllen = sizeof(ctrlmsg);
436         msg.msg_flags = 0;
437
438         nbytes = recvmsg(s, &msg, 0);
439         if (nbytes < 0)
440                 error(1, errno, "recvmsg");
441
442         if (nbytes < sizeof(struct can_frame))
443                 error(1, 0, "recvmsg: incomplete CAN frame\n");
444
445         get_tstamp(ts_user);
446         MEMSET_ZERO(*ts_kern);
447         for (cmsg = CMSG_FIRSTHDR(&msg);
448              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
449              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
450                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
451                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
452                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
453                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
454         }
455
456 }
457
458 void process_tx(int s)
459 {
460         error(1, 0, "%s: not implemented", __FUNCTION__);
461 }
462
463 void process_on_wire_rx(int s)
464 {
465         struct timespec ts_kern, ts_user, ts_diff;
466         struct can_frame frame;
467         struct msg_info *mi;
468         receive(s, &frame, &ts_kern, &ts_user);
469         mi = frame2info(&frame);
470         mi->ts_rx_onwire_kern = ts_kern;
471         mi->ts_rx_onwire = ts_user;
472 }
473
474
475 void process_final_rx(int s)
476 {
477         struct timespec ts_kern, ts_user, ts_diff;
478         struct can_frame frame;
479         struct msg_info *mi;
480         int ret;
481         
482         receive(s, &frame, &ts_kern, &ts_user);
483         mi = frame2info(&frame);
484         mi->ts_rx_final_kern = ts_kern;
485         mi->ts_rx_final = ts_user;
486         mi->received = frame;
487
488         if (opt.histogram)
489                 histogram_add(&histogram, get_msg_latency_us(mi));
490
491         ret = write(completion_pipe[1], &mi, sizeof(mi));
492         if (ret == -1)
493                 error(1, errno, "completion_pipe write");
494 }
495
496 void *measure_thread(void *arg)
497 {
498         int s, i, ret;
499         struct pollfd pfd[3];
500         struct timespec timeout;
501         struct sockaddr_can addr;
502         sigset_t set;
503         unsigned msg_in_progress = 0;
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
680 int main(int argc, const char *argv[])
681 {
682         pthread_t thread;
683         sigset_t set;
684         int ret, i;
685
686         parse_options(argc, argv);
687
688         mlockall(MCL_CURRENT | MCL_FUTURE);
689
690         signal(SIGINT, term_handler);
691         signal(SIGTERM, term_handler);
692
693         for (i=0; i<MAX_INFOS; i++)
694                 msg_infos[i].id = -1;
695
696         if (opt.histogram) {
697                 histogram_init(&histogram, 5000000, 1);
698         }
699
700         ret = pipe(completion_pipe);
701         if (ret == -1)
702                 error(1, errno, "pipe");
703         ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
704         if (ret == -1)
705                 error(1, errno, "pipe fcntl");
706
707         init_ftrace();
708         
709         pthread_create(&thread, 0, measure_thread, NULL);
710
711         struct timespec next, now, diff;
712         clock_gettime(CLOCK_MONOTONIC, &next);
713         int completed = 0;
714         while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
715                 struct pollfd pfd[1];
716                 pfd[0].fd = completion_pipe[0];
717                 pfd[0].events = POLLIN;
718                 ret = poll(pfd, 1, 100);
719                 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
720                         error(1, errno, "poll main");
721                 if (ret > 0 && (pfd[0].revents & POLLIN)) {
722                         struct msg_info *mi;
723                         int ret;
724                         ret = read(completion_pipe[0], &mi, sizeof(mi));
725                         if (ret < sizeof(mi))
726                                 error(1, errno, "read completion returned %d", ret);
727                         if (opt.file)
728                                 msg_info_print(opt.file, mi);
729                         msg_info_free(mi);
730                         completed++;
731                 }
732
733                 clock_gettime(CLOCK_MONOTONIC, &now);
734                 if (timespec_subtract(&diff, &next, &now)) {
735                         printf("\rMessage %d", count);
736                         fflush(stdout);
737                         next.tv_nsec += 100000000;
738                         while (next.tv_nsec >= 1000000000) {
739                                 next.tv_nsec -= 1000000000;
740                                 next.tv_sec++;
741                         }
742                 }
743         }
744         printf("\rMessage %d\n", count);
745
746         pthread_join(thread, NULL);
747
748         close(completion_pipe[0]);
749         close(completion_pipe[1]);
750
751         if (opt.histogram) {
752                 histogram_fprint(&histogram, opt.histogram);
753                 fclose(opt.histogram);
754         }
755         if (opt.file)
756                 fclose(opt.file);
757
758         if (stats.overrun)
759                 printf("overrun=%d\n", stats.overrun);
760         if (stats.enobufs)
761                 printf("enobufs=%d\n", stats.enobufs);
762
763         return 0;
764 }