1 /**************************************************************************/
2 /* CAN latency tester */
3 /* Copyright (C) 2010 Michal Sojka, DCE FEE CTU Prague */
5 /**************************************************************************/
14 #include <semaphore.h>
21 #include <sys/ioctl.h>
23 #include <sys/types.h>
24 //#include <ul_list.h>
28 #include <sys/socket.h>
29 #include <linux/can.h>
30 #include <linux/can/raw.h>
35 #include "histogram.h"
38 #define dbg(level, fmt, arg...) do {} while (0)
40 #define dbg(level, fmt, arg...) do { if (level <= DEBUG) { printf("candping: " fmt, ## arg); } } while (0)
43 #define INTERRUPTED_SYSCALL(errno) (errno == EINTR || errno == ERESTART)
45 #define MEMSET_ZERO(obj) memset(&(obj), 0, sizeof(obj))
47 /* Global variables */
48 volatile sig_atomic_t finish_flag = 0; /* Threads should terminate. */
49 sem_t finish_sem; /* Thread signals a termination */
51 /* Command line options */
63 struct options opt = {
70 int num_interfaces = 0;
71 int count = 0; /* Number of sent messages */
76 struct timespec ts_sent, ts_sent_kern;
77 struct timespec ts_rx_onwire, ts_rx_onwire_kern;
78 struct timespec ts_rx_final, ts_rx_final_kern;
81 #define MAX_INFOS 10000
82 struct msg_info msg_infos[MAX_INFOS];
84 struct histogram histogram;
86 static inline struct msg_info *frame2info(struct can_frame *frame)
89 if (frame->can_dlc == 2) {
90 memcpy(&idx, frame->data, sizeof(idx));
92 error(1, 0, "%s idx too high", __FUNCTION__);
94 error(1, 0, "%s error", __FUNCTION__);
95 return &msg_infos[idx];
98 static inline char *tstamp_str(const void *ctx, struct timespec *tstamp)
100 return talloc_asprintf(ctx, "%ld.%06ld",
101 tstamp->tv_sec, tstamp->tv_nsec/1000);
104 void print_msg_info(struct msg_info *mi)
106 struct timespec diff;
107 void *local = talloc_new (NULL);
109 #define S(ts) tstamp_str(local, &ts)
110 #define DIFF(a, b) (timespec_subtract(&diff, &b, &a), S(diff))
112 if (num_interfaces == 2)
113 printf("%s -> %s (%s) = %s (%s)\n",
114 S(mi->ts_sent), S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
115 DIFF(mi->ts_sent, mi->ts_rx_final_kern),
116 DIFF(mi->ts_sent, mi->ts_rx_final));
118 printf("%s -> %s (%s) -> %s (%s) = %s (%s), %s (%s)\n",
120 S(mi->ts_rx_onwire_kern), S(mi->ts_rx_onwire),
121 S(mi->ts_rx_final_kern), S(mi->ts_rx_final),
122 DIFF(mi->ts_sent, mi->ts_rx_onwire_kern),
123 DIFF(mi->ts_sent, mi->ts_rx_onwire),
124 DIFF(mi->ts_rx_onwire_kern, mi->ts_rx_final_kern),
125 DIFF(mi->ts_rx_onwire, mi->ts_rx_final));
132 /* Subtract the `struct timespec' values X and Y, storing the result in
133 RESULT. Return 1 if the difference is negative, otherwise 0. */
135 int timespec_subtract (struct timespec *result, struct timespec *x, struct timespec *yy)
137 struct timespec ylocal = *yy, *y = &ylocal;
138 /* Perform the carry for the later subtraction by updating Y. */
139 if (x->tv_nsec < y->tv_nsec) {
140 int nsec = (y->tv_nsec - x->tv_nsec) / 1000000000 + 1;
141 y->tv_nsec -= 1000000000 * nsec;
144 if (x->tv_nsec - y->tv_nsec > 1000000000) {
145 int nsec = (x->tv_nsec - y->tv_nsec) / 1000000000;
146 y->tv_nsec += 1000000000 * nsec;
150 /* Compute the time remaining to wait.
151 `tv_nsec' is certainly positive. */
152 result->tv_sec = x->tv_sec - y->tv_sec;
153 result->tv_nsec = x->tv_nsec - y->tv_nsec;
155 /* Return 1 if result is negative. */
156 return x->tv_sec < y->tv_sec;
159 void dbg_print_timespec(char *msg, struct timespec *tv)
162 printf("%s sec=%ld nsec=%ld\n", msg, tv->tv_sec, tv->tv_nsec);
165 static inline unsigned get_msg_latency_us(struct msg_info *mi)
167 struct timespec diff;
168 if (num_interfaces == 3)
169 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_rx_onwire_kern);
171 timespec_subtract(&diff, &mi->ts_rx_final_kern, &mi->ts_sent);
172 return diff.tv_sec * 1000000 + diff.tv_nsec/1000;
175 void set_sched_policy_and_prio(int policy, int rtprio)
177 struct sched_param scheduling_parameters;
178 int maxprio=sched_get_priority_max(policy);
179 int minprio=sched_get_priority_min(policy);
181 if((rtprio < minprio) || (rtprio > maxprio))
182 error(1, 0, "The priority for requested policy is out of <%d, %d> range\n",
185 scheduling_parameters.sched_priority = rtprio;
187 if (0 != pthread_setschedparam(pthread_self(), policy, &scheduling_parameters))
188 error(1, errno, "pthread_setschedparam error");
191 void term_handler(int signum)
196 static inline int sock_get_if_index(int s, const char *if_name)
201 strcpy(ifr.ifr_name, if_name);
202 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
203 error(1, errno, "SIOCGIFINDEX '%s'", if_name);
204 return ifr.ifr_ifindex;
207 static inline get_tstamp(struct timespec *ts)
209 clock_gettime(CLOCK_REALTIME, ts);
212 int send_frame(int socket)
214 struct can_frame frame;
217 static int curr_msg = -1;
222 while (msg_infos[i].id != 0 && i != curr_msg) {
228 error(1, 0, "Msg info table is full! Probably, many packets were lost.");
232 frame.can_id = opt.id;
235 memcpy(frame.data, &idx, sizeof(idx));
236 mi = frame2info(&frame);
238 mi->id = frame.can_id;
239 mi->length = frame.can_dlc;
240 get_tstamp(&mi->ts_sent);
241 ret = write(socket, &frame, sizeof(frame));
245 void msg_info_free(struct msg_info *mi)
250 static inline void get_next_timeout(struct timespec *timeout)
253 static struct timespec last = {-1, 0 };
255 clock_gettime(CLOCK_MONOTONIC, &now);
257 if (last.tv_sec == -1)
259 if (opt.period_us != 0) {
260 last.tv_sec += opt.period_us/1000000;
261 last.tv_nsec += (opt.period_us%1000000)*1000;
262 while (last.tv_nsec >= 1000000000) {
263 last.tv_nsec -= 1000000000;
266 timespec_subtract(timeout, &last, &now);
267 } else if (opt.timeout_ms != 0) {
268 timeout->tv_sec = opt.timeout_ms/1000;
269 timeout->tv_nsec = (opt.timeout_ms%1000)*1000000;
271 error(1, 0, "Timeout and period cannot be both zero");
274 void receive(int s, struct can_frame *frame, struct timespec *ts_kern, struct timespec *ts_user)
276 char ctrlmsg[CMSG_SPACE(sizeof(struct timeval)) + CMSG_SPACE(sizeof(__u32))];
279 struct cmsghdr *cmsg;
280 struct sockaddr_can addr;
282 static uint64_t dropcnt = 0;
284 iov.iov_base = frame;
285 msg.msg_name = &addr;
288 msg.msg_control = &ctrlmsg;
290 /* these settings may be modified by recvmsg() */
291 iov.iov_len = sizeof(*frame);
292 msg.msg_namelen = sizeof(addr);
293 msg.msg_controllen = sizeof(ctrlmsg);
296 nbytes = recvmsg(s, &msg, 0);
298 error(1, errno, "recvmsg");
300 if (nbytes < sizeof(struct can_frame))
301 error(1, 0, "recvmsg: incomplete CAN frame\n");
304 MEMSET_ZERO(*ts_kern);
305 for (cmsg = CMSG_FIRSTHDR(&msg);
306 cmsg && (cmsg->cmsg_level == SOL_SOCKET);
307 cmsg = CMSG_NXTHDR(&msg,cmsg)) {
308 if (cmsg->cmsg_type == SO_TIMESTAMPNS)
309 *ts_kern = *(struct timespec *)CMSG_DATA(cmsg);
310 else if (cmsg->cmsg_type == SO_RXQ_OVFL)
311 dropcnt += *(__u32 *)CMSG_DATA(cmsg);
316 void process_tx(int s)
318 error(1, 0, "%s: not implemented", __FUNCTION__);
321 void process_on_wire_rx(int s)
323 struct timespec ts_kern, ts_user, ts_diff;
324 struct can_frame frame;
326 receive(s, &frame, &ts_kern, &ts_user);
327 mi = frame2info(&frame);
328 mi->ts_rx_onwire_kern = ts_kern;
329 mi->ts_rx_onwire = ts_user;
333 void process_final_rx(int s)
335 struct timespec ts_kern, ts_user, ts_diff;
336 struct can_frame frame;
338 receive(s, &frame, &ts_kern, &ts_user);
339 mi = frame2info(&frame);
340 mi->ts_rx_final_kern = ts_kern;
341 mi->ts_rx_final = ts_user;
343 if (opt.histogram_fn)
344 histogram_add(&histogram, get_msg_latency_us(mi));
351 void *measure_thread(void *arg)
354 struct pollfd pfd[3];
355 struct timespec timeout;
356 struct sockaddr_can addr;
358 unsigned msg_in_progress = 0;
362 for (i=0; i<num_interfaces; i++) {
363 if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0)
364 error(1, errno, "socket");
366 addr.can_family = AF_CAN;
367 addr.can_ifindex = sock_get_if_index(s, opt.interface[i]);
369 if (i == 0) { /* TX socket */
370 /* disable default receive filter on this RAW socket */
371 /* This is obsolete as we do not read from the socket at all, but for */
372 /* this reason we can remove the receive list in the Kernel to save a */
373 /* little (really a very little!) CPU usage. */
374 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0) == -1)
375 error(1, errno, "SOL_CAN_RAW");
378 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
379 error(1, errno, "bind");
381 const int timestamp_on = 1;
382 if (setsockopt(s, SOL_SOCKET, SO_TIMESTAMPNS,
383 ×tamp_on, sizeof(timestamp_on)) < 0)
384 error(1, errno, "setsockopt SO_TIMESTAMP");
386 const int dropmonitor_on = 1;
387 if (setsockopt(s, SOL_SOCKET, SO_RXQ_OVFL,
388 &dropmonitor_on, sizeof(dropmonitor_on)) < 0)
389 error(1, errno, "setsockopt SO_RXQ_OVFL not supported by your Linux Kernel");
393 pfd[i].events = POLLIN | POLLERR | ((opt.period_us == 0 && !opt.oneattime) ? POLLOUT : 0);
395 pfd[i].events = POLLIN;
398 set_sched_policy_and_prio(SCHED_FIFO, 99);
402 ret = send_frame(pfd[0].fd); \
403 if (ret != sizeof(struct can_frame)) \
404 error(1, errno, "send_frame (line %d)", __LINE__); \
414 while (!finish_flag &&
415 (opt.count == 0 || count < opt.count || msg_in_progress != 0)) {
417 get_next_timeout(&timeout);
418 //printf("ppoll"); fflush(stdout);
419 ret = ppoll(pfd, num_interfaces, &timeout, NULL);
420 //printf("=%d\n", ret);
423 if (!INTERRUPTED_SYSCALL(errno))
424 error(1, errno, "ppoll");
428 if (opt.count == 0 || count < opt.count) {
432 error(1, 0, "poll timeout");
436 if (pfd[0].revents & (POLLIN|POLLERR)) {
437 process_tx(pfd[0].fd);
439 if (pfd[0].revents & POLLOUT) {
440 if (opt.count == 0 || count < opt.count)
445 if (num_interfaces == 3 && pfd[1].revents != 0) {
446 process_on_wire_rx(pfd[1].fd);
450 i = (num_interfaces == 2) ? 1 : 2;
451 if (pfd[i].revents != 0) {
452 process_final_rx(pfd[i].fd);
455 if ((opt.count == 0 || count < opt.count) &&
463 for (i=0; i<num_interfaces; i++)
469 struct poptOption optionsTable[] = {
470 { "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" },
471 { "count", 'c', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.count, 0, "The count of messages to send, zero corresponds to infinity", "num"},
472 { "id", 'i', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.id, 0, "CAN ID of sent messages", "id"},
473 { "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"},
474 { "timeout",'t', POPT_ARG_INT|POPT_ARGFLAG_SHOW_DEFAULT, &opt.timeout_ms,0, "Timeout when period is zero", "ms"},
475 { "oneattime",'o', POPT_ARG_NONE, &opt.oneattime,0, "Send the next message only when the previous was finally received"},
476 { "verbose",'v', POPT_ARG_NONE, NULL, 'v', "Send the next message only when the previous was finally received"},
477 // { "file", 'f', POPT_ARG_STRING, &opt.file, 0, "File where to store results", "filename"},
478 { "histogram", 'h', POPT_ARG_STRING, &opt.histogram_fn, 0, "Store histogram in file", "filename"},
480 { NULL, 0, 0, NULL, 0 }
483 int parse_options(int argc, const char *argv[])
486 poptContext optCon; /* context for parsing command-line options */
488 optCon = poptGetContext(NULL, argc, argv, optionsTable, 0);
489 //poptSetOtherOptionHelp(optCon, "[OPTIONS]* <port>");
491 /* Now do options processing */
492 while ((c = poptGetNextOpt(optCon)) >= 0) {
500 error(1, 0, "%s: %s\n",
501 poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
504 if (num_interfaces < 2 || num_interfaces > 3)
505 error(1, 0, "-d option must be given exactly 2 or 3 times");
507 if (opt.oneattime && opt.period_us)
508 error(1, 0, "oneattime and period cannot be specified at the same time");
510 poptFreeContext(optCon);
516 int main(int argc, const char *argv[])
523 parse_options(argc, argv);
525 mlockall(MCL_CURRENT | MCL_FUTURE);
527 signal(SIGINT, term_handler);
528 signal(SIGTERM, term_handler);
530 if (opt.histogram_fn) {
531 histogram_init(&histogram, 1000000, 1);
532 fhist = fopen(opt.histogram_fn, "w");
534 error(1, errno, "open %s", opt.histogram_fn);
538 pthread_create(&thread, 0, measure_thread, NULL);
540 while (!finish_flag && (opt.count == 0 || count < opt.count)) {
542 printf("\rMessage %d", count);
548 printf("\rMessage %d\n", count);
550 pthread_join(thread, NULL);
552 if (opt.histogram_fn) {
553 histogram_fprint(&histogram, fhist);