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 = {
84 struct timespec tic, tac;
86 unsigned invalid_frame;
89 int num_interfaces = 0;
90 int count = 0; /* Number of sent messages */
91 unsigned msg_in_progress = 0;
92 int completion_pipe[2];
97 struct timespec ts_sent, ts_sent_kern;
98 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
99 struct timespec ts_rx_final, ts_rx_final_kern;
100 struct can_frame sent, received;
103 #define MAX_INFOS 10000
104 struct msg_info msg_infos[MAX_INFOS];
106 struct histogram histogram;
108 void sprint_canframe(char *buf , struct can_frame *cf, int sep) {
109 /* documentation see lib.h */
112 int dlc = (cf->can_dlc > 8)? 8 : cf->can_dlc;
114 if (cf->can_id & CAN_ERR_FLAG) {
115 sprintf(buf, "%08X#", cf->can_id & (CAN_ERR_MASK|CAN_ERR_FLAG));
117 } else if (cf->can_id & CAN_EFF_FLAG) {
118 sprintf(buf, "%08X#", cf->can_id & CAN_EFF_MASK);
121 sprintf(buf, "%03X#", cf->can_id & CAN_SFF_MASK);
125 if (cf->can_id & CAN_RTR_FLAG) /* there are no ERR frames with RTR */
126 sprintf(buf+offset, "R");
128 for (i = 0; i < dlc; i++) {
129 sprintf(buf+offset, "%02X", cf->data[i]);
131 if (sep && (i+1 < dlc))
132 sprintf(buf+offset++, ".");
136 static inline struct msg_info *frame2info(struct can_frame *frame)
139 if (frame->can_dlc >= 2) {
140 memcpy(&idx, frame->data, sizeof(idx));
141 if (idx >= MAX_INFOS)
142 error(1, 0, "%s idx too high", __FUNCTION__);
145 error(1, 0, "%s error", __FUNCTION__);
147 return &msg_infos[idx];
150 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
152 return talloc_asprintf(ctx, "%ld.%06ld",
153 tstamp->tv_sec, tstamp->tv_nsec/1000);
156 void msg_info_print(FILE *f, struct msg_info *mi)
158 struct timespec diff;
159 void *local = talloc_new (NULL);
161 char sent[64], received[64];
163 sprint_canframe(sent, &mi->sent, true);
164 sprint_canframe(received, &mi->received, true);
166 #define S(ts) tstamp_str(local, &ts)
167 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
169 switch (num_interfaces) {
171 fprintf(f, "%ld: %s %s -> %s (%s) %s = %s (%s)\n",
172 num, S(mi->ts_sent), sent, S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
173 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
174 DIFF(mi->ts_sent, mi->ts_rx_final));
177 fprintf(f, "%ld: %s %s -> %s (%s) -> %s (%s) %s = %s (%s), %s (%s)\n",
178 num, S(mi->ts_sent), sent,
179 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
180 S(mi->ts_rx_final_kern), S(mi->ts_rx_final), received,
181 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
182 DIFF(mi->ts_sent, mi->ts_rx_onwire),
183 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
184 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
193 /* Subtract the `struct timespec' values X and Y, storing the result in
194 RESULT. Return 1 if the difference is negative, otherwise 0. */
196 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
198 struct timespec ylocal = *yy, *y = &ylocal;
199 /* Perform the carry for the later subtraction by updating Y. */
200 if (x->tv_nsec < y->tv_nsec) {
201 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
202 y->tv_nsec -= 1000000000 * nsec;
205 if (x->tv_nsec - y->tv_nsec > 1000000000) {
206 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
207 y->tv_nsec += 1000000000 * nsec;
211 /* Compute the time remaining to wait.
212 `tv_nsec' is certainly positive. */
213 result->tv_sec = x->tv_sec - y->tv_sec;
214 result->tv_nsec = x->tv_nsec - y->tv_nsec;
216 /* Return 1 if result is negative. */
217 return x->tv_sec < y->tv_sec;
220 void dbg_print_timespec(char *msg, struct timespec *tv)
223 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
226 static inline unsigned get_msg_latency_us(struct msg_info *mi)
228 struct timespec diff;
229 switch (num_interfaces) {
232 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_rx_onwire);
234 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
238 timespec_subtract(&diff, &mi->ts_rx_final, &mi->ts_sent);
240 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
245 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
248 void set_sched_policy_and_prio(int policy, int rtprio)
250 struct sched_param scheduling_parameters;
251 int maxprio=sched_get_priority_max(policy);
252 int minprio=sched_get_priority_min(policy);
254 if((rtprio < minprio) || (rtprio > maxprio))
255 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
258 scheduling_parameters.sched_priority = rtprio;
260 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
261 error(1, errno, "pthread_setschedparam error");
264 void term_handler(int signum)
269 static inline int sock_get_if_index(int s, const char *if_name)
274 strcpy(ifr.ifr_name, if_name);
275 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
276 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
277 return ifr.ifr_ifindex;
280 static inline get_tstamp(struct timespec *ts)
282 clock_gettime(CLOCK_REALTIME, ts);
296 debugfs = "/sys/kernel/debug";
298 strcpy(path, debugfs);
299 strcat(path,"/tracing/tracing_on");
300 trace_fd = open(path, O_WRONLY);
302 write(trace_fd, "1", 1);
304 strcpy(path, debugfs);
305 strcat(path,"/tracing/trace_marker");
306 marker_fd = open(path, O_WRONLY);
308 strcpy(path, debugfs);
309 strcat(path,"/tracing/set_ftrace_pid");
310 f = fopen(path, "w");
311 fprintf(f, "%d\n", getpid());
313 system("echo function_graph > /sys/kernel/debug/tracing/current_tracer");
314 system("echo can_send > /sys/kernel/debug/tracing/set_graph_function");
315 system("echo > /sys/kernel/debug/tracing/trace");
316 system("echo 1 > /sys/kernel/debug/tracing/tracing_enabled");
321 static inline void trace_on()
324 write(trace_fd, "1", 1);
327 static inline void trace_off(int ret)
329 if (marker_fd >= 0) {
331 sprintf(marker, "write returned %d\n", ret);
332 write(marker_fd, marker, strlen(marker));
335 write(trace_fd, "0", 1);
338 static inline void msg_info_free(struct msg_info *mi)
343 static inline bool msg_info_used(struct msg_info *mi)
348 int send_frame(int socket)
350 struct can_frame frame;
353 static int curr_msg = -1;
359 while (msg_info_used(&msg_infos[i]) && i != curr_msg) {
365 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
369 frame.can_id = opt.id;
371 error(1, 0, "Length < 2 is not yet supported");
372 frame.can_dlc = opt.length;
374 memcpy(frame.data, &idx, sizeof(idx));
375 mi = frame2info(&frame);
377 mi->id = frame.can_id;
378 mi->length = frame.can_dlc;
379 get_tstamp(&mi->ts_sent);
383 ret = write(socket, &frame, sizeof(frame));
386 if (ret == -1 || num_interfaces == 1)
391 static inline send_and_check(int s)
395 if (ret != sizeof(struct can_frame)) {
396 /* if (ret == -1 && errno == ENOBUFS && opt.period_us == 0 && !opt.oneattime) { */
397 /* stats.enobufs++; */
398 /* /\* Ignore this error - pfifo_fast qeuue is full *\/ */
400 error(1, errno, "send_frame (line %d)", __LINE__);
407 static inline void get_next_timeout(struct timespec *timeout)
410 static struct timespec last = {-1, 0 };
412 clock_gettime(CLOCK_MONOTONIC, &now);
414 if (last.tv_sec == -1)
416 if (opt.period_us != 0) {
417 last.tv_sec += opt.period_us/1000000;
418 last.tv_nsec += (opt.period_us%1000000)*1000;
419 while (last.tv_nsec >= 1000000000) {
420 last.tv_nsec -= 1000000000;
423 if (timespec_subtract(timeout, &last, &now) /* is negative */) {
425 memset(timeout, 0, sizeof(*timeout));
427 } else if (opt.timeout_ms != 0) {
428 timeout->tv_sec = opt.timeout_ms/1000;
429 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
431 error(1, 0, "Timeout and period cannot be both zero");
434 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
436 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
439 struct cmsghdr *cmsg;
440 struct sockaddr_can addr;
442 static uint64_t dropcnt = 0;
444 iov.iov_base = frame;
445 msg.msg_name = &addr;
448 msg.msg_control = &ctrlmsg;
450 /* these settings may be modified by recvmsg() */
451 iov.iov_len = sizeof(*frame);
452 msg.msg_namelen = sizeof(addr);
453 msg.msg_controllen = sizeof(ctrlmsg);
456 nbytes = recvmsg(s, &msg, 0);
458 error(1, errno, "recvmsg");
460 if (nbytes < sizeof(struct can_frame))
461 error(1, 0, "recvmsg: incomplete CAN frame\n");
464 MEMSET_ZERO(*ts_kern);
465 for (cmsg = CMSG_FIRSTHDR(&msg);
466 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
467 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
468 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
469 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
470 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
471 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
476 void process_tx(int s)
478 error(1, 0, "%s: not implemented", __FUNCTION__);
481 void process_on_wire_rx(int s)
483 struct timespec ts_kern, ts_user, ts_diff;
484 struct can_frame frame;
486 receive(s, &frame, &ts_kern, &ts_user);
487 mi = frame2info(&frame);
488 if (msg_info_used(mi)) {
489 mi->ts_rx_onwire_kern = ts_kern;
490 mi->ts_rx_onwire = ts_user;
492 stats.invalid_frame++;
496 void process_final_rx(int s)
498 struct timespec ts_kern, ts_user, ts_diff;
499 struct can_frame frame;
503 receive(s, &frame, &ts_kern, &ts_user);
504 mi = frame2info(&frame);
505 mi->ts_rx_final_kern = ts_kern;
506 mi->ts_rx_final = ts_user;
507 mi->received = frame;
509 histogram_add(&histogram, get_msg_latency_us(mi));
511 ret = write(completion_pipe[1], &mi, sizeof(mi));
513 error(1, errno, "completion_pipe write");
516 void *measure_thread(void *arg)
519 struct pollfd pfd[3];
520 struct timespec timeout;
521 struct sockaddr_can addr;
523 int consecutive_timeouts = 0;
527 for (i=0; i<num_interfaces; i++) {
528 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
529 error(1, errno, "socket");
531 addr.can_family = AF_CAN;
532 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
534 if (i == 0) { /* TX socket */
535 /* disable default receive filter on this RAW socket */
536 /* This is obsolete as we do not read from the socket at all, but for */
537 /* this reason we can remove the receive list in the Kernel to save a */
538 /* little (really a very little!) CPU usage. */
539 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
540 error(1, errno, "SOL_CAN_RAW");
543 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
544 error(1, errno, "bind");
546 const int timestamp_on = 1;
547 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
548 ×tamp_on, sizeof(timestamp_on)) < 0)
549 error(1, errno, "setsockopt SO_TIMESTAMP");
551 const int dropmonitor_on = 1;
552 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
553 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
554 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
558 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
560 pfd[i].events = POLLIN;
563 set_sched_policy_and_prio(SCHED_FIFO, 40);
565 #define SEND() send_and_check(pfd[0].fd)
570 get_tstamp(&stats.tic);
572 while (!finish_flag &&
573 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
575 get_next_timeout(&timeout);
576 //printf("ppoll"); fflush(stdout);
577 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
578 //printf("=%d\n", ret);
581 if (!INTERRUPTED_SYSCALL(errno))
582 error(1, errno, "ppoll");
586 if (opt.count == 0 || count < opt.count) {
590 /* Lost message - send a new one */
592 consecutive_timeouts++;
593 if (consecutive_timeouts < 10)
595 else /* Something is really broken */
600 if (pfd[0].revents & (POLLIN|POLLERR)) {
601 process_tx(pfd[0].fd);
603 if (pfd[0].revents & POLLOUT) {
604 if (opt.count == 0 || count < opt.count)
609 if (num_interfaces == 3 && pfd[1].revents != 0) {
610 process_on_wire_rx(pfd[1].fd);
614 i = (num_interfaces == 2) ? 1 : 2;
615 if (pfd[i].revents != 0) {
616 consecutive_timeouts = 0;
617 process_final_rx(pfd[i].fd);
620 if ((opt.count == 0 || count < opt.count) &&
628 get_tstamp(&stats.tac);
630 for (i=0; i<num_interfaces; i++)
636 struct poptOption optionsTable[] = {
637 { "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" },
638 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
639 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
640 { "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"},
641 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
642 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
643 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
644 { "name", 'n', POPT_ARG_STRING, &opt.name, 0, "Prefix of the generated files"},
645 { "length", 'l', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.length, 0, "The length of generated messages", "bytes"},
646 { "userhist", 'u', POPT_ARG_NONE, &opt.userhist, 0, "Generate histogram from userspace timestamps"},
647 { "quiet", 'q', POPT_ARG_NONE, &opt.quiet, 0, "Do not print progress and statistics"},
649 { NULL, 0, 0, NULL, 0 }
652 int parse_options(int argc, const char *argv[])
655 poptContext optCon; /* context for parsing command-line options */
656 void *local = talloc_new (NULL);
658 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
659 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
661 /* Now do options processing */
662 while ((c = poptGetNextOpt(optCon)) >= 0) {
670 error(1, 0, "%s: %s\n",
671 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
674 if (num_interfaces < 1 || num_interfaces > 3)
675 error(1, 0, "-d option must only be given one, two or three times");
677 if (opt.oneattime && opt.period_us)
678 error(1, 0, "oneattime and period cannot be specified at the same time");
681 char *f = talloc_asprintf(local, "%s-msgs.txt", opt.name);
682 opt.f_msgs = fopen(f, "w");
684 error(1, errno, "fopen: %s", f);
688 char *f = talloc_asprintf(local, "%s-hist.txt", opt.name);
689 opt.f_hist = fopen(f, "w");
691 error(1, errno, "fopen: %s", f);
695 char *f = talloc_asprintf(local, "%s-stat.txt", opt.name);
696 opt.f_stat = fopen(f, "w");
698 error(1, errno, "fopen: %s", f);
701 poptFreeContext(optCon);
706 void print_progress()
709 if (num_interfaces > 1)
710 printf("\rSent %5d, in progress %5d", count, msg_in_progress);
712 printf("\rSent %5d", count);
717 int main(int argc, const char *argv[])
723 parse_options(argc, argv);
725 mlockall(MCL_CURRENT | MCL_FUTURE);
727 signal(SIGINT, term_handler);
728 signal(SIGTERM, term_handler);
730 for (i=0; i<MAX_INFOS; i++)
731 msg_infos[i].id = -1;
733 histogram_init(&histogram, 5000000, 1);
735 ret = pipe(completion_pipe);
737 error(1, errno, "pipe");
738 ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
740 error(1, errno, "pipe fcntl");
744 pthread_create(&thread, 0, measure_thread, NULL);
746 struct timespec next, now, diff, allsent = {0,0};
747 clock_gettime(CLOCK_MONOTONIC, &next);
749 while (!finish_flag && (opt.count == 0 || completed < opt.count)) {
750 struct pollfd pfd[1];
751 pfd[0].fd = completion_pipe[0];
752 pfd[0].events = POLLIN;
753 ret = poll(pfd, 1, 100);
754 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
755 error(1, errno, "poll main");
756 if (ret > 0 && (pfd[0].revents & POLLIN)) {
759 ret = read(completion_pipe[0], &mi, sizeof(mi));
760 if (ret < sizeof(mi))
761 error(1, errno, "read completion returned %d", ret);
762 msg_info_print(opt.f_msgs, mi);
767 clock_gettime(CLOCK_MONOTONIC, &now);
768 if (timespec_subtract(&diff, &next, &now)) {
770 next.tv_nsec += 100000000;
771 while (next.tv_nsec >= 1000000000) {
772 next.tv_nsec -= 1000000000;
776 if (opt.count != 0 && count >= opt.count) {
777 if (allsent.tv_sec == 0)
779 timespec_subtract(&diff, &now, &allsent);
780 if (diff.tv_sec >= 1)
788 stats.lost = msg_in_progress;
790 pthread_join(thread, NULL);
792 close(completion_pipe[0]);
793 close(completion_pipe[1]);
795 histogram_fprint(&histogram, opt.f_hist);
800 fprintf(opt.f_stat, "cmdline='");
801 for (i=0; i<argc; i++)
802 fprintf(opt.f_stat, "%s%s", argv[i], i < argc-1 ? " " : "");
803 fprintf(opt.f_stat, "'\n");
805 timespec_subtract(&diff, &stats.tac, &stats.tic);
806 fprintf(opt.f_stat, "duration=%s # seconds\n", tstamp_str(NULL, &diff));
808 fprintf(opt.f_stat, "sent=%d\n", count);
809 fprintf(opt.f_stat, "overrun=%d\n", stats.overrun);
810 if (stats.overrun && !opt.quiet)
811 printf("overrun=%d\n", stats.overrun);
812 fprintf(opt.f_stat, "enobufs=%d\n", stats.enobufs);
813 if (stats.enobufs && !opt.quiet)
814 printf("enobufs=%d\n", stats.enobufs);
815 fprintf(opt.f_stat, "lost=%d\n", stats.lost);
816 if (stats.lost && !opt.quiet)
817 printf("lost=%d\n", stats.lost);
818 fprintf(opt.f_stat, "timeouts=%d\n", stats.timeouts);
819 if (stats.timeouts && !opt.quiet)
820 printf("timeouts=%d\n", stats.timeouts);
821 fprintf(opt.f_stat, "invalid_frame=%d\n", stats.timeouts);
822 if (stats.timeouts && !opt.quiet)
823 printf("invalid_frame=%d\n", stats.timeouts);