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