1 /**************************************************************************/
2 /* CAN latency tester */
3 /* Copyright (C) 2010 Michal Sojka, DCE FEE CTU Prague */
5 /**************************************************************************/
16 #include <semaphore.h>
24 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/types.h>
33 #include <linux/can.h>
34 #include <linux/can/raw.h>
36 #include "histogram.h"
39 #define dbg(level, fmt, arg...) do {} while (0)
41 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
44 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
46 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
48 /* Global variables */
49 volatile sig_atomic_t finish_flag = 0; /* Threads should terminate. */
50 sem_t finish_sem; /* Thread signals a termination */
52 /* Command line options */
65 struct options opt = {
72 int num_interfaces = 0;
73 int count = 0; /* Number of sent messages */
74 int completion_pipe[2];
79 struct timespec ts_sent, ts_sent_kern;
80 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
81 struct timespec ts_rx_final, ts_rx_final_kern;
82 struct can_frame sent, received;
85 #define MAX_INFOS 10000
86 struct msg_info msg_infos[MAX_INFOS];
88 struct histogram histogram;
90 int can_frame_sprintf(char *buf, struct can_frame *frame)
95 sprintf(&datastr[i*2], "%02x", frame->data[i]);
96 sprintf(buf, "id=0x%x, len=%d, data=%s",
97 frame->can_id, frame->can_dlc, datastr);
100 static inline struct msg_info *frame2info(struct can_frame *frame)
103 if (frame->can_dlc >= 2) {
104 memcpy(&idx, frame->data, sizeof(idx));
105 if (idx >= MAX_INFOS)
106 error(1, 0, "%s idx too high", __FUNCTION__);
109 error(1, 0, "%s error", __FUNCTION__);
111 return &msg_infos[idx];
114 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
116 return talloc_asprintf(ctx, "%ld.%06ld",
117 tstamp->tv_sec, tstamp->tv_nsec/1000);
120 void msg_info_print(FILE *f, struct msg_info *mi)
122 struct timespec diff;
123 void *local = talloc_new (NULL);
125 char sent[64], received[64];
127 can_frame_sprintf(sent, &mi->sent);
128 can_frame_sprintf(received, &mi->received);
130 #define S(ts) tstamp_str(local, &ts)
131 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
133 if (num_interfaces == 2)
134 fprintf(f, "%ld: %s [%s] -> %s (%s) [%s] = %s (%s)\n",
135 num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
136 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
137 DIFF(mi->ts_sent, mi->ts_rx_final));
139 fprintf(f, "%ld: %s [%s] -> %s (%s) -> %s (%s) [%s] = %s (%s), %s (%s)\n",
140 num, S(mi->ts_sent), sent,
141 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
142 S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
143 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
144 DIFF(mi->ts_sent, mi->ts_rx_onwire),
145 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
146 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
153 int msg_info_store(FILE *f, struct msg_info *mi)
155 struct timespec diff;
156 void *local = talloc_new (NULL);
159 #define S(ts) tstamp_str(local, &ts)
160 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
162 if (num_interfaces == 2)
163 fprintf(f, "%ld %d %d %s\n",
164 num, mi->id, mi->length,
165 DIFF(mi->ts_sent, mi->ts_rx_final_kern));
167 fprintf(f, "%ld %d %d %s\n",
168 num, mi->id, mi->length,
169 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
176 /* Subtract the `struct timespec' values X and Y, storing the result in
177 RESULT. Return 1 if the difference is negative, otherwise 0. */
179 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
181 struct timespec ylocal = *yy, *y = &ylocal;
182 /* Perform the carry for the later subtraction by updating Y. */
183 if (x->tv_nsec < y->tv_nsec) {
184 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
185 y->tv_nsec -= 1000000000 * nsec;
188 if (x->tv_nsec - y->tv_nsec > 1000000000) {
189 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
190 y->tv_nsec += 1000000000 * nsec;
194 /* Compute the time remaining to wait.
195 `tv_nsec' is certainly positive. */
196 result->tv_sec = x->tv_sec - y->tv_sec;
197 result->tv_nsec = x->tv_nsec - y->tv_nsec;
199 /* Return 1 if result is negative. */
200 return x->tv_sec < y->tv_sec;
203 void dbg_print_timespec(char *msg, struct timespec *tv)
206 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
209 static inline unsigned get_msg_latency_us(struct msg_info *mi)
211 struct timespec diff;
212 if (num_interfaces == 3)
213 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
215 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
216 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
219 void set_sched_policy_and_prio(int policy, int rtprio)
221 struct sched_param scheduling_parameters;
222 int maxprio=sched_get_priority_max(policy);
223 int minprio=sched_get_priority_min(policy);
225 if((rtprio < minprio) || (rtprio > maxprio))
226 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
229 scheduling_parameters.sched_priority = rtprio;
231 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
232 error(1, errno, "pthread_setschedparam error");
235 void term_handler(int signum)
240 static inline int sock_get_if_index(int s, const char *if_name)
245 strcpy(ifr.ifr_name, if_name);
246 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
247 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
248 return ifr.ifr_ifindex;
251 static inline get_tstamp(struct timespec *ts)
253 clock_gettime(CLOCK_MONOTONIC, ts);
256 int send_frame(int socket)
258 struct can_frame frame;
261 static int curr_msg = -1;
267 while (msg_infos[i].id != 0 && i != curr_msg) {
273 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
277 frame.can_id = opt.id;
279 error(1, 0, "Length < 2 is not yet supported");
280 frame.can_dlc = opt.length;
282 memcpy(frame.data, &idx, sizeof(idx));
283 mi = frame2info(&frame);
285 mi->id = frame.can_id;
286 mi->length = frame.can_dlc;
287 get_tstamp(&mi->ts_sent);
289 ret = write(socket, &frame, sizeof(frame));
293 void msg_info_free(struct msg_info *mi)
298 static inline void get_next_timeout(struct timespec *timeout)
301 static struct timespec last = {-1, 0 };
303 clock_gettime(CLOCK_MONOTONIC, &now);
305 if (last.tv_sec == -1)
307 if (opt.period_us != 0) {
308 last.tv_sec += opt.period_us/1000000;
309 last.tv_nsec += (opt.period_us%1000000)*1000;
310 while (last.tv_nsec >= 1000000000) {
311 last.tv_nsec -= 1000000000;
314 timespec_subtract(timeout, &last, &now);
315 } else if (opt.timeout_ms != 0) {
316 timeout->tv_sec = opt.timeout_ms/1000;
317 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
319 error(1, 0, "Timeout and period cannot be both zero");
322 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
324 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
327 struct cmsghdr *cmsg;
328 struct sockaddr_can addr;
330 static uint64_t dropcnt = 0;
332 iov.iov_base = frame;
333 msg.msg_name = &addr;
336 msg.msg_control = &ctrlmsg;
338 /* these settings may be modified by recvmsg() */
339 iov.iov_len = sizeof(*frame);
340 msg.msg_namelen = sizeof(addr);
341 msg.msg_controllen = sizeof(ctrlmsg);
344 nbytes = recvmsg(s, &msg, 0);
346 error(1, errno, "recvmsg");
348 if (nbytes < sizeof(struct can_frame))
349 error(1, 0, "recvmsg: incomplete CAN frame\n");
352 MEMSET_ZERO(*ts_kern);
353 for (cmsg = CMSG_FIRSTHDR(&msg);
354 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
355 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
356 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
357 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
358 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
359 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
364 void process_tx(int s)
366 error(1, 0, "%s: not implemented", __FUNCTION__);
369 void process_on_wire_rx(int s)
371 struct timespec ts_kern, ts_user, ts_diff;
372 struct can_frame frame;
374 receive(s, &frame, &ts_kern, &ts_user);
375 mi = frame2info(&frame);
376 mi->ts_rx_onwire_kern = ts_kern;
377 mi->ts_rx_onwire = ts_user;
381 void process_final_rx(int s)
383 struct timespec ts_kern, ts_user, ts_diff;
384 struct can_frame frame;
388 receive(s, &frame, &ts_kern, &ts_user);
389 mi = frame2info(&frame);
390 mi->ts_rx_final_kern = ts_kern;
391 mi->ts_rx_final = ts_user;
392 mi->received = frame;
395 histogram_add(&histogram, get_msg_latency_us(mi));
397 ret = write(completion_pipe[1], &mi, sizeof(mi));
399 error(1, errno, "completion_pipe write");
402 void *measure_thread(void *arg)
405 struct pollfd pfd[3];
406 struct timespec timeout;
407 struct sockaddr_can addr;
409 unsigned msg_in_progress = 0;
413 for (i=0; i<num_interfaces; i++) {
414 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
415 error(1, errno, "socket");
417 addr.can_family = AF_CAN;
418 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
420 if (i == 0) { /* TX socket */
421 /* disable default receive filter on this RAW socket */
422 /* This is obsolete as we do not read from the socket at all, but for */
423 /* this reason we can remove the receive list in the Kernel to save a */
424 /* little (really a very little!) CPU usage. */
425 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
426 error(1, errno, "SOL_CAN_RAW");
429 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
430 error(1, errno, "bind");
432 const int timestamp_on = 1;
433 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
434 ×tamp_on, sizeof(timestamp_on)) < 0)
435 error(1, errno, "setsockopt SO_TIMESTAMP");
437 const int dropmonitor_on = 1;
438 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
439 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
440 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
444 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
446 pfd[i].events = POLLIN;
449 set_sched_policy_and_prio(SCHED_FIFO, 99);
453 ret = send_frame(pfd[0].fd); \
454 if (ret != sizeof(struct can_frame)) \
455 error(1, errno, "send_frame (line %d)", __LINE__); \
465 while (!finish_flag &&
466 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
468 get_next_timeout(&timeout);
469 //printf("ppoll"); fflush(stdout);
470 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
471 //printf("=%d\n", ret);
474 if (!INTERRUPTED_SYSCALL(errno))
475 error(1, errno, "ppoll");
479 if (opt.count == 0 || count < opt.count) {
483 error(1, 0, "poll timeout");
487 if (pfd[0].revents & (POLLIN|POLLERR)) {
488 process_tx(pfd[0].fd);
490 if (pfd[0].revents & POLLOUT) {
491 if (opt.count == 0 || count < opt.count)
496 if (num_interfaces == 3 && pfd[1].revents != 0) {
497 process_on_wire_rx(pfd[1].fd);
501 i = (num_interfaces == 2) ? 1 : 2;
502 if (pfd[i].revents != 0) {
503 process_final_rx(pfd[i].fd);
506 if ((opt.count == 0 || count < opt.count) &&
514 for (i=0; i<num_interfaces; i++)
520 struct poptOption optionsTable[] = {
521 { "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" },
522 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
523 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
524 { "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"},
525 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
526 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
527 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
528 { "file", 'f', POPT_ARG_STRING, NULL, 'f', "File where to store results", "filename"},
529 { "histogram", 'h', POPT_ARG_STRING, NULL, 'h', "Store histogram in file", "filename"},
530 { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.length, 0, "The length of generated messages", "bytes"},
532 { NULL, 0, 0, NULL, 0 }
535 int parse_options(int argc, const char *argv[])
538 poptContext optCon; /* context for parsing command-line options */
540 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
541 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
543 /* Now do options processing */
544 while ((c = poptGetNextOpt(optCon)) >= 0) {
550 opt.file = fopen(poptGetOptArg(optCon), "w");
552 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
555 opt.histogram = fopen(poptGetOptArg(optCon), "w");
557 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
562 error(1, 0, "%s: %s\n",
563 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
566 if (num_interfaces < 2 || num_interfaces > 3)
567 error(1, 0, "-d option must be given exactly 2 or 3 times");
569 if (opt.oneattime && opt.period_us)
570 error(1, 0, "oneattime and period cannot be specified at the same time");
572 poptFreeContext(optCon);
578 int main(int argc, const char *argv[])
584 parse_options(argc, argv);
586 mlockall(MCL_CURRENT | MCL_FUTURE);
588 signal(SIGINT, term_handler);
589 signal(SIGTERM, term_handler);
592 histogram_init(&histogram, 5000000, 1);
595 ret = pipe(completion_pipe);
597 error(1, errno, "pipe");
598 ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
600 error(1, errno, "pipe fcntl");
602 pthread_create(&thread, 0, measure_thread, NULL);
604 struct timespec next, now, diff;
605 clock_gettime(CLOCK_MONOTONIC, &next);
607 while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
608 struct pollfd pfd[1];
609 pfd[0].fd = completion_pipe[0];
610 pfd[0].events = POLLIN;
611 ret = poll(pfd, 1, 100);
612 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
613 error(1, errno, "poll main");
614 if (ret > 0 && (pfd[0].revents & POLLIN)) {
617 ret = read(completion_pipe[0], &mi, sizeof(mi));
618 if (ret < sizeof(mi))
619 error(1, errno, "read completion returned %d", ret);
621 msg_info_print(opt.file, mi);
626 clock_gettime(CLOCK_MONOTONIC, &now);
627 if (timespec_subtract(&diff, &next, &now)) {
628 printf("\rMessage %d", count);
630 next.tv_nsec += 100000000;
631 while (next.tv_nsec >= 1000000000) {
632 next.tv_nsec -= 1000000000;
637 printf("\rMessage %d\n", count);
639 pthread_join(thread, NULL);
641 close(completion_pipe[0]);
642 close(completion_pipe[1]);
645 histogram_fprint(&histogram, opt.histogram);
646 fclose(opt.histogram);