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