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 */
64 struct options opt = {
71 int num_interfaces = 0;
72 int count = 0; /* Number of sent messages */
73 int completion_pipe[2];
78 struct timespec ts_sent, ts_sent_kern;
79 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
80 struct timespec ts_rx_final, ts_rx_final_kern;
83 #define MAX_INFOS 10000
84 struct msg_info msg_infos[MAX_INFOS];
86 struct histogram histogram;
88 static inline struct msg_info *frame2info(struct can_frame *frame)
91 if (frame->can_dlc == 2) {
92 memcpy(&idx, frame->data, sizeof(idx));
94 error(1, 0, "%s idx too high", __FUNCTION__);
96 error(1, 0, "%s error", __FUNCTION__);
97 return &msg_infos[idx];
100 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
102 return talloc_asprintf(ctx, "%ld.%06ld",
103 tstamp->tv_sec, tstamp->tv_nsec/1000);
106 void print_msg_info(struct msg_info *mi)
108 struct timespec diff;
109 void *local = talloc_new (NULL);
111 #define S(ts) tstamp_str(local, &ts)
112 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
114 if (num_interfaces == 2)
115 printf("%s -> %s (%s) = %s (%s)\n",
116 S(mi->ts_sent), S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
117 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
118 DIFF(mi->ts_sent, mi->ts_rx_final));
120 printf("%s -> %s (%s) -> %s (%s) = %s (%s), %s (%s)\n",
122 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
123 S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
124 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
125 DIFF(mi->ts_sent, mi->ts_rx_onwire),
126 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
127 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
133 int msg_info_store(FILE *f, struct msg_info *mi)
135 struct timespec diff;
136 void *local = talloc_new (NULL);
138 #define S(ts) tstamp_str(local, &ts)
139 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
141 if (num_interfaces == 2)
142 fprintf(f, "%d %d %s\n",
144 DIFF(mi->ts_sent, mi->ts_rx_final_kern));
146 fprintf(f, "%d %d %s\n",
148 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern));
155 /* Subtract the `struct timespec' values X and Y, storing the result in
156 RESULT. Return 1 if the difference is negative, otherwise 0. */
158 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
160 struct timespec ylocal = *yy, *y = &ylocal;
161 /* Perform the carry for the later subtraction by updating Y. */
162 if (x->tv_nsec < y->tv_nsec) {
163 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
164 y->tv_nsec -= 1000000000 * nsec;
167 if (x->tv_nsec - y->tv_nsec > 1000000000) {
168 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
169 y->tv_nsec += 1000000000 * nsec;
173 /* Compute the time remaining to wait.
174 `tv_nsec' is certainly positive. */
175 result->tv_sec = x->tv_sec - y->tv_sec;
176 result->tv_nsec = x->tv_nsec - y->tv_nsec;
178 /* Return 1 if result is negative. */
179 return x->tv_sec < y->tv_sec;
182 void dbg_print_timespec(char *msg, struct timespec *tv)
185 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
188 static inline unsigned get_msg_latency_us(struct msg_info *mi)
190 struct timespec diff;
191 if (num_interfaces == 3)
192 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
194 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
195 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
198 void set_sched_policy_and_prio(int policy, int rtprio)
200 struct sched_param scheduling_parameters;
201 int maxprio=sched_get_priority_max(policy);
202 int minprio=sched_get_priority_min(policy);
204 if((rtprio < minprio) || (rtprio > maxprio))
205 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
208 scheduling_parameters.sched_priority = rtprio;
210 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
211 error(1, errno, "pthread_setschedparam error");
214 void term_handler(int signum)
219 static inline int sock_get_if_index(int s, const char *if_name)
224 strcpy(ifr.ifr_name, if_name);
225 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
226 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
227 return ifr.ifr_ifindex;
230 static inline get_tstamp(struct timespec *ts)
232 clock_gettime(CLOCK_REALTIME, ts);
235 int send_frame(int socket)
237 struct can_frame frame;
240 static int curr_msg = -1;
245 while (msg_infos[i].id != 0 && i != curr_msg) {
251 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
255 frame.can_id = opt.id;
258 memcpy(frame.data, &idx, sizeof(idx));
259 mi = frame2info(&frame);
261 mi->id = frame.can_id;
262 mi->length = frame.can_dlc;
263 get_tstamp(&mi->ts_sent);
264 ret = write(socket, &frame, sizeof(frame));
268 void msg_info_free(struct msg_info *mi)
273 static inline void get_next_timeout(struct timespec *timeout)
276 static struct timespec last = {-1, 0 };
278 clock_gettime(CLOCK_MONOTONIC, &now);
280 if (last.tv_sec == -1)
282 if (opt.period_us != 0) {
283 last.tv_sec += opt.period_us/1000000;
284 last.tv_nsec += (opt.period_us%1000000)*1000;
285 while (last.tv_nsec >= 1000000000) {
286 last.tv_nsec -= 1000000000;
289 timespec_subtract(timeout, &last, &now);
290 } else if (opt.timeout_ms != 0) {
291 timeout->tv_sec = opt.timeout_ms/1000;
292 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
294 error(1, 0, "Timeout and period cannot be both zero");
297 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
299 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
302 struct cmsghdr *cmsg;
303 struct sockaddr_can addr;
305 static uint64_t dropcnt = 0;
307 iov.iov_base = frame;
308 msg.msg_name = &addr;
311 msg.msg_control = &ctrlmsg;
313 /* these settings may be modified by recvmsg() */
314 iov.iov_len = sizeof(*frame);
315 msg.msg_namelen = sizeof(addr);
316 msg.msg_controllen = sizeof(ctrlmsg);
319 nbytes = recvmsg(s, &msg, 0);
321 error(1, errno, "recvmsg");
323 if (nbytes < sizeof(struct can_frame))
324 error(1, 0, "recvmsg: incomplete CAN frame\n");
327 MEMSET_ZERO(*ts_kern);
328 for (cmsg = CMSG_FIRSTHDR(&msg);
329 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
330 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
331 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
332 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
333 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
334 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
339 void process_tx(int s)
341 error(1, 0, "%s: not implemented", __FUNCTION__);
344 void process_on_wire_rx(int s)
346 struct timespec ts_kern, ts_user, ts_diff;
347 struct can_frame frame;
349 receive(s, &frame, &ts_kern, &ts_user);
350 mi = frame2info(&frame);
351 mi->ts_rx_onwire_kern = ts_kern;
352 mi->ts_rx_onwire = ts_user;
356 void process_final_rx(int s)
358 struct timespec ts_kern, ts_user, ts_diff;
359 struct can_frame frame;
363 receive(s, &frame, &ts_kern, &ts_user);
364 mi = frame2info(&frame);
365 mi->ts_rx_final_kern = ts_kern;
366 mi->ts_rx_final = ts_user;
369 histogram_add(&histogram, get_msg_latency_us(mi));
371 ret = write(completion_pipe[1], &mi, sizeof(mi));
373 error(1, errno, "completion_pipe write");
376 void *measure_thread(void *arg)
379 struct pollfd pfd[3];
380 struct timespec timeout;
381 struct sockaddr_can addr;
383 unsigned msg_in_progress = 0;
387 for (i=0; i<num_interfaces; i++) {
388 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
389 error(1, errno, "socket");
391 addr.can_family = AF_CAN;
392 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
394 if (i == 0) { /* TX socket */
395 /* disable default receive filter on this RAW socket */
396 /* This is obsolete as we do not read from the socket at all, but for */
397 /* this reason we can remove the receive list in the Kernel to save a */
398 /* little (really a very little!) CPU usage. */
399 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
400 error(1, errno, "SOL_CAN_RAW");
403 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
404 error(1, errno, "bind");
406 const int timestamp_on = 1;
407 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
408 ×tamp_on, sizeof(timestamp_on)) < 0)
409 error(1, errno, "setsockopt SO_TIMESTAMP");
411 const int dropmonitor_on = 1;
412 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
413 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
414 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
418 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
420 pfd[i].events = POLLIN;
423 set_sched_policy_and_prio(SCHED_FIFO, 99);
427 ret = send_frame(pfd[0].fd); \
428 if (ret != sizeof(struct can_frame)) \
429 error(1, errno, "send_frame (line %d)", __LINE__); \
439 while (!finish_flag &&
440 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
442 get_next_timeout(&timeout);
443 //printf("ppoll"); fflush(stdout);
444 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
445 //printf("=%d\n", ret);
448 if (!INTERRUPTED_SYSCALL(errno))
449 error(1, errno, "ppoll");
453 if (opt.count == 0 || count < opt.count) {
457 error(1, 0, "poll timeout");
461 if (pfd[0].revents & (POLLIN|POLLERR)) {
462 process_tx(pfd[0].fd);
464 if (pfd[0].revents & POLLOUT) {
465 if (opt.count == 0 || count < opt.count)
470 if (num_interfaces == 3 && pfd[1].revents != 0) {
471 process_on_wire_rx(pfd[1].fd);
475 i = (num_interfaces == 2) ? 1 : 2;
476 if (pfd[i].revents != 0) {
477 process_final_rx(pfd[i].fd);
480 if ((opt.count == 0 || count < opt.count) &&
488 for (i=0; i<num_interfaces; i++)
494 struct poptOption optionsTable[] = {
495 { "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" },
496 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
497 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
498 { "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"},
499 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
500 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
501 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
502 { "file", 'f', POPT_ARG_STRING, NULL, 'f', "File where to store results", "filename"},
503 { "histogram", 'h', POPT_ARG_STRING, NULL, 'h', "Store histogram in file", "filename"},
505 { NULL, 0, 0, NULL, 0 }
508 int parse_options(int argc, const char *argv[])
511 poptContext optCon; /* context for parsing command-line options */
513 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
514 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
516 /* Now do options processing */
517 while ((c = poptGetNextOpt(optCon)) >= 0) {
523 opt.file = fopen(poptGetOptArg(optCon), "w");
525 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
528 opt.histogram = fopen(poptGetOptArg(optCon), "w");
530 error(1, errno, "fopen: %s", poptGetOptArg(optCon));
535 error(1, 0, "%s: %s\n",
536 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
539 if (num_interfaces < 2 || num_interfaces > 3)
540 error(1, 0, "-d option must be given exactly 2 or 3 times");
542 if (opt.oneattime && opt.period_us)
543 error(1, 0, "oneattime and period cannot be specified at the same time");
545 poptFreeContext(optCon);
551 int main(int argc, const char *argv[])
557 parse_options(argc, argv);
559 mlockall(MCL_CURRENT | MCL_FUTURE);
561 signal(SIGINT, term_handler);
562 signal(SIGTERM, term_handler);
565 histogram_init(&histogram, 1000000, 1);
568 ret = pipe(completion_pipe);
570 error(1, errno, "pipe");
571 ret = fcntl(completion_pipe[1], F_SETFL, O_NONBLOCK);
573 error(1, errno, "pipe fcntl");
575 pthread_create(&thread, 0, measure_thread, NULL);
577 struct timespec next, now, diff;
578 clock_gettime(CLOCK_MONOTONIC, &next);
579 while (!finish_flag && (opt.count == 0 || count < opt.count)) {
580 struct pollfd pfd[1];
581 pfd[0].fd = completion_pipe[0];
582 pfd[0].events = POLLIN;
583 ret = poll(pfd, 1, 100);
584 if (ret == -1 && !INTERRUPTED_SYSCALL(errno))
585 error(1, errno, "poll main");
586 if (ret > 0 && (pfd[0].revents & POLLIN)) {
588 read(completion_pipe[0], &mi, sizeof(mi));
590 msg_info_store(opt.file, mi);
594 clock_gettime(CLOCK_MONOTONIC, &now);
595 if (timespec_subtract(&diff, &next, &now)) {
596 printf("\rMessage %d", count);
598 next.tv_nsec += 100000000;
599 while (next.tv_nsec >= 1000000000) {
600 next.tv_nsec -= 1000000000;
605 printf("\rMessage %d\n", count);
607 pthread_join(thread, NULL);
609 close(completion_pipe[0]);
610 close(completion_pipe[1]);
613 histogram_fprint(&histogram, opt.histogram);
614 fclose(opt.histogram);