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