1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Kay Sievers
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 * "Simple Network Time Protocol Version 4 (SNTPv4) is a subset of the
24 * Network Time Protocol (NTP) used to synchronize computer clocks in
25 * the Internet. SNTPv4 can be used when the ultimate performance of
26 * a full NTP implementation based on RFC 1305 is neither needed nor
29 * "Unlike most NTP clients, SNTP clients normally operate with only a
30 * single server at a time."
32 * http://tools.ietf.org/html/rfc4330
42 #include <arpa/inet.h>
43 #include <netinet/in.h>
44 #include <netinet/ip.h>
45 #include <sys/timex.h>
46 #include <sys/socket.h>
49 #include "sparse-endian.h"
52 #include "timedate-sntp.h"
55 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
58 /* Maximum delta in seconds which the system clock is gradually adjusted
59 * to approach the network time. Deltas larger that this are set by letting
60 * the system time jump. The maximum for adjtime is 500ms.
62 #define NTP_MAX_ADJUST 0.2
65 * "Define the required accuracy of the system clock, then calculate the
66 * maximum timeout. Use the longest maximum timeout possible given the system
67 * constraints to minimize time server aggregate load."
69 * "A client MUST NOT under any conditions use a poll interval less
72 #define NTP_POLL_INTERVAL_MIN_SEC 16
73 #define NTP_POLL_INTERVAL_MAX_SEC 2048
74 #define NTP_POLL_ACCURACY_SEC 0.1
76 #define NTP_LEAP_PLUSSEC 1
77 #define NTP_LEAP_MINUSSEC 2
78 #define NTP_LEAP_NOTINSYNC 3
79 #define NTP_MODE_CLIENT 3
80 #define NTP_MODE_SERVER 4
81 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
82 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
83 #define NTP_FIELD_MODE(f) ((f) & 7)
84 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
87 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
88 * in seconds relative to 0h on 1 January 1900."
90 #define OFFSET_1900_1970 2208988800UL
107 struct ntp_ts_short root_delay;
108 struct ntp_ts_short root_dispersion;
110 struct ntp_ts reference_time;
111 struct ntp_ts origin_time;
112 struct ntp_ts recv_time;
113 struct ntp_ts trans_time;
117 sd_event_source *event_receive;
118 sd_event_source *event_timer;
121 struct sockaddr_in server_addr;
123 uint64_t packet_count;
125 struct timespec trans_time_mon;
126 struct timespec trans_time;
129 usec_t poll_interval;
135 unsigned int samples_idx;
136 double samples_jitter;
139 static int sntp_arm_timer(SNTPContext *sntp);
141 static int log2i(int a) {
154 static double log2d(int a) {
156 return 1.0 / (1UL << - a);
160 static double ntp_ts_to_d(const struct ntp_ts *ts) {
161 return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
164 static double tv_to_d(const struct timeval *tv) {
165 return tv->tv_sec + (1.0e-6 * tv->tv_usec);
168 static double ts_to_d(const struct timespec *ts) {
169 return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
172 static void d_to_tv(double d, struct timeval *tv) {
173 tv->tv_sec = (long)d;
174 tv->tv_usec = (d - tv->tv_sec) * 1000 * 1000;
176 /* the kernel expects -0.3s as {-1, 7000.000} */
177 if (tv->tv_usec < 0) {
179 tv->tv_usec += 1000 * 1000;
183 static double square(double d) {
187 static int sntp_send_request(SNTPContext *sntp) {
188 struct ntp_msg ntpmsg = {};
189 struct sockaddr_in addr = {};
194 * "The client initializes the NTP message header, sends the request
195 * to the server, and strips the time of day from the Transmit
196 * Timestamp field of the reply. For this purpose, all the NTP
197 * header fields are set to 0, except the Mode, VN, and optional
198 * Transmit Timestamp fields."
200 ntpmsg.field = NTP_FIELD(0, 4, NTP_MODE_CLIENT);
203 * Set transmit timestamp, remember it; the server will send that back
204 * as the origin timestamp and we have an indication that this is the
205 * matching answer to our request.
207 * The actual value does not matter, We do not care about the correct
208 * NTP UINT_MAX fraction, we just pass the plain nanosecond value.
210 clock_gettime(CLOCK_MONOTONIC, &sntp->trans_time_mon);
211 clock_gettime(CLOCK_REALTIME, &sntp->trans_time);
212 ntpmsg.trans_time.sec = htobe32(sntp->trans_time.tv_sec + OFFSET_1900_1970);
213 ntpmsg.trans_time.frac = htobe32(sntp->trans_time.tv_nsec);
215 addr.sin_family = AF_INET;
216 addr.sin_port = htobe16(123);
217 addr.sin_addr.s_addr = inet_addr(sntp->server);
218 len = sendto(sntp->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &addr, sizeof(addr));
220 log_debug("Sending NTP request to %s failed: %m", sntp->server);
224 sntp->pending = true;
226 /* re-arm timer for next poll interval, in case the packet never arrives back */
227 r = sntp_arm_timer(sntp);
231 log_debug("Sent NTP request to: %s", sntp->server);
235 static int sntp_timer(sd_event_source *source, usec_t usec, void *userdata) {
236 SNTPContext *sntp = userdata;
240 sntp_send_request(sntp);
244 static int sntp_arm_timer(SNTPContext *sntp) {
249 assert(sntp->event_receive);
251 if (sntp->poll_interval <= 0) {
252 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
256 if (sntp->event_timer) {
257 r = sd_event_source_set_time(sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval);
261 return sd_event_source_set_enabled(sntp->event_timer, SD_EVENT_ONESHOT);
264 e = sd_event_source_get_event(sntp->event_receive);
265 r = sd_event_add_monotonic(e, &sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval, 0, sntp_timer, sntp);
272 static int sntp_adjust_clock(SNTPContext *sntp, double offset, int leap_sec) {
273 struct timex tmx = {};
277 * For small deltas, tell the kernel to gradually adjust the system
278 * clock to the NTP time, larger deltas are just directly set.
280 * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
281 * syncs the system time periodically to the hardware clock.
283 if (offset < NTP_MAX_ADJUST && offset > -NTP_MAX_ADJUST) {
286 constant = log2i(sntp->poll_interval / USEC_PER_SEC) - 5;
288 tmx.modes |= ADJ_STATUS | ADJ_OFFSET | ADJ_TIMECONST;
289 tmx.status = STA_PLL;
290 tmx.offset = offset * 1000 * 1000;
291 tmx.constant = constant;
293 log_debug(" adjust (slew): %+f sec\n", (double)tmx.offset / USEC_PER_SEC);
295 tmx.modes = ADJ_SETOFFSET;
296 d_to_tv(offset, &tmx.time);
297 log_debug(" adjust (jump): %+f sec\n", tv_to_d(&tmx.time));
302 tmx.status |= STA_INS;
305 tmx.status |= STA_DEL;
309 r = clock_adjtime(CLOCK_REALTIME, &tmx);
313 log_debug(" status : %04i %s\n"
314 " time now : %li.%06li\n"
316 " offset : %+f sec\n"
317 " freq offset : %+li (%+.3f ppm)\n",
318 tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
319 tmx.time.tv_sec, tmx.time.tv_usec,
321 (double)tmx.offset / USEC_PER_SEC,
322 tmx.freq, (double)tmx.freq / 65536);
327 static bool sntp_sample_spike_detection(SNTPContext *sntp, double offset, double delay) {
328 unsigned int i, idx_cur, idx_new, idx_min;
332 /* store the current data in our samples array */
333 idx_cur = sntp->samples_idx;
334 idx_new = (idx_cur + 1) % ELEMENTSOF(sntp->samples);
335 sntp->samples_idx = idx_new;
336 sntp->samples[idx_new].offset = offset;
337 sntp->samples[idx_new].delay = delay;
339 sntp->packet_count++;
342 * Spike detection; compare the difference between the
343 * current offset to the previous offset and jitter.
345 spike = sntp->packet_count > 2 && fabs(offset - sntp->samples[idx_cur].offset) > sntp->samples_jitter * 3;
347 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
348 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(sntp->samples); i++)
349 if (sntp->samples[i].delay > 0 && sntp->samples[i].delay < sntp->samples[idx_min].delay)
352 for (jitter = 0, i = 0; i < ELEMENTSOF(sntp->samples); i++)
353 jitter += square(sntp->samples[i].offset - sntp->samples[idx_min].offset);
354 sntp->samples_jitter = sqrt(jitter / (ELEMENTSOF(sntp->samples) - 1));
359 static void snmp_adjust_poll(SNTPContext *sntp, double offset, bool spike) {
363 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
364 sntp->poll_interval /= 2;
368 delta = fabs(offset);
370 /* set to minimal poll interval */
371 if (delta > NTP_POLL_ACCURACY_SEC) {
372 sntp->poll_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
376 /* increase polling interval */
377 if (delta < NTP_POLL_ACCURACY_SEC * 0.25) {
378 if (sntp->poll_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
379 sntp->poll_interval *= 2;
383 /* decrease polling interval */
384 if (delta > NTP_POLL_ACCURACY_SEC * 0.75) {
385 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
386 sntp->poll_interval /= 2;
391 static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
392 SNTPContext *sntp = userdata;
393 unsigned char buf[sizeof(struct ntp_msg)];
396 .iov_len = sizeof(buf),
399 struct cmsghdr cmsghdr;
400 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
402 struct sockaddr_in server_addr;
403 struct msghdr msghdr = {
406 .msg_control = &control,
407 .msg_controllen = sizeof(control),
408 .msg_name = &server_addr,
409 .msg_namelen = sizeof(server_addr),
411 struct cmsghdr *cmsg;
413 struct timeval *recv_time;
415 struct ntp_msg *ntpmsg;
416 double origin, recv, trans, dest;
417 double delay, offset;
422 if (revents & (EPOLLHUP|EPOLLERR)) {
423 log_debug("Server connection returned error, closing.");
424 sntp_server_disconnect(sntp);
428 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
430 log_debug("Error receiving message, disconnecting");
434 if (iov.iov_len < sizeof(struct ntp_msg)) {
435 log_debug("Invalid response from server, disconnecting");
439 if (sntp->server_addr.sin_addr.s_addr != server_addr.sin_addr.s_addr) {
440 log_debug("Response from unknown server, disconnecting");
445 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
446 if (cmsg->cmsg_level != SOL_SOCKET)
449 switch (cmsg->cmsg_type) {
451 recv_time = (struct timeval *) CMSG_DATA(cmsg);
456 log_debug("Invalid packet timestamp, disconnecting");
460 ntpmsg = iov.iov_base;
461 if (!sntp->pending) {
462 log_debug("Unexpected reply, ignoring");
465 sntp->pending = false;
467 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
468 if (be32toh(ntpmsg->origin_time.sec) != sntp->trans_time.tv_sec + OFFSET_1900_1970||
469 be32toh(ntpmsg->origin_time.frac) != sntp->trans_time.tv_nsec) {
470 log_debug("Invalid reply, not our transmit time, ignoring");
474 if (NTP_FIELD_LEAP(ntpmsg->field) == NTP_LEAP_NOTINSYNC) {
475 log_debug("Server is not synchronized, disconnecting");
479 if (NTP_FIELD_VERSION(ntpmsg->field) != 4) {
480 log_debug("Response NTPv%d, disconnecting", NTP_FIELD_VERSION(ntpmsg->field));
484 if (NTP_FIELD_MODE(ntpmsg->field) != NTP_MODE_SERVER) {
485 log_debug("Unsupported mode %d, disconnecting", NTP_FIELD_MODE(ntpmsg->field));
489 /* announce leap seconds */
490 if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_PLUSSEC)
492 else if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_MINUSSEC)
498 * "Timestamp Name ID When Generated
499 * ------------------------------------------------------------
500 * Originate Timestamp T1 time request sent by client
501 * Receive Timestamp T2 time request received by server
502 * Transmit Timestamp T3 time reply sent by server
503 * Destination Timestamp T4 time reply received by client
505 * The roundtrip delay d and system clock offset t are defined as:
506 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
508 clock_gettime(CLOCK_MONOTONIC, &now);
509 origin = tv_to_d(recv_time) - (ts_to_d(&now) - ts_to_d(&sntp->trans_time_mon)) + OFFSET_1900_1970;
510 recv = ntp_ts_to_d(&ntpmsg->recv_time);
511 trans = ntp_ts_to_d(&ntpmsg->trans_time);
512 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
514 offset = ((recv - origin) + (trans - dest)) / 2;
515 delay = (dest - origin) - (trans - recv);
517 spike = sntp_sample_spike_detection(sntp, offset, delay);
519 snmp_adjust_poll(sntp, offset, spike);
521 log_debug("NTP response:\n"
526 " precision : %f sec (%d)\n"
527 " reference : %.4s\n"
532 " offset : %+f sec\n"
534 " packet count : %llu\n"
535 " jitter/spike : %f (%s)\n"
536 " poll interval: %llu\n",
537 NTP_FIELD_LEAP(ntpmsg->field),
538 NTP_FIELD_VERSION(ntpmsg->field),
539 NTP_FIELD_MODE(ntpmsg->field),
541 log2d(ntpmsg->precision), ntpmsg->precision,
542 ntpmsg->stratum == 1 ? ntpmsg->refid : "n/a",
543 origin - OFFSET_1900_1970,
544 recv - OFFSET_1900_1970,
545 trans - OFFSET_1900_1970,
546 dest - OFFSET_1900_1970,
548 (unsigned long long)sntp->packet_count,
549 sntp->samples_jitter, spike ? "yes" : "no",
550 sntp->poll_interval / USEC_PER_SEC);
552 log_info("%4llu %s %+12f", sntp->poll_interval / USEC_PER_SEC, spike ? "y" : "n", offset);
555 r = sntp_adjust_clock(sntp, offset, leap_sec);
557 log_error("Failed to call clock_adjtime(): %m");
560 r = sntp_arm_timer(sntp);
567 int sntp_server_connect(SNTPContext *sntp, const char *server) {
568 _cleanup_free_ char *s = NULL;
572 assert(sntp->server_socket >= 0);
582 zero(sntp->server_addr);
583 sntp->server_addr.sin_family = AF_INET;
584 sntp->server_addr.sin_addr.s_addr = inet_addr(server);
586 sntp->poll_interval = 2 * NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
588 return sntp_send_request(sntp);
591 void sntp_server_disconnect(SNTPContext *sntp) {
595 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
596 sntp->event_receive = sd_event_source_unref(sntp->event_receive);
597 if (sntp->server_socket > 0)
598 close(sntp->server_socket);
599 sntp->server_socket = -1;
600 zero(sntp->server_addr);
605 int sntp_new(SNTPContext **sntp, sd_event *e) {
606 _cleanup_free_ SNTPContext *c;
607 _cleanup_close_ int fd = -1;
608 struct sockaddr_in addr;
610 const int tos = IPTOS_LOWDELAY;
613 c = new0(SNTPContext, 1);
617 fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
622 addr.sin_family = AF_INET;
623 r = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
627 r = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
631 r = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
635 r = sd_event_add_io(e, &c->event_receive, fd, EPOLLIN, sntp_receive_response, c);
639 c->server_socket = fd;
648 SNTPContext *sntp_unref(SNTPContext *sntp) {
649 sntp_server_disconnect(sntp);