]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
Latester update
[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 } opt = {
60         .id = 10,
61         .period_us = 0,
62         .timeout_ms = 1000,
63         
64 };
65
66 int num_interfaces = 0;
67
68 struct msg_info {
69         canid_t id;
70         uint8_t length;
71         struct timespec ts_sent, ts_sent_kern;
72         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
73         struct timespec ts_rx_final, ts_rx_final_kern;
74 };
75
76 #define MAX_INFOS 10000
77 struct msg_info msg_infos[MAX_INFOS];
78 uint16_t curr_msg = 0;
79
80 static inline struct msg_info *frame2info(struct can_frame *frame)
81 {
82         uint16_t idx;
83         if (frame->can_dlc == 2) {
84                 memcpy(&idx, frame->data, sizeof(idx));
85                 if (idx >= MAX_INFOS)
86                         error(1, 0, "%s idx too high", __FUNCTION__);
87         } else
88                 error(1, 0, "%s error", __FUNCTION__);
89         return &msg_infos[idx];
90 }
91
92 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
93 {
94         return talloc_asprintf(ctx, "%ld.%06ld",
95                                tstamp->tv_sec, tstamp->tv_nsec/1000);
96 }
97
98 void print_msg_info(struct msg_info *mi)
99 {
100         struct timespec diff;
101         void *local = talloc_new (NULL);
102         
103 #define S(ts) tstamp_str(local, &ts)
104 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
105         
106         if (num_interfaces == 2) 
107                 printf("%s -> %s (%s) = %s (%s)\n",
108                        S(mi->ts_sent), S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
109                        DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
110                        DIFF(mi->ts_sent, mi->ts_rx_onwire));
111         else
112                 printf("%s -> %s (%s) -> %s (%s) = %s (%s), %s (%s)\n",
113                        S(mi->ts_sent),
114                        S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
115                        S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
116                        DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
117                        DIFF(mi->ts_sent, mi->ts_rx_onwire),
118                        DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
119                        DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
120 #undef S
121 #undef DIFF
122         talloc_free (local);
123 }
124
125
126 /* Subtract the `struct timespec' values X and Y, storing the result in
127    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
128      
129 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
130 {
131         struct timespec ylocal = *yy, *y = &ylocal;
132         /* Perform the carry for the later subtraction by updating Y. */
133         if (x->tv_nsec < y->tv_nsec) {
134                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
135                 y->tv_nsec -= 1000000000 * nsec;
136                 y->tv_sec += nsec;
137         }
138         if (x->tv_nsec - y->tv_nsec > 1000000000) {
139                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
140                 y->tv_nsec += 1000000000 * nsec;
141                 y->tv_sec -= nsec;
142         }
143      
144         /* Compute the time remaining to wait.
145            `tv_nsec' is certainly positive. */
146         result->tv_sec = x->tv_sec - y->tv_sec;
147         result->tv_nsec = x->tv_nsec - y->tv_nsec;
148      
149         /* Return 1 if result is negative. */
150         return x->tv_sec < y->tv_sec;
151 }
152
153 void dbg_print_timespec(char *msg, struct timespec *tv)
154 {
155
156         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
157 }
158
159 void set_sched_policy_and_prio(int policy, int rtprio)
160 {
161         struct sched_param scheduling_parameters;
162         int maxprio=sched_get_priority_max(policy);
163         int minprio=sched_get_priority_min(policy);
164
165         if((rtprio < minprio) || (rtprio > maxprio))
166                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
167                       minprio, maxprio);
168
169         scheduling_parameters.sched_priority = rtprio;
170
171         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
172                 error(1, errno, "pthread_setschedparam error");
173 }
174
175 void term_handler(int signum)
176 {
177         finish_flag = 1;
178 }
179
180 static inline int sock_get_if_index(int s, const char *if_name)
181 {
182         struct ifreq ifr;
183         MEMSET_ZERO(ifr);
184         
185         strcpy(ifr.ifr_name, if_name);
186         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
187                 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
188         return ifr.ifr_ifindex;
189 }
190
191 static inline get_tstamp(struct timespec *ts)
192 {
193         clock_gettime(CLOCK_REALTIME, ts);
194 }
195
196 int send_frame(int socket)
197 {
198         struct can_frame frame;
199         struct msg_info *mi;
200         int ret;
201
202         frame.can_id = opt.id;
203         frame.can_dlc = 2;
204         memcpy(frame.data, &curr_msg, sizeof(curr_msg));
205         mi = frame2info(&frame);
206
207         get_tstamp(&mi->ts_sent);
208         ret = write(socket, &frame, sizeof(frame));
209         return ret;
210 }
211
212 static inline void get_next_timeout(struct timespec *timeout)
213 {
214         struct timespec now;
215         static struct timespec last = {-1, 0 };
216
217         clock_gettime(CLOCK_MONOTONIC, &now);
218         
219         if (last.tv_sec == -1)
220                 last = now;
221         if (opt.period_us != 0) {
222                 last.tv_sec += opt.period_us/1000000;
223                 last.tv_nsec += (opt.period_us%1000000)*1000;
224                 while (last.tv_nsec >= 1000000000) {
225                         last.tv_nsec -= 1000000000;
226                         last.tv_sec++;
227                 }               
228                 timespec_subtract(timeout, &last, &now);
229         } else if (opt.timeout_ms != 0) {
230                 timeout->tv_sec = opt.timeout_ms/1000;
231                 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
232         } else
233                 error(1, 0, "Timeout and period cannot be both zero");
234 }
235
236 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
237 {
238         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
239         struct iovec iov;
240         struct msghdr msg;
241         struct cmsghdr *cmsg;
242         struct sockaddr_can addr;
243         int nbytes;
244         static uint64_t dropcnt = 0;
245
246         iov.iov_base = frame;
247         msg.msg_name = &addr;
248         msg.msg_iov = &iov;
249         msg.msg_iovlen = 1;
250         msg.msg_control = &ctrlmsg;
251
252         /* these settings may be modified by recvmsg() */
253         iov.iov_len = sizeof(*frame);
254         msg.msg_namelen = sizeof(addr);
255         msg.msg_controllen = sizeof(ctrlmsg);  
256         msg.msg_flags = 0;
257
258         nbytes = recvmsg(s, &msg, 0);
259         if (nbytes < 0)
260                 error(1, errno, "recvmsg");
261
262         if (nbytes < sizeof(struct can_frame))
263                 error(1, 0, "recvmsg: incomplete CAN frame\n");
264
265         get_tstamp(ts_user);
266         MEMSET_ZERO(*ts_kern);
267         for (cmsg = CMSG_FIRSTHDR(&msg);
268              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
269              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
270                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
271                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
272                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
273                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
274         }
275
276 }
277
278 void process_tx(int s)
279 {
280         error(1, 0, "%s: not implemented", __FUNCTION__);
281 }
282
283 void process_on_wire_rx(int s)
284 {
285         struct timespec ts_kern, ts_user, ts_diff;
286         struct can_frame frame;
287         struct msg_info *mi;
288         receive(s, &frame, &ts_kern, &ts_user);
289         mi = frame2info(&frame);
290         mi->ts_rx_onwire_kern = ts_kern;
291         mi->ts_rx_onwire = ts_user;
292 }
293
294
295 void process_final_rx(int s)
296 {
297         struct timespec ts_kern, ts_user, ts_diff;
298         struct can_frame frame;
299         struct msg_info *mi;
300         receive(s, &frame, &ts_kern, &ts_user);
301         mi = frame2info(&frame);
302         mi->ts_rx_final_kern = ts_kern;
303         mi->ts_rx_final = ts_user;
304
305         print_msg_info(mi);
306 }
307
308 void *measure_thread(void *arg)
309 {
310         int s, i, ret;
311         struct pollfd pfd[3];
312         struct timespec timeout;
313         struct sockaddr_can addr;
314         sigset_t set;
315         int count = 0;
316         unsigned msg_in_progress = 0;
317
318         MEMSET_ZERO(pfd);
319         
320         for (i=0; i<num_interfaces; i++) {
321                 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
322                         error(1, errno, "socket");
323
324                 addr.can_family = AF_CAN;
325                 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
326
327                 if (i == 0) {   /* TX socket */
328                         /* disable default receive filter on this RAW socket */
329                         /* This is obsolete as we do not read from the socket at all, but for */
330                         /* this reason we can remove the receive list in the Kernel to save a */
331                         /* little (really a very little!) CPU usage.                          */
332                         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
333                                 error(1, errno, "SOL_CAN_RAW");
334                 }
335
336                 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
337                         error(1, errno, "bind");
338
339                 const int timestamp_on = 1;
340                 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
341                                &timestamp_on, sizeof(timestamp_on)) < 0)
342                         error(1, errno, "setsockopt SO_TIMESTAMP");
343
344 //              const int dropmonitor_on = 1;
345 //              if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
346 //                             &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
347 //                      error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
348
349                 pfd[i].fd = s;
350                 if (i == 0)
351                         pfd[i].events = POLLIN | POLLERR | (opt.period_us == 0 ? POLLOUT : 0);
352                 else
353                         pfd[i].events = POLLIN;
354         }
355
356         set_sched_policy_and_prio(SCHED_FIFO, 99);
357
358 #define SEND()                                          \
359         do {                                            \
360                 ret = send_frame(pfd[0].fd);            \
361                 if (ret != sizeof(struct can_frame))    \
362                         error(1, errno, "send_frame");  \
363                 msg_in_progress++;                      \
364         } while (0)
365
366         while (!finish_flag &&
367                (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
368                 get_next_timeout(&timeout);
369                 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
370                 switch (ret) {
371                 case -1: // Error
372                         if (!INTERRUPTED_SYSCALL(errno))
373                                 error(1, errno, "ppoll");
374                         break;
375                 case 0: // Timeout
376                         if (opt.period_us) {
377                                 if (opt.count == 0 || count++ < opt.count) {
378                                         SEND();
379                                 } else {
380                                         error(1, 0, "poll timeout");
381                                 }
382                         }
383                         break;
384                 default: // Event
385                         if (pfd[0].revents & (POLLIN|POLLERR)) {
386                                 process_tx(pfd[0].fd);
387                         }
388                         if (pfd[0].revents & POLLOUT) {
389                                 if ((opt.count == 0 || count++ < opt.count) &&
390                                     !opt.oneattime) {
391                                         SEND();
392                                 }
393                         }
394                         pfd[0].revents = 0;
395
396                         if (num_interfaces == 3 && pfd[1].revents != 0) {
397                                 process_on_wire_rx(pfd[1].fd);
398                                 pfd[1].revents = 0;
399                         }
400
401                         i = (num_interfaces == 2) ? 1 : 2;
402                         if (pfd[i].revents != 0) {
403                                 process_final_rx(pfd[i].fd);
404                                 msg_in_progress--;
405                                 pfd[i].revents = 0;
406                                 if ((opt.count == 0 || count++ < opt.count) &&
407                                     opt.oneattime) {
408                                         SEND();
409                                 }
410                         }
411                 }
412         }
413
414         for (i=0; i<num_interfaces; i++)
415                 close(pfd[i].fd);
416
417         return NULL;
418 }
419
420 struct poptOption optionsTable[] = {
421         { "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" },
422         { "count",  'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.count,   0,   "The count of messages to send, zero corresponds to infinity", "num"},
423         { "id",     'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.id,      0,   "CAN ID of sent messages", "id"},
424         { "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"},
425         { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT,  &opt.timeout_ms,0,   "Timeout when period is zero", "ms"},
426         { "oneattime",'o', POPT_ARG_NONE,                         &opt.oneattime,0,   "Send the next message only when the previous was finally received"},
427         { "verbose",'v', POPT_ARG_NONE,                           NULL, 'v',   "Send the next message only when the previous was finally received"},
428         POPT_AUTOHELP
429         { NULL, 0, 0, NULL, 0 }
430 };
431
432 int parse_options(int argc, const char *argv[])
433 {
434         int c;
435         poptContext optCon;   /* context for parsing command-line options */
436         
437         optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
438         //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
439
440         /* Now do options processing */
441         while ((c = poptGetNextOpt(optCon)) >= 0) {
442                 switch (c) {
443                 case 'd':
444                         num_interfaces++;
445                         break;
446                 }
447         }
448         if (c < -1)
449                 error(1, 0, "%s: %s\n",
450                       poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
451                       poptStrerror(c));
452         
453         if (num_interfaces < 2 || num_interfaces > 3)
454                 error(1, 0, "-d option must be given exactly 2 or 3 times");
455
456         poptFreeContext(optCon);
457
458         return 0;
459 }
460
461
462 int main(int argc, const char *argv[])
463 {
464         pthread_t thread;
465         sigset_t set;
466         int ret;
467
468         parse_options(argc, argv);
469                            
470         mlockall(MCL_CURRENT | MCL_FUTURE);
471
472         signal(SIGINT, term_handler);
473         signal(SIGTERM, term_handler);
474
475
476         pthread_create(&thread, 0, measure_thread, NULL);
477
478         while (!finish_flag) {
479                 sleep(1);
480         }
481
482         pthread_join(thread, NULL);
483
484         return 0;
485 }