]> rtime.felk.cvut.cz Git - can-benchmark.git/blob - latester/latester.c
Merge branch 'master' of rtime.felk.cvut.cz:/can-benchmark
[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
33 #include "histogram.h"
34
35 #ifndef DEBUG
36 #define dbg(level, fmt, arg...) do {} while (0)
37 #else
38 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
39 #endif
40
41 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
42
43 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
44
45 /* Global variables */
46 volatile sig_atomic_t finish_flag = 0;  /* Threads should terminate. */
47 sem_t finish_sem;               /* Thread signals a termination */
48
49 #define MAX_INTERFACES 4
50
51 /* Command line options */
52 char *option_interface[MAX_INTERFACES];
53 int num_interfaces = 0;
54 canid_t option_id;
55 unsigned option_period_us = 100000;
56
57 struct msg_info {
58         canid_t id;
59         uint8_t length;
60         struct timespec ts_sent, ts_sent_kern;
61         struct timespec ts_rx_onwire, ts_rx_onwire_kern;
62         struct timespec ts_rx_final, ts_rx_final_kern;
63 };
64
65 #define MAX_INFOS 10000
66 struct msg_info msg_infos[MAX_INFOS];
67 uint16_t curr_msg = 0;
68
69 static inline struct msg_info *frame2info(struct can_frame *frame)
70 {
71         uint16_t idx;
72         if (frame->can_dlc == 2) {
73                 memcpy(&idx, frame->data, sizeof(idx));
74                 if (idx >= MAX_INFOS)
75                         error(1, 0, "%s idx too high", __FUNCTION__);
76         } else
77                 error(1, 0, "%s error", __FUNCTION__);
78         return &msg_infos[idx];
79 }
80
81 static inline char *tstamp_str(char *buf, struct timespec *tstamp)
82 {
83         sprintf(buf, "%ld.%06ld", tstamp->tv_sec, tstamp->tv_nsec/1000);
84 }
85
86 void print_msg_info(struct msg_info *mi)
87 {
88         struct timespec ts_diff1, ts_diff2;
89         char str_sent[32], str_kern[32], str_user[32], str_diff1[32], str_diff2[32];
90         timespec_subtract(&ts_diff1, &mi->ts_rx_final_kern, &mi->ts_sent);
91         timespec_subtract(&ts_diff2, &mi->ts_rx_final,      &mi->ts_sent);
92         tstamp_str(str_sent, &mi->ts_sent);
93         tstamp_str(str_kern, &mi->ts_rx_final_kern);
94         tstamp_str(str_user, &mi->ts_rx_final);
95         tstamp_str(str_diff1, &ts_diff1);
96         tstamp_str(str_diff2, &ts_diff2);
97         printf("%s -> %s (%s) = %s (%s)\n", str_sent, str_user, str_kern, str_diff1, str_diff2);
98 }
99
100
101 /* Subtract the `struct timespec' values X and Y, storing the result in
102    RESULT.  Return 1 if the difference is negative, otherwise 0.  */
103      
104 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
105 {
106         struct timespec ylocal = *yy, *y = &ylocal;
107         /* Perform the carry for the later subtraction by updating Y. */
108         if (x->tv_nsec < y->tv_nsec) {
109                 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
110                 y->tv_nsec -= 1000000000 * nsec;
111                 y->tv_sec += nsec;
112         }
113         if (x->tv_nsec - y->tv_nsec > 1000000000) {
114                 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
115                 y->tv_nsec += 1000000000 * nsec;
116                 y->tv_sec -= nsec;
117         }
118      
119         /* Compute the time remaining to wait.
120            `tv_nsec' is certainly positive. */
121         result->tv_sec = x->tv_sec - y->tv_sec;
122         result->tv_nsec = x->tv_nsec - y->tv_nsec;
123      
124         /* Return 1 if result is negative. */
125         return x->tv_sec < y->tv_sec;
126 }
127
128 void dbg_print_timespec(char *msg, struct timespec *tv)
129 {
130
131         printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
132 }
133
134 void set_sched_policy_and_prio(int policy, int rtprio)
135 {
136         struct sched_param scheduling_parameters;
137         int maxprio=sched_get_priority_max(policy);
138         int minprio=sched_get_priority_min(policy);
139
140         if((rtprio < minprio) || (rtprio > maxprio))
141                 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
142                       minprio, maxprio);
143
144         scheduling_parameters.sched_priority = rtprio;
145
146         if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
147                 error(1, errno, "pthread_setschedparam error");
148 }
149
150 void term_handler(int signum)
151 {
152         finish_flag = 1;
153 }
154
155 static inline int sock_get_if_index(int s, const char *if_name)
156 {
157         struct ifreq ifr;
158         MEMSET_ZERO(ifr);
159         
160         strcpy(ifr.ifr_name, if_name);
161         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
162                 error(1, errno, "SIOCGIFINDEX");
163         return ifr.ifr_ifindex;
164 }
165
166 static inline get_tstamp(struct timespec *ts)
167 {
168         clock_gettime(CLOCK_REALTIME, ts);
169 }
170
171 int send_frame(int socket)
172 {
173         struct can_frame frame;
174         struct msg_info *mi;
175         int ret;
176
177         frame.can_id = option_id;
178         frame.can_dlc = 2;
179         memcpy(frame.data, &curr_msg, sizeof(curr_msg));
180         mi = frame2info(&frame);
181
182         get_tstamp(&mi->ts_sent);
183         ret = write(socket, &frame, sizeof(frame));
184         return ret;
185 }
186
187 static inline void get_next_timeout(struct timespec *timeout)
188 {
189         struct timespec now;
190         static struct timespec last = {-1, 0 };
191
192         clock_gettime(CLOCK_MONOTONIC, &now);
193         
194         if (last.tv_sec == -1)
195                 last = now;
196         last.tv_sec += option_period_us/1000000;
197         last.tv_nsec += (option_period_us%1000000)*1000;
198         while (last.tv_nsec >= 1000000000) {
199                 last.tv_nsec -= 1000000000;
200                 last.tv_sec++;
201         }               
202         timespec_subtract(timeout, &last, &now);
203 }
204
205 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
206 {
207         char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
208         struct iovec iov;
209         struct msghdr msg;
210         struct cmsghdr *cmsg;
211         struct sockaddr_can addr;
212         int nbytes;
213         static uint64_t dropcnt = 0;
214
215         iov.iov_base = frame;
216         msg.msg_name = &addr;
217         msg.msg_iov = &iov;
218         msg.msg_iovlen = 1;
219         msg.msg_control = &ctrlmsg;
220
221         /* these settings may be modified by recvmsg() */
222         iov.iov_len = sizeof(*frame);
223         msg.msg_namelen = sizeof(addr);
224         msg.msg_controllen = sizeof(ctrlmsg);  
225         msg.msg_flags = 0;
226
227         nbytes = recvmsg(s, &msg, 0);
228         if (nbytes < 0)
229                 error(1, errno, "recvmsg");
230
231         if (nbytes < sizeof(struct can_frame))
232                 error(1, 0, "recvmsg: incomplete CAN frame\n");
233
234         get_tstamp(ts_user);
235         MEMSET_ZERO(*ts_kern);
236         for (cmsg = CMSG_FIRSTHDR(&msg);
237              cmsg && (cmsg->cmsg_level == SOL_SOCKET);
238              cmsg = CMSG_NXTHDR(&msg,cmsg)) {
239                 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
240                         *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
241                 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
242                         dropcnt += *(__u32 *)CMSG_DATA(cmsg);
243         }
244
245 }
246
247 void process_tx(int s)
248 {
249         error(1, 0, "%s: not implemented", __FUNCTION__);
250 }
251
252 void process_on_wire_rx(int s)
253 {
254         error(1, 0, "%s: not implemented", __FUNCTION__);
255 }
256
257
258 void process_final_rx(int s)
259 {
260         struct timespec ts_kern, ts_user, ts_diff;
261         struct can_frame frame;
262         struct msg_info *mi;
263         receive(s, &frame, &ts_kern, &ts_user);
264         mi = frame2info(&frame);
265         mi->ts_rx_final_kern = ts_kern;
266         mi->ts_rx_final = ts_user;
267
268         print_msg_info(mi);
269 }
270
271 void *measure_thread(void *arg)
272 {
273         int s, i, ret;
274         struct pollfd pfd[MAX_INTERFACES];
275         struct timespec timeout;
276         struct sockaddr_can addr;
277         sigset_t set;
278
279         MEMSET_ZERO(pfd);
280         
281         for (i=0; i<num_interfaces; i++) {
282                 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
283                         error(1, errno, "socket");
284
285                 addr.can_family = AF_CAN;
286                 addr.can_ifindex = sock_get_if_index(s, option_interface[i]);
287
288                 if (i == 0) {   /* TX socket */
289                         /* disable default receive filter on this RAW socket */
290                         /* This is obsolete as we do not read from the socket at all, but for */
291                         /* this reason we can remove the receive list in the Kernel to save a */
292                         /* little (really a very little!) CPU usage.                          */
293                         if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
294                                 error(1, errno, "SOL_CAN_RAW");
295                 }
296
297                 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
298                         error(1, errno, "bind");
299
300                 const int timestamp_on = 1;
301                 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
302                                &timestamp_on, sizeof(timestamp_on)) < 0)
303                         error(1, errno, "setsockopt SO_TIMESTAMP");
304
305 //              const int dropmonitor_on = 1;
306 //              if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
307 //                             &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
308 //                      error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
309
310                 pfd[i].fd = s;
311                 pfd[i].events = (i == 0) ? POLLERR : POLLIN;
312         }
313
314         set_sched_policy_and_prio(SCHED_FIFO, 99);
315
316         while (!finish_flag) {
317                 get_next_timeout(&timeout);
318                 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
319                 switch (ret) {
320                 case -1:
321                         if (!INTERRUPTED_SYSCALL(errno))
322                                 error(1, errno, "ppoll");
323                         break;
324                 case 0:
325                         ret = send_frame(pfd[0].fd);
326                         if (ret != sizeof(struct can_frame))
327                                 error(1, errno, "send_frame");
328                         break;
329                 default:
330                         if (pfd[0].revents != 0) {
331                                 process_tx(pfd[0].fd);
332                         }
333                         if (pfd[1].revents != 0) {
334                                 switch (num_interfaces) {
335                                 case 2: process_final_rx(pfd[1].fd); break;
336                                 case 3: process_on_wire_rx(pfd[1].fd); break;
337                                 }
338                         }
339                         if (pfd[2].revents != 0) {
340                                 process_final_rx(pfd[2].fd);
341                         }
342                 }
343         }
344
345         for (i=0; i<num_interfaces; i++)
346                 close(pfd[i].fd);
347
348         return NULL;
349 }
350
351 void print_help(void)
352 {
353         printf("Usage: latester -d <interface> -d <interface> ... [other options]\n"
354                "Other options:\n"
355                "  -d <interface> Interface to use. Must be given two times (tx, rx) or three times (tx, rx1, rx2).\n"
356                 );
357 }
358      
359 int parse_options(int argc, char *argv[])
360 {
361         int c;
362         
363         opterr = 0;
364         while ((c = getopt (argc, argv, "d:h")) != -1)
365                 switch (c)
366                 {
367                 case 'd':
368                         if (num_interfaces < MAX_INTERFACES) {
369                                 option_interface[num_interfaces] = optarg;
370                                 num_interfaces++;
371                         } else
372                                 error(1, 0, "error: Too many -d options");
373                         break;
374                 case 'h':
375                         print_help();
376                         exit(0);
377                         break;
378                 case '?':
379                         if (isprint (optopt))
380                                 error (1, 0, "Unknown option `-%c'.\n", optopt);
381                         else
382                                 error (1, 0, "Unknown option character `\\x%x'.\n", optopt);
383                 default:
384                         error(1, 0, "Unhandled parameter");
385                 }
386         if (num_interfaces < 2 || num_interfaces > 3)
387                 error(1, 0, "-d option must be given exactly 2 or 3 times");
388         return 0;
389 }
390
391 int main(int argc, char *argv[])
392 {
393         pthread_t thread;
394         sigset_t set;
395         int ret;
396                            
397         parse_options(argc, argv);
398
399         mlockall(MCL_CURRENT | MCL_FUTURE);
400
401         signal(SIGINT, term_handler);
402         signal(SIGTERM, term_handler);
403
404
405         pthread_create(&thread, 0, measure_thread, NULL);
406
407         while (!finish_flag) {
408                 sleep(1);
409         }
410
411         pthread_join(thread, NULL);
412
413         return 0;
414 }