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