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