diff --git a/port.c b/port.c index bd10d0a..dcd3f00 100644 --- a/port.c +++ b/port.c @@ -231,6 +231,29 @@ int set_tmo_lin(int fd, int seconds) return timerfd_settime(fd, 0, &tmo, NULL); } +int set_tmo_random(int fd, int min, int span, int log_seconds) +{ + uint64_t value_ns, min_ns, span_ns; + struct itimerspec tmo = { + {0, 0}, {0, 0} + }; + + if (log_seconds >= 0) { + min_ns = min * NS_PER_SEC << log_seconds; + span_ns = span * NS_PER_SEC << log_seconds; + } else { + min_ns = min * NS_PER_SEC >> -log_seconds; + span_ns = span * NS_PER_SEC >> -log_seconds; + } + + value_ns = min_ns + (span_ns * (random() % (1 << 15) + 1) >> 15); + + tmo.it_value.tv_sec = value_ns / NS_PER_SEC; + tmo.it_value.tv_nsec = value_ns % NS_PER_SEC; + + return timerfd_settime(fd, 0, &tmo, NULL); +} + static void fc_clear(struct foreign_clock *fc) { struct ptp_message *m; @@ -786,8 +809,8 @@ static void port_nrate_initialize(struct port *p) static int port_set_announce_tmo(struct port *p) { - return set_tmo_log(p->fda.fd[FD_ANNOUNCE_TIMER], - p->announceReceiptTimeout, p->logAnnounceInterval); + return set_tmo_random(p->fda.fd[FD_ANNOUNCE_TIMER], + p->announceReceiptTimeout, 1, p->logAnnounceInterval); } static int port_set_delay_tmo(struct port *p) diff --git a/port.h b/port.h index 5fef028..e781f24 100644 --- a/port.h +++ b/port.h @@ -173,6 +173,21 @@ enum port_state port_state(struct port *port); */ int set_tmo_log(int fd, unsigned int scale, int log_seconds); +/** + * Utility function for setting a file descriptor timer. + * + * This function sets the timer 'fd' to a random value between M * 2^N and + * (M + S) * 2^N, where M is the value of the 'min' parameter, S is the value + * of the 'span' parameter, and N in the value of the 'log_seconds' parameter. + * + * @param fd A file descriptor previously opened with timerfd_create(2). + * @param min The minimum value for the timer. + * @param span The span value for the timer. Must be a positive value. + * @param log_seconds The exponential factor for the timer. + * @return Zero on success, non-zero otherwise. + */ +int set_tmo_random(int fd, int min, int span, int log_seconds); + /** * Utility function for setting or resetting a file descriptor timer. *