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