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