]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
63d96e5381d5f549bac39dc823a3b9fe618f0083
[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 #ifndef DEBUG
39 #define dbg(level, fmt, arg...) do {} while (0)
40 #else
41 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
42 #endif
43
44 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
45
46 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
47
48 /* Global variables */
49 volatile sig_atomic_t finish_flag = 0;  /* Threads should terminate. */
50 sem_t finish_sem;               /* Thread signals a termination */
51
52 /* Command line options */
53 struct options {
54         char **interface;
55         canid_t id;
56         unsigned period_us;
57         unsigned timeout_ms;
58         unsigned count;
59         unsigned oneattime;
60         FILE *file;
61         FILE *histogram;
62 };
63
64 struct options opt = {
65         .id = 10,
66         .period_us = 0,
67         .timeout_ms = 1000,
68
69 };
70
71 int num_interfaces = 0;
72 int count = 0;                  /* Number of sent messages */
73 int completion_pipe[2];
74
75 struct msg_info {
76         canid_t id;
77         uint8_t length;
78         struct timespec ts_sent, ts_sent_kern;
79         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
80         struct timespec ts_rx_final, ts_rx_final_kern;
81 };
82
83 #define MAX_INFOS 10000
84 struct msg_info msg_infos[MAX_INFOS];
85
86 struct histogram histogram;
87
88 static inline struct msg_info *frame2info(struct can_frame *frame)
89 {
90         uint16_t idx;
91         if (frame->can_dlc == 2) {
92                 memcpy(&idx, frame->data, sizeof(idx));
93                 if (idx >= MAX_INFOS)
94                         error(1, 0, "%s idx too high", __FUNCTION__);
95         } else
96                 error(1, 0, "%s error", __FUNCTION__);
97         return &msg_infos[idx];
98 }
99
100 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
101 {
102         return talloc_asprintf(ctx, "%ld.%06ld",
103                                tstamp->tv_sec, tstamp->tv_nsec/1000);
104 }
105
106 void print_msg_info(struct msg_info *mi)
107 {
108         struct timespec diff;
109         void *local = talloc_new (NULL);
110
111 #define S(ts) tstamp_str(local, &ts)
112 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
113
114         if (num_interfaces == 2)
115                 printf("%s -> %s (%s) = %s (%s)\n",
116                        S(mi->ts_sent), S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
117                        DIFF(mi->ts_sent, mi->ts_rx_final_kern),
118                        DIFF(mi->ts_sent, mi->ts_rx_final));
119         else
120                 printf("%s -> %s (%s) -> %s (%s) = %s (%s), %s (%s)\n",
121                        S(mi->ts_sent),
122                        S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
123                        S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
124                        DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
125                        DIFF(mi->ts_sent, mi->ts_rx_onwire),
126                        DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
127                        DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
128 #undef S
129 #undef DIFF
130         talloc_free (local);
131 }
132
133 int msg_info_store(FILE *f, struct msg_info *mi)
134 {
135         struct timespec diff;
136         void *local = talloc_new (NULL);
137
138 #define S(ts) tstamp_str(local, &ts)
139 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
140
141         if (num_interfaces == 2)
142                 fprintf(f, "%d %d %s\n",
143                         mi->id, mi->length,
144                         DIFF(mi->ts_sent, mi->ts_rx_final_kern));
145         else
146                 fprintf(f, "%d %d %s\n",
147                         mi->id, mi->length,
148                         DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
149 #undef S
150 #undef DIFF
151         talloc_free (local);
152 }
153
154
155 /* Subtract the `struct timespec' values X and Y, storing the result in
156    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
157
158 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
159 {
160         struct timespec ylocal = *yy, *y = &ylocal;
161         /* Perform the carry for the later subtraction by updating Y. */
162         if (x->tv_nsec < y->tv_nsec) {
163                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
164                 y->tv_nsec -= 1000000000 * nsec;
165                 y->tv_sec += nsec;
166         }
167         if (x->tv_nsec - y->tv_nsec > 1000000000) {
168                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
169                 y->tv_nsec += 1000000000 * nsec;
170                 y->tv_sec -= nsec;
171         }
172
173         /* Compute the time remaining to wait.
174            `tv_nsec' is certainly positive. */
175         result->tv_sec = x->tv_sec - y->tv_sec;
176         result->tv_nsec = x->tv_nsec - y->tv_nsec;
177
178         /* Return 1 if result is negative. */
179         return x->tv_sec < y->tv_sec;
180 }
181
182 void dbg_print_timespec(char *msg, struct timespec *tv)
183 {
184
185         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
186 }
187
188 static inline unsigned get_msg_latency_us(struct msg_info *mi)
189 {
190         struct timespec diff;
191         if (num_interfaces == 3)
192                 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
193         else
194                 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
195         return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
196 }
197
198 void set_sched_policy_and_prio(int policy, int rtprio)
199 {
200         struct sched_param scheduling_parameters;
201         int maxprio=sched_get_priority_max(policy);
202         int minprio=sched_get_priority_min(policy);
203
204         if((rtprio < minprio) || (rtprio > maxprio))
205                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
206                       minprio, maxprio);
207
208         scheduling_parameters.sched_priority = rtprio;
209
210         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
211                 error(1, errno, "pthread_setschedparam error");
212 }
213
214 void term_handler(int signum)
215 {
216         finish_flag = 1;
217 }
218
219 static inline int sock_get_if_index(int s, const char *if_name)
220 {
221         struct ifreq ifr;
222         MEMSET_ZERO(ifr);
223
224         strcpy(ifr.ifr_name, if_name);
225         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
226                 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
227         return ifr.ifr_ifindex;
228 }
229
230 static inline get_tstamp(struct timespec *ts)
231 {
232         clock_gettime(CLOCK_REALTIME, ts);
233 }
234
235 int send_frame(int socket)
236 {
237         struct can_frame frame;
238         struct msg_info *mi;
239         int ret;
240         static int curr_msg = -1;
241         int i;
242         uint16_t idx;
243         
244         i = curr_msg+1;
245         while (msg_infos[i].id != 0 && i != curr_msg) {
246                 i++;
247                 if (i >= MAX_INFOS)
248                         i = 0;
249         }
250         if (i == curr_msg)
251                 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
252         else
253                 curr_msg = i;
254
255         frame.can_id = opt.id;
256         frame.can_dlc = 2;
257         idx = curr_msg;
258         memcpy(frame.data, &idx, sizeof(idx));
259         mi = frame2info(&frame);
260
261         mi->id = frame.can_id;
262         mi->length = frame.can_dlc;
263         get_tstamp(&mi->ts_sent);
264         ret = write(socket, &frame, sizeof(frame));
265         return ret;
266 }
267
268 void msg_info_free(struct msg_info *mi)
269 {
270         mi->id = 0;
271 }
272
273 static inline void get_next_timeout(struct timespec *timeout)
274 {
275         struct timespec now;
276         static struct timespec last = {-1, 0 };
277
278         clock_gettime(CLOCK_MONOTONIC, &now);
279
280         if (last.tv_sec == -1)
281                 last = now;
282         if (opt.period_us != 0) {
283                 last.tv_sec += opt.period_us/1000000;
284                 last.tv_nsec += (opt.period_us%1000000)*1000;
285                 while (last.tv_nsec >= 1000000000) {
286                         last.tv_nsec -= 1000000000;
287                         last.tv_sec++;
288                 }
289                 timespec_subtract(timeout, &last, &now);
290         } else if (opt.timeout_ms != 0) {
291                 timeout->tv_sec = opt.timeout_ms/1000;
292                 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
293         } else
294                 error(1, 0, "Timeout and period cannot be both zero");
295 }
296
297 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
298 {
299         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
300         struct iovec iov;
301         struct msghdr msg;
302         struct cmsghdr *cmsg;
303         struct sockaddr_can addr;
304         int nbytes;
305         static uint64_t dropcnt = 0;
306
307         iov.iov_base = frame;
308         msg.msg_name = &addr;
309         msg.msg_iov = &iov;
310         msg.msg_iovlen = 1;
311         msg.msg_control = &ctrlmsg;
312
313         /* these settings may be modified by recvmsg() */
314         iov.iov_len = sizeof(*frame);
315         msg.msg_namelen = sizeof(addr);
316         msg.msg_controllen = sizeof(ctrlmsg);
317         msg.msg_flags = 0;
318
319         nbytes = recvmsg(s, &msg, 0);
320         if (nbytes < 0)
321                 error(1, errno, "recvmsg");
322
323         if (nbytes < sizeof(struct can_frame))
324                 error(1, 0, "recvmsg: incomplete CAN frame\n");
325
326         get_tstamp(ts_user);
327         MEMSET_ZERO(*ts_kern);
328         for (cmsg = CMSG_FIRSTHDR(&msg);
329              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
330              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
331                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
332                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
333                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
334                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
335         }
336
337 }
338
339 void process_tx(int s)
340 {
341         error(1, 0, "%s: not implemented", __FUNCTION__);
342 }
343
344 void process_on_wire_rx(int s)
345 {
346         struct timespec ts_kern, ts_user, ts_diff;
347         struct can_frame frame;
348         struct msg_info *mi;
349         receive(s, &frame, &ts_kern, &ts_user);
350         mi = frame2info(&frame);
351         mi->ts_rx_onwire_kern = ts_kern;
352         mi->ts_rx_onwire = ts_user;
353 }
354
355
356 void process_final_rx(int s)
357 {
358         struct timespec ts_kern, ts_user, ts_diff;
359         struct can_frame frame;
360         struct msg_info *mi;
361         int ret;
362         
363         receive(s, &frame, &ts_kern, &ts_user);
364         mi = frame2info(&frame);
365         mi->ts_rx_final_kern = ts_kern;
366         mi->ts_rx_final = ts_user;
367
368         if (opt.histogram)
369                 histogram_add(&histogram, get_msg_latency_us(mi));
370
371         ret = write(completion_pipe[1], &mi, sizeof(mi));
372         if (ret == -1)
373                 error(1, errno, "completion_pipe write");
374 }
375
376 void *measure_thread(void *arg)
377 {
378         int s, i, ret;
379         struct pollfd pfd[3];
380         struct timespec timeout;
381         struct sockaddr_can addr;
382         sigset_t set;
383         unsigned msg_in_progress = 0;
384
385         MEMSET_ZERO(pfd);
386
387         for (i=0; i<num_interfaces; i++) {
388                 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
389                         error(1, errno, "socket");
390
391                 addr.can_family = AF_CAN;
392                 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
393
394                 if (i == 0) {   /* TX socket */
395                         /* disable default receive filter on this RAW socket */
396                         /* This is obsolete as we do not read from the socket at all, but for */
397                         /* this reason we can remove the receive list in the Kernel to save a */
398                         /* little (really a very little!) CPU usage.                          */
399                         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
400                                 error(1, errno, "SOL_CAN_RAW");
401                 }
402
403                 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
404                         error(1, errno, "bind");
405
406                 const int timestamp_on = 1;
407                 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
408                                &timestamp_on, sizeof(timestamp_on)) < 0)
409                         error(1, errno, "setsockopt SO_TIMESTAMP");
410
411                 const int dropmonitor_on = 1;
412                 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
413                                &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
414                         error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
415
416                 pfd[i].fd = s;
417                 if (i == 0)
418                         pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
419                 else
420                         pfd[i].events = POLLIN;
421         }
422
423         set_sched_policy_and_prio(SCHED_FIFO, 99);
424
425 #define SEND()                                          \
426         do {                                            \
427                 ret = send_frame(pfd[0].fd);            \
428                 if (ret != sizeof(struct can_frame))    \
429                         error(1, errno, "send_frame (line %d)", __LINE__); \
430                 count++;                                \
431                 msg_in_progress++;                      \
432         } while (0)
433
434         if (opt.oneattime) {
435                 SEND();
436                 count = 1;
437         }
438
439         while (!finish_flag &&
440                (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
441
442                 get_next_timeout(&timeout);
443                 //printf("ppoll"); fflush(stdout);
444                 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
445                 //printf("=%d\n", ret);
446                 switch (ret) {
447                 case -1: // Error
448                         if (!INTERRUPTED_SYSCALL(errno))
449                                 error(1, errno, "ppoll");
450                         break;
451                 case 0: // Timeout
452                         if (opt.period_us) {
453                                 if (opt.count == 0 || count < opt.count) {
454                                         SEND();
455                                 }
456                         } else {
457                                 error(1, 0, "poll timeout");
458                         }
459                         break;
460                 default: // Event
461                         if (pfd[0].revents & (POLLIN|POLLERR)) {
462                                 process_tx(pfd[0].fd);
463                         }
464                         if (pfd[0].revents & POLLOUT) {
465                                 if (opt.count == 0 || count < opt.count)
466                                         SEND();
467                         }
468                         pfd[0].revents = 0;
469
470                         if (num_interfaces == 3 && pfd[1].revents != 0) {
471                                 process_on_wire_rx(pfd[1].fd);
472                                 pfd[1].revents = 0;
473                         }
474
475                         i = (num_interfaces == 2) ? 1 : 2;
476                         if (pfd[i].revents != 0) {
477                                 process_final_rx(pfd[i].fd);
478                                 msg_in_progress--;
479                                 pfd[i].revents = 0;
480                                 if ((opt.count == 0 || count < opt.count) &&
481                                     opt.oneattime) {
482                                         SEND();
483                                 }
484                         }
485                 }
486         }
487
488         for (i=0; i<num_interfaces; i++)
489                 close(pfd[i].fd);
490
491         return NULL;
492 }
493
494 struct poptOption optionsTable[] = {
495         { "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" },
496         { "count",  'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.count,   0,   "The count of messages to send, zero corresponds to infinity", "num"},
497         { "id",     'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.id,      0,   "CAN ID of sent messages", "id"},
498         { "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"},
499         { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
500         { "oneattime",'o', POPT_ARG_NONE,                         &opt.oneattime,0,  "Send the next message only when the previous was finally received"},
501         { "verbose",'v', POPT_ARG_NONE,                           NULL, 'v',         "Send the next message only when the previous was finally received"},
502         { "file",   'f', POPT_ARG_STRING,                         NULL, 'f',         "File where to store results", "filename"},
503         { "histogram", 'h', POPT_ARG_STRING,                      NULL, 'h',         "Store histogram in file", "filename"},
504         POPT_AUTOHELP
505         { NULL, 0, 0, NULL, 0 }
506 };
507
508 int parse_options(int argc, const char *argv[])
509 {
510         int c;
511         poptContext optCon;   /* context for parsing command-line options */
512
513         optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
514         //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
515
516         /* Now do options processing */
517         while ((c = poptGetNextOpt(optCon)) >= 0) {
518                 switch (c) {
519                 case 'd':
520                         num_interfaces++;
521                         break;
522                 case 'f':
523                         opt.file = fopen(poptGetOptArg(optCon), "w");
524                         if (!opt.file)
525                                 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
526                         break;
527                 case 'h':
528                         opt.histogram = fopen(poptGetOptArg(optCon), "w");
529                         if (!opt.histogram)
530                                 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
531                         break;
532                 }
533         }
534         if (c < -1)
535                 error(1, 0, "%s: %s\n",
536                       poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
537                       poptStrerror(c));
538
539         if (num_interfaces < 2 || num_interfaces > 3)
540                 error(1, 0, "-d option must be given exactly 2 or 3 times");
541
542         if (opt.oneattime && opt.period_us)
543                 error(1, 0, "oneattime and period cannot be specified at the same time");
544
545         poptFreeContext(optCon);
546
547         return 0;
548 }
549
550
551 int main(int argc, const char *argv[])
552 {
553         pthread_t thread;
554         sigset_t set;
555         int ret;
556
557         parse_options(argc, argv);
558
559         mlockall(MCL_CURRENT | MCL_FUTURE);
560
561         signal(SIGINT, term_handler);
562         signal(SIGTERM, term_handler);
563
564         if (opt.histogram) {
565                 histogram_init(&histogram, 1000000, 1);
566         }
567
568         ret = pipe(completion_pipe);
569         if (ret == -1)
570                 error(1, errno, "pipe");
571         ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
572         if (ret == -1)
573                 error(1, errno, "pipe fcntl");
574         
575         pthread_create(&thread, 0, measure_thread, NULL);
576
577         struct timespec next, now, diff;
578         clock_gettime(CLOCK_MONOTONIC, &next);
579         while (!finish_flag && (opt.count == 0 || count < opt.count)) {
580                 struct pollfd pfd[1];
581                 pfd[0].fd = completion_pipe[0];
582                 pfd[0].events = POLLIN;
583                 ret = poll(pfd, 1, 100);
584                 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
585                         error(1, errno, "poll main");
586                 if (ret > 0 && (pfd[0].revents & POLLIN)) {
587                         struct msg_info *mi;
588                         read(completion_pipe[0], &mi, sizeof(mi));
589                         if (opt.file)
590                                 msg_info_store(opt.file, mi);
591                         msg_info_free(mi);
592                 }
593
594                 clock_gettime(CLOCK_MONOTONIC, &now);
595                 if (timespec_subtract(&diff, &next, &now)) {
596                         printf("\rMessage %d", count);
597                         fflush(stdout);
598                         next.tv_nsec += 100000000;
599                         while (next.tv_nsec >= 1000000000) {
600                                 next.tv_nsec -= 1000000000;
601                                 next.tv_sec++;
602                         }
603                 }
604         }
605         printf("\rMessage %d\n", count);
606
607         pthread_join(thread, NULL);
608
609         close(completion_pipe[0]);
610         close(completion_pipe[1]);
611
612         if (opt.histogram) {
613                 histogram_fprint(&histogram, opt.histogram);
614                 fclose(opt.histogram);
615         }
616         if (opt.file)
617                 fclose(opt.file);
618
619         return 0;
620 }