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 */
67 /* Temporary variables */
73 struct options opt = {
86 int num_interfaces = 0;
87 int count = 0; /* Number of sent messages */
88 unsigned msg_in_progress = 0;
89 int completion_pipe[2];
94 struct timespec ts_sent, ts_sent_kern;
95 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
96 struct timespec ts_rx_final, ts_rx_final_kern;
97 struct can_frame sent, received;
100 #define MAX_INFOS 10000
101 struct msg_info msg_infos[MAX_INFOS];
103 struct histogram histogram;
105 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
106 /* documentation see lib.h */
109 int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
111 if (cf->can_id & CAN_ERR_FLAG) {
112 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
114 } else if (cf->can_id & CAN_EFF_FLAG) {
115 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
118 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
122 if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
123 sprintf(buf+offset, "R");
125 for (i = 0; i < dlc; i++) {
126 sprintf(buf+offset, "%02X", cf->data[i]);
128 if (sep && (i+1 < dlc))
129 sprintf(buf+offset++, ".");
133 static inline struct msg_info *frame2info(struct can_frame *frame)
136 if (frame->can_dlc >= 2) {
137 memcpy(&idx, frame->data, sizeof(idx));
138 if (idx >= MAX_INFOS)
139 error(1, 0, "%s idx too high", __FUNCTION__);
142 error(1, 0, "%s error", __FUNCTION__);
144 return &msg_infos[idx];
147 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
149 return talloc_asprintf(ctx, "%ld.%06ld",
150 tstamp->tv_sec, tstamp->tv_nsec/1000);
153 void msg_info_print(FILE *f, struct msg_info *mi)
155 struct timespec diff;
156 void *local = talloc_new (NULL);
158 char sent[64], received[64];
160 sprint_canframe(sent, &mi->sent, true);
161 sprint_canframe(received, &mi->received, true);
163 #define S(ts) tstamp_str(local, &ts)
164 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
166 if (num_interfaces == 2)
167 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s)\n",
168 num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
169 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
170 DIFF(mi->ts_sent, mi->ts_rx_final));
172 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s)\n",
173 num, S(mi->ts_sent), sent,
174 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
175 S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
176 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
177 DIFF(mi->ts_sent, mi->ts_rx_onwire),
178 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
179 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
186 int msg_info_store(FILE *f, struct msg_info *mi)
188 struct timespec diff;
189 void *local = talloc_new (NULL);
192 #define S(ts) tstamp_str(local, &ts)
193 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
195 if (num_interfaces == 2)
196 fprintf(f, "%ld %d %d %s\n",
197 num, mi->id, mi->length,
198 DIFF(mi->ts_sent, mi->ts_rx_final_kern));
200 fprintf(f, "%ld %d %d %s\n",
201 num, mi->id, mi->length,
202 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
209 /* Subtract the `struct timespec' values X and Y, storing the result in
210 RESULT. Return 1 if the difference is negative, otherwise 0. */
212 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
214 struct timespec ylocal = *yy, *y = &ylocal;
215 /* Perform the carry for the later subtraction by updating Y. */
216 if (x->tv_nsec < y->tv_nsec) {
217 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
218 y->tv_nsec -= 1000000000 * nsec;
221 if (x->tv_nsec - y->tv_nsec > 1000000000) {
222 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
223 y->tv_nsec += 1000000000 * nsec;
227 /* Compute the time remaining to wait.
228 `tv_nsec' is certainly positive. */
229 result->tv_sec = x->tv_sec - y->tv_sec;
230 result->tv_nsec = x->tv_nsec - y->tv_nsec;
232 /* Return 1 if result is negative. */
233 return x->tv_sec < y->tv_sec;
236 void dbg_print_timespec(char *msg, struct timespec *tv)
239 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
242 static inline unsigned get_msg_latency_us(struct msg_info *mi)
244 struct timespec diff;
245 if (num_interfaces == 3)
247 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
249 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
252 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
254 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
255 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
258 void set_sched_policy_and_prio(int policy, int rtprio)
260 struct sched_param scheduling_parameters;
261 int maxprio=sched_get_priority_max(policy);
262 int minprio=sched_get_priority_min(policy);
264 if((rtprio < minprio) || (rtprio > maxprio))
265 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
268 scheduling_parameters.sched_priority = rtprio;
270 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
271 error(1, errno, "pthread_setschedparam error");
274 void term_handler(int signum)
279 static inline int sock_get_if_index(int s, const char *if_name)
284 strcpy(ifr.ifr_name, if_name);
285 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
286 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
287 return ifr.ifr_ifindex;
290 static inline get_tstamp(struct timespec *ts)
292 clock_gettime(CLOCK_REALTIME, ts);
306 debugfs = "/sys/kernel/debug";
308 strcpy(path, debugfs);
309 strcat(path,"/tracing/tracing_on");
310 trace_fd = open(path, O_WRONLY);
312 write(trace_fd, "1", 1);
314 strcpy(path, debugfs);
315 strcat(path,"/tracing/trace_marker");
316 marker_fd = open(path, O_WRONLY);
318 strcpy(path, debugfs);
319 strcat(path,"/tracing/set_ftrace_pid");
320 f = fopen(path, "w");
321 fprintf(f, "%d\n", getpid());
323 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
324 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
325 system("echo > /sys/kernel/debug/tracing/trace");
326 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
331 static inline void trace_on()
334 write(trace_fd, "1", 1);
337 static inline void trace_off(int ret)
339 if (marker_fd >= 0) {
341 sprintf(marker, "write returned %d\n", ret);
342 write(marker_fd, marker, strlen(marker));
345 write(trace_fd, "0", 1);
348 void msg_info_free(struct msg_info *mi)
353 int send_frame(int socket)
355 struct can_frame frame;
358 static int curr_msg = -1;
364 while (msg_infos[i].id != -1 && i != curr_msg) {
370 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
374 frame.can_id = opt.id;
376 error(1, 0, "Length < 2 is not yet supported");
377 frame.can_dlc = opt.length;
379 memcpy(frame.data, &idx, sizeof(idx));
380 mi = frame2info(&frame);
382 mi->id = frame.can_id;
383 mi->length = frame.can_dlc;
384 get_tstamp(&mi->ts_sent);
388 ret = write(socket, &frame, sizeof(frame));
396 static inline send_and_check(int s)
400 if (ret != sizeof(struct can_frame)) {
401 /* if (ret == -1 && errno == ENOBUFS && opt.period_us == 0 && !opt.oneattime) { */
402 /* stats.enobufs++; */
403 /* /\* Ignore this error - pfifo_fast qeuue is full *\/ */
405 error(1, errno, "send_frame (line %d)", __LINE__);
412 static inline void get_next_timeout(struct timespec *timeout)
415 static struct timespec last = {-1, 0 };
417 clock_gettime(CLOCK_MONOTONIC, &now);
419 if (last.tv_sec == -1)
421 if (opt.period_us != 0) {
422 last.tv_sec += opt.period_us/1000000;
423 last.tv_nsec += (opt.period_us%1000000)*1000;
424 while (last.tv_nsec >= 1000000000) {
425 last.tv_nsec -= 1000000000;
428 if (timespec_subtract(timeout, &last, &now) /* is negative */) {
430 memset(timeout, 0, sizeof(*timeout));
432 } else if (opt.timeout_ms != 0) {
433 timeout->tv_sec = opt.timeout_ms/1000;
434 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
436 error(1, 0, "Timeout and period cannot be both zero");
439 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
441 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
444 struct cmsghdr *cmsg;
445 struct sockaddr_can addr;
447 static uint64_t dropcnt = 0;
449 iov.iov_base = frame;
450 msg.msg_name = &addr;
453 msg.msg_control = &ctrlmsg;
455 /* these settings may be modified by recvmsg() */
456 iov.iov_len = sizeof(*frame);
457 msg.msg_namelen = sizeof(addr);
458 msg.msg_controllen = sizeof(ctrlmsg);
461 nbytes = recvmsg(s, &msg, 0);
463 error(1, errno, "recvmsg");
465 if (nbytes < sizeof(struct can_frame))
466 error(1, 0, "recvmsg: incomplete CAN frame\n");
469 MEMSET_ZERO(*ts_kern);
470 for (cmsg = CMSG_FIRSTHDR(&msg);
471 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
472 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
473 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
474 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
475 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
476 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
481 void process_tx(int s)
483 error(1, 0, "%s: not implemented", __FUNCTION__);
486 void process_on_wire_rx(int s)
488 struct timespec ts_kern, ts_user, ts_diff;
489 struct can_frame frame;
491 receive(s, &frame, &ts_kern, &ts_user);
492 mi = frame2info(&frame);
493 mi->ts_rx_onwire_kern = ts_kern;
494 mi->ts_rx_onwire = ts_user;
498 void process_final_rx(int s)
500 struct timespec ts_kern, ts_user, ts_diff;
501 struct can_frame frame;
505 receive(s, &frame, &ts_kern, &ts_user);
506 mi = frame2info(&frame);
507 mi->ts_rx_final_kern = ts_kern;
508 mi->ts_rx_final = ts_user;
509 mi->received = frame;
511 histogram_add(&histogram, get_msg_latency_us(mi));
513 ret = write(completion_pipe[1], &mi, sizeof(mi));
515 error(1, errno, "completion_pipe write");
518 void *measure_thread(void *arg)
521 struct pollfd pfd[3];
522 struct timespec timeout;
523 struct sockaddr_can addr;
528 for (i=0; i<num_interfaces; i++) {
529 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
530 error(1, errno, "socket");
532 addr.can_family = AF_CAN;
533 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
535 if (i == 0) { /* TX socket */
536 /* disable default receive filter on this RAW socket */
537 /* This is obsolete as we do not read from the socket at all, but for */
538 /* this reason we can remove the receive list in the Kernel to save a */
539 /* little (really a very little!) CPU usage. */
540 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
541 error(1, errno, "SOL_CAN_RAW");
544 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
545 error(1, errno, "bind");
547 const int timestamp_on = 1;
548 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
549 ×tamp_on, sizeof(timestamp_on)) < 0)
550 error(1, errno, "setsockopt SO_TIMESTAMP");
552 const int dropmonitor_on = 1;
553 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
554 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
555 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
559 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
561 pfd[i].events = POLLIN;
564 set_sched_policy_and_prio(SCHED_FIFO, 40);
566 #define SEND() send_and_check(pfd[0].fd)
571 while (!finish_flag &&
572 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
574 get_next_timeout(&timeout);
575 //printf("ppoll"); fflush(stdout);
576 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
577 //printf("=%d\n", ret);
580 if (!INTERRUPTED_SYSCALL(errno))
581 error(1, errno, "ppoll");
585 if (opt.count == 0 || count < opt.count) {
589 error(1, 0, "poll timeout");
593 if (pfd[0].revents & (POLLIN|POLLERR)) {
594 process_tx(pfd[0].fd);
596 if (pfd[0].revents & POLLOUT) {
597 if (opt.count == 0 || count < opt.count)
602 if (num_interfaces == 3 && pfd[1].revents != 0) {
603 process_on_wire_rx(pfd[1].fd);
607 i = (num_interfaces == 2) ? 1 : 2;
608 if (pfd[i].revents != 0) {
609 process_final_rx(pfd[i].fd);
612 if ((opt.count == 0 || count < opt.count) &&
620 for (i=0; i<num_interfaces; i++)
626 struct poptOption optionsTable[] = {
627 { "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" },
628 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
629 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
630 { "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"},
631 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
632 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
633 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
634 { "name", 'n', POPT_ARG_STRING, &opt.name, 0, "Prefix of the generated files"},
635 { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.length, 0, "The length of generated messages", "bytes"},
636 { "userhist", 'u', POPT_ARG_NONE, &opt.userhist, 0, "Generate histogram from userspace timestamps"},
637 { "quiet", 'q', POPT_ARG_NONE, &opt.quiet, 0, "Do not print progress and statistics"},
639 { NULL, 0, 0, NULL, 0 }
642 int parse_options(int argc, const char *argv[])
645 poptContext optCon; /* context for parsing command-line options */
646 void *local = talloc_new (NULL);
648 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
649 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
651 /* Now do options processing */
652 while ((c = poptGetNextOpt(optCon)) >= 0) {
660 error(1, 0, "%s: %s\n",
661 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
664 if (num_interfaces < 2 || num_interfaces > 3)
665 error(1, 0, "-d option must be given exactly 2 or 3 times");
667 if (opt.oneattime && opt.period_us)
668 error(1, 0, "oneattime and period cannot be specified at the same time");
671 char *f = talloc_asprintf(local, "%s-msgs.txt", opt.name);
672 opt.f_msgs = fopen(f, "w");
674 error(1, errno, "fopen: %s", f);
678 char *f = talloc_asprintf(local, "%s-hist.txt", opt.name);
679 opt.f_hist = fopen(f, "w");
681 error(1, errno, "fopen: %s", f);
685 char *f = talloc_asprintf(local, "%s-stat.txt", opt.name);
686 opt.f_stat = fopen(f, "w");
688 error(1, errno, "fopen: %s", f);
691 poptFreeContext(optCon);
696 void print_progress()
699 printf("\rSent %5d, in progress %5d", count, msg_in_progress);
704 int main(int argc, const char *argv[])
710 parse_options(argc, argv);
712 mlockall(MCL_CURRENT | MCL_FUTURE);
714 signal(SIGINT, term_handler);
715 signal(SIGTERM, term_handler);
717 for (i=0; i<MAX_INFOS; i++)
718 msg_infos[i].id = -1;
720 histogram_init(&histogram, 5000000, 1);
722 ret = pipe(completion_pipe);
724 error(1, errno, "pipe");
725 ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
727 error(1, errno, "pipe fcntl");
731 pthread_create(&thread, 0, measure_thread, NULL);
733 struct timespec next, now, diff, allsent = {0,0};
734 clock_gettime(CLOCK_MONOTONIC, &next);
736 while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
737 struct pollfd pfd[1];
738 pfd[0].fd = completion_pipe[0];
739 pfd[0].events = POLLIN;
740 ret = poll(pfd, 1, 100);
741 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
742 error(1, errno, "poll main");
743 if (ret > 0 && (pfd[0].revents & POLLIN)) {
746 ret = read(completion_pipe[0], &mi, sizeof(mi));
747 if (ret < sizeof(mi))
748 error(1, errno, "read completion returned %d", ret);
749 msg_info_print(opt.f_msgs, mi);
754 clock_gettime(CLOCK_MONOTONIC, &now);
755 if (timespec_subtract(&diff, &next, &now)) {
757 next.tv_nsec += 100000000;
758 while (next.tv_nsec >= 1000000000) {
759 next.tv_nsec -= 1000000000;
763 if (opt.count != 0 && count >= opt.count) {
764 if (allsent.tv_sec == 0)
766 timespec_subtract(&diff, &now, &allsent);
767 if (diff.tv_sec >= 1)
775 stats.lost = msg_in_progress;
777 pthread_join(thread, NULL);
779 close(completion_pipe[0]);
780 close(completion_pipe[1]);
782 histogram_fprint(&histogram, opt.f_hist);
787 fprintf(opt.f_stat, "sent=%d\n", count);
788 fprintf(opt.f_stat, "overrun=%d\n", stats.overrun);
789 if (stats.overrun && !opt.quiet)
790 printf("overrun=%d\n", stats.overrun);
791 fprintf(opt.f_stat, "enobufs=%d\n", stats.enobufs);
792 if (stats.enobufs && !opt.quiet)
793 printf("enobufs=%d\n", stats.enobufs);
794 fprintf(opt.f_stat, "lost=%d\n", stats.lost);
795 if (stats.lost && !opt.quiet)
796 printf("lost=%d\n", stats.lost);