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