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"
41 #define dbg(level, fmt, arg...) do {} while (0)
43 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
46 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
48 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
50 /* Global variables */
51 volatile sig_atomic_t finish_flag = 0; /* Threads should terminate. */
52 sem_t finish_sem; /* Thread signals a termination */
54 /* Command line options */
68 struct options opt = {
80 int num_interfaces = 0;
81 int count = 0; /* Number of sent messages */
82 int completion_pipe[2];
87 struct timespec ts_sent, ts_sent_kern;
88 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
89 struct timespec ts_rx_final, ts_rx_final_kern;
90 struct can_frame sent, received;
93 #define MAX_INFOS 10000
94 struct msg_info msg_infos[MAX_INFOS];
96 struct histogram histogram;
98 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
99 /* documentation see lib.h */
102 int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
104 if (cf->can_id & CAN_ERR_FLAG) {
105 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
107 } else if (cf->can_id & CAN_EFF_FLAG) {
108 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
111 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
115 if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
116 sprintf(buf+offset, "R");
118 for (i = 0; i < dlc; i++) {
119 sprintf(buf+offset, "%02X", cf->data[i]);
121 if (sep && (i+1 < dlc))
122 sprintf(buf+offset++, ".");
126 static inline struct msg_info *frame2info(struct can_frame *frame)
129 if (frame->can_dlc >= 2) {
130 memcpy(&idx, frame->data, sizeof(idx));
131 if (idx >= MAX_INFOS)
132 error(1, 0, "%s idx too high", __FUNCTION__);
135 error(1, 0, "%s error", __FUNCTION__);
137 return &msg_infos[idx];
140 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
142 return talloc_asprintf(ctx, "%ld.%06ld",
143 tstamp->tv_sec, tstamp->tv_nsec/1000);
146 void msg_info_print(FILE *f, struct msg_info *mi)
148 struct timespec diff;
149 void *local = talloc_new (NULL);
151 char sent[64], received[64];
153 sprint_canframe(sent, &mi->sent, true);
154 sprint_canframe(received, &mi->received, true);
156 #define S(ts) tstamp_str(local, &ts)
157 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
159 if (num_interfaces == 2)
160 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s)\n",
161 num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
162 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
163 DIFF(mi->ts_sent, mi->ts_rx_final));
165 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s)\n",
166 num, S(mi->ts_sent), sent,
167 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
168 S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
169 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
170 DIFF(mi->ts_sent, mi->ts_rx_onwire),
171 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
172 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
179 int msg_info_store(FILE *f, struct msg_info *mi)
181 struct timespec diff;
182 void *local = talloc_new (NULL);
185 #define S(ts) tstamp_str(local, &ts)
186 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
188 if (num_interfaces == 2)
189 fprintf(f, "%ld %d %d %s\n",
190 num, mi->id, mi->length,
191 DIFF(mi->ts_sent, mi->ts_rx_final_kern));
193 fprintf(f, "%ld %d %d %s\n",
194 num, mi->id, mi->length,
195 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
202 /* Subtract the `struct timespec' values X and Y, storing the result in
203 RESULT. Return 1 if the difference is negative, otherwise 0. */
205 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
207 struct timespec ylocal = *yy, *y = &ylocal;
208 /* Perform the carry for the later subtraction by updating Y. */
209 if (x->tv_nsec < y->tv_nsec) {
210 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
211 y->tv_nsec -= 1000000000 * nsec;
214 if (x->tv_nsec - y->tv_nsec > 1000000000) {
215 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
216 y->tv_nsec += 1000000000 * nsec;
220 /* Compute the time remaining to wait.
221 `tv_nsec' is certainly positive. */
222 result->tv_sec = x->tv_sec - y->tv_sec;
223 result->tv_nsec = x->tv_nsec - y->tv_nsec;
225 /* Return 1 if result is negative. */
226 return x->tv_sec < y->tv_sec;
229 void dbg_print_timespec(char *msg, struct timespec *tv)
232 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
235 static inline unsigned get_msg_latency_us(struct msg_info *mi)
237 struct timespec diff;
238 if (num_interfaces == 3)
240 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
242 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
245 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
247 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
248 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
251 void set_sched_policy_and_prio(int policy, int rtprio)
253 struct sched_param scheduling_parameters;
254 int maxprio=sched_get_priority_max(policy);
255 int minprio=sched_get_priority_min(policy);
257 if((rtprio < minprio) || (rtprio > maxprio))
258 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
261 scheduling_parameters.sched_priority = rtprio;
263 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
264 error(1, errno, "pthread_setschedparam error");
267 void term_handler(int signum)
272 static inline int sock_get_if_index(int s, const char *if_name)
277 strcpy(ifr.ifr_name, if_name);
278 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
279 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
280 return ifr.ifr_ifindex;
283 static inline get_tstamp(struct timespec *ts)
285 clock_gettime(CLOCK_REALTIME, ts);
299 debugfs = "/sys/kernel/debug";
301 strcpy(path, debugfs);
302 strcat(path,"/tracing/tracing_on");
303 trace_fd = open(path, O_WRONLY);
305 write(trace_fd, "1", 1);
307 strcpy(path, debugfs);
308 strcat(path,"/tracing/trace_marker");
309 marker_fd = open(path, O_WRONLY);
311 strcpy(path, debugfs);
312 strcat(path,"/tracing/set_ftrace_pid");
313 f = fopen(path, "w");
314 fprintf(f, "%d\n", getpid());
316 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
317 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
318 system("echo > /sys/kernel/debug/tracing/trace");
319 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
324 static inline void trace_on()
327 write(trace_fd, "1", 1);
330 static inline void trace_off(int ret)
332 if (marker_fd >= 0) {
334 sprintf(marker, "write returned %d\n", ret);
335 write(marker_fd, marker, strlen(marker));
338 write(trace_fd, "0", 1);
341 void msg_info_free(struct msg_info *mi)
346 int send_frame(int socket)
348 struct can_frame frame;
351 static int curr_msg = -1;
357 while (msg_infos[i].id != -1 && i != curr_msg) {
363 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
367 frame.can_id = opt.id;
369 error(1, 0, "Length < 2 is not yet supported");
370 frame.can_dlc = opt.length;
372 memcpy(frame.data, &idx, sizeof(idx));
373 mi = frame2info(&frame);
375 mi->id = frame.can_id;
376 mi->length = frame.can_dlc;
377 get_tstamp(&mi->ts_sent);
381 ret = write(socket, &frame, sizeof(frame));
389 static inline void get_next_timeout(struct timespec *timeout)
392 static struct timespec last = {-1, 0 };
394 clock_gettime(CLOCK_MONOTONIC, &now);
396 if (last.tv_sec == -1)
398 if (opt.period_us != 0) {
399 last.tv_sec += opt.period_us/1000000;
400 last.tv_nsec += (opt.period_us%1000000)*1000;
401 while (last.tv_nsec >= 1000000000) {
402 last.tv_nsec -= 1000000000;
405 if (timespec_subtract(timeout, &last, &now) /* is negative */) {
407 memset(timeout, 0, sizeof(*timeout));
409 } else if (opt.timeout_ms != 0) {
410 timeout->tv_sec = opt.timeout_ms/1000;
411 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
413 error(1, 0, "Timeout and period cannot be both zero");
416 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
418 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
421 struct cmsghdr *cmsg;
422 struct sockaddr_can addr;
424 static uint64_t dropcnt = 0;
426 iov.iov_base = frame;
427 msg.msg_name = &addr;
430 msg.msg_control = &ctrlmsg;
432 /* these settings may be modified by recvmsg() */
433 iov.iov_len = sizeof(*frame);
434 msg.msg_namelen = sizeof(addr);
435 msg.msg_controllen = sizeof(ctrlmsg);
438 nbytes = recvmsg(s, &msg, 0);
440 error(1, errno, "recvmsg");
442 if (nbytes < sizeof(struct can_frame))
443 error(1, 0, "recvmsg: incomplete CAN frame\n");
446 MEMSET_ZERO(*ts_kern);
447 for (cmsg = CMSG_FIRSTHDR(&msg);
448 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
449 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
450 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
451 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
452 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
453 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
458 void process_tx(int s)
460 error(1, 0, "%s: not implemented", __FUNCTION__);
463 void process_on_wire_rx(int s)
465 struct timespec ts_kern, ts_user, ts_diff;
466 struct can_frame frame;
468 receive(s, &frame, &ts_kern, &ts_user);
469 mi = frame2info(&frame);
470 mi->ts_rx_onwire_kern = ts_kern;
471 mi->ts_rx_onwire = ts_user;
475 void process_final_rx(int s)
477 struct timespec ts_kern, ts_user, ts_diff;
478 struct can_frame frame;
482 receive(s, &frame, &ts_kern, &ts_user);
483 mi = frame2info(&frame);
484 mi->ts_rx_final_kern = ts_kern;
485 mi->ts_rx_final = ts_user;
486 mi->received = frame;
489 histogram_add(&histogram, get_msg_latency_us(mi));
491 ret = write(completion_pipe[1], &mi, sizeof(mi));
493 error(1, errno, "completion_pipe write");
496 void *measure_thread(void *arg)
499 struct pollfd pfd[3];
500 struct timespec timeout;
501 struct sockaddr_can addr;
503 unsigned msg_in_progress = 0;
507 for (i=0; i<num_interfaces; i++) {
508 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
509 error(1, errno, "socket");
511 addr.can_family = AF_CAN;
512 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
514 if (i == 0) { /* TX socket */
515 /* disable default receive filter on this RAW socket */
516 /* This is obsolete as we do not read from the socket at all, but for */
517 /* this reason we can remove the receive list in the Kernel to save a */
518 /* little (really a very little!) CPU usage. */
519 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
520 error(1, errno, "SOL_CAN_RAW");
523 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
524 error(1, errno, "bind");
526 const int timestamp_on = 1;
527 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
528 ×tamp_on, sizeof(timestamp_on)) < 0)
529 error(1, errno, "setsockopt SO_TIMESTAMP");
531 const int dropmonitor_on = 1;
532 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
533 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
534 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
538 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
540 pfd[i].events = POLLIN;
543 set_sched_policy_and_prio(SCHED_FIFO, 40);
547 ret = send_frame(pfd[0].fd); \
548 if (ret != sizeof(struct can_frame)) { \
549 if (ret == -1 && errno == ENOBUFS && opt.period_us == 0 && !opt.oneattime) { \
551 /* Ignore this error - pfifo_fast qeuue is full */ \
553 error(1, errno, "send_frame (line %d)", __LINE__); \
566 while (!finish_flag &&
567 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
569 get_next_timeout(&timeout);
570 //printf("ppoll"); fflush(stdout);
571 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
572 //printf("=%d\n", ret);
575 if (!INTERRUPTED_SYSCALL(errno))
576 error(1, errno, "ppoll");
580 if (opt.count == 0 || count < opt.count) {
584 error(1, 0, "poll timeout");
588 if (pfd[0].revents & (POLLIN|POLLERR)) {
589 process_tx(pfd[0].fd);
591 if (pfd[0].revents & POLLOUT) {
592 if (opt.count == 0 || count < opt.count)
597 if (num_interfaces == 3 && pfd[1].revents != 0) {
598 process_on_wire_rx(pfd[1].fd);
602 i = (num_interfaces == 2) ? 1 : 2;
603 if (pfd[i].revents != 0) {
604 process_final_rx(pfd[i].fd);
607 if ((opt.count == 0 || count < opt.count) &&
615 for (i=0; i<num_interfaces; i++)
621 struct poptOption optionsTable[] = {
622 { "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" },
623 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
624 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
625 { "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"},
626 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
627 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
628 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
629 { "file", 'f', POPT_ARG_STRING, NULL, 'f', "File where to store results", "filename"},
630 { "histogram", 'h', POPT_ARG_STRING, NULL, 'h', "Store histogram in file", "filename"},
631 { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.length, 0, "The length of generated messages", "bytes"},
632 { "userhist", 'u', POPT_ARG_NONE, &opt.userhist, 0, "Generate histogram from userspace timestamps"},
634 { NULL, 0, 0, NULL, 0 }
637 int parse_options(int argc, const char *argv[])
640 poptContext optCon; /* context for parsing command-line options */
642 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
643 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
645 /* Now do options processing */
646 while ((c = poptGetNextOpt(optCon)) >= 0) {
652 opt.file = fopen(poptGetOptArg(optCon), "w");
654 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
657 opt.histogram = fopen(poptGetOptArg(optCon), "w");
659 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
664 error(1, 0, "%s: %s\n",
665 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
668 if (num_interfaces < 2 || num_interfaces > 3)
669 error(1, 0, "-d option must be given exactly 2 or 3 times");
671 if (opt.oneattime && opt.period_us)
672 error(1, 0, "oneattime and period cannot be specified at the same time");
674 poptFreeContext(optCon);
680 int main(int argc, const char *argv[])
686 parse_options(argc, argv);
688 mlockall(MCL_CURRENT | MCL_FUTURE);
690 signal(SIGINT, term_handler);
691 signal(SIGTERM, term_handler);
693 for (i=0; i<MAX_INFOS; i++)
694 msg_infos[i].id = -1;
697 histogram_init(&histogram, 5000000, 1);
700 ret = pipe(completion_pipe);
702 error(1, errno, "pipe");
703 ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
705 error(1, errno, "pipe fcntl");
709 pthread_create(&thread, 0, measure_thread, NULL);
711 struct timespec next, now, diff;
712 clock_gettime(CLOCK_MONOTONIC, &next);
714 while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
715 struct pollfd pfd[1];
716 pfd[0].fd = completion_pipe[0];
717 pfd[0].events = POLLIN;
718 ret = poll(pfd, 1, 100);
719 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
720 error(1, errno, "poll main");
721 if (ret > 0 && (pfd[0].revents & POLLIN)) {
724 ret = read(completion_pipe[0], &mi, sizeof(mi));
725 if (ret < sizeof(mi))
726 error(1, errno, "read completion returned %d", ret);
728 msg_info_print(opt.file, mi);
733 clock_gettime(CLOCK_MONOTONIC, &now);
734 if (timespec_subtract(&diff, &next, &now)) {
735 printf("\rMessage %d", count);
737 next.tv_nsec += 100000000;
738 while (next.tv_nsec >= 1000000000) {
739 next.tv_nsec -= 1000000000;
744 printf("\rMessage %d\n", count);
746 pthread_join(thread, NULL);
748 close(completion_pipe[0]);
749 close(completion_pipe[1]);
752 histogram_fprint(&histogram, opt.histogram);
753 fclose(opt.histogram);
759 printf("overrun=%d\n", stats.overrun);
761 printf("enobufs=%d\n", stats.enobufs);