timesyncd.c revision 687ed1237b20a6db174fd0b372df20fa9a3a23c2
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2014 Kay Sievers
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include "missing.h"
#include "util.h"
#include "sparse-endian.h"
#include "log.h"
#include "sd-event.h"
#include "sd-daemon.h"
#ifndef ADJ_SETOFFSET
#endif
/* expected accuracy of time synchronization; used to adjust the poll interval */
#define NTP_ACCURACY_SEC 0.2
/*
* "A client MUST NOT under any conditions use a poll interval less
* than 15 seconds."
*/
#define NTP_POLL_INTERVAL_MIN_SEC 32
#define NTP_POLL_INTERVAL_MAX_SEC 2048
/*
* Maximum delta in seconds which the system clock is gradually adjusted
* (slew) to approach the network time. Deltas larger that this are set by
* letting the system time jump. The kernel's limit for adjtime is 0.5s.
*/
#define NTP_MAX_ADJUST 0.4
/* NTP protocol, packet header */
#define NTP_LEAP_PLUSSEC 1
#define NTP_LEAP_MINUSSEC 2
#define NTP_LEAP_NOTINSYNC 3
#define NTP_MODE_CLIENT 3
#define NTP_MODE_SERVER 4
#define NTP_FIELD_MODE(f) ((f) & 7)
/*
* "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
* in seconds relative to 0h on 1 January 1900."
*/
#define OFFSET_1900_1970 2208988800UL
struct ntp_ts {
} _packed_;
struct ntp_ts_short {
} _packed_;
struct ntp_msg {
struct ntp_ts_short root_delay;
struct ntp_ts_short root_dispersion;
char refid[4];
struct ntp_ts reference_time;
struct ntp_ts origin_time;
struct ntp_ts trans_time;
} _packed_;
struct Manager {
/* peer */
char *server;
struct sockaddr_in server_addr;
int server_socket;
/* last sent packet */
struct timespec trans_time_mon;
struct timespec trans_time;
bool pending;
/* poll timer */
bool poll_resync;
/* history data */
struct {
double offset;
double delay;
} samples[8];
unsigned int samples_idx;
double samples_jitter;
/* last change */
bool jumped;
/* watch for time changes */
int clock_watch_fd;
};
static void manager_free(Manager *m);
static int sntp_clock_watch_setup(Manager *m);
static void sntp_server_disconnect(Manager *m);
}
}
}
/* the kernel expects -0.3s as {-1, 7000.000} */
}
}
static double square(double d) {
return d * d;
}
static int sntp_send_request(Manager *m) {
struct sockaddr_in addr = {};
int r;
/*
* "The client initializes the NTP message header, sends the request
* to the server, and strips the time of day from the Transmit
* Timestamp field of the reply. For this purpose, all the NTP
* header fields are set to 0, except the Mode, VN, and optional
* Transmit Timestamp fields."
*/
/*
* Set transmit timestamp, remember it; the server will send that back
* as the origin timestamp and we have an indication that this is the
* matching answer to our request.
*
* The actual value does not matter, We do not care about the correct
* NTP UINT_MAX fraction; we just pass the plain nanosecond value.
*/
m->pending = true;
} else
/* re-arm timer with incresing timeout, in case the packets never arrive back */
if (m->retry_interval > 0) {
m->retry_interval *= 2;
} else
r = sntp_arm_timer(m, m->retry_interval);
if (r < 0)
return r;
return 0;
}
assert(m);
return 0;
}
int r;
assert(m);
assert(m->event_receive);
if (next == 0) {
return 0;
}
if (m->event_timer) {
if (r < 0)
return r;
}
r = sd_event_add_time(
m->event,
&m->event_timer,
sntp_timer, m);
if (r < 0)
return r;
return 0;
}
assert(m);
assert(m->event_receive);
/* rearm timer */
/* skip our own jumps */
if (m->jumped) {
m->jumped = false;
return 0;
}
/* resync */
log_info("System time changed. Resyncing.");
m->poll_resync = true;
return 0;
}
/* wake up when the system time changes underneath us */
static int sntp_clock_watch_setup(Manager *m) {
sd_event *e;
int r;
assert(m);
assert(m->event_receive);
if (fd < 0) {
log_error("Failed to create timerfd: %m");
return -errno;
}
log_error("Failed to set up timerfd: %m");
return -errno;
}
e = sd_event_source_get_event(m->event_receive);
if (r < 0) {
return r;
}
m->event_clock_watch = source;
if (m->clock_watch_fd >= 0)
close(m->clock_watch_fd);
m->clock_watch_fd = fd;
fd = -1;
return 0;
}
int r;
/*
* For small deltas, tell the kernel to gradually adjust the system
* clock to the NTP time, larger deltas are just directly set.
*
* Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
* syncs the system time periodically to the hardware clock.
*/
} else {
m->jumped = true;
}
switch (leap_sec) {
case 1:
break;
case -1:
break;
}
//r = clock_adjtime(CLOCK_REALTIME, &tmx);
if (r < 0)
return r;
log_debug(" status : %04i %s\n"
" time now : %li.%06li\n"
" constant : %li\n"
" offset : %+f sec\n"
" freq offset : %+li (%+.3f ppm)\n",
return 0;
}
double jitter;
double j;
m->packet_count++;
/* ignore initial sample */
if (m->packet_count == 1)
return false;
/* store the current data in our samples array */
idx_cur = m->samples_idx;
m->samples_idx = idx_new;
/* calculate new jitter value from the RMS differences relative to the lowest delay sample */
jitter = m->samples_jitter;
idx_min = i;
j = 0;
for (i = 0; i < ELEMENTSOF(m->samples); i++)
/* ignore samples when resyncing */
if (m->poll_resync)
return false;
/* always accept offset if we are farther off than the round-trip delay */
return false;
/* we need a few samples before looking at them */
if (m->packet_count < 4)
return false;
/* do not accept anything worse than the maximum possible error of the best sample */
return true;
/* compare the difference between the current offset to the previous offset and jitter */
}
if (m->poll_resync) {
m->poll_resync = false;
return;
}
/* set to minimal poll interval */
return;
}
/* increase polling interval */
m->poll_interval_usec *= 2;
return;
}
/* decrease polling interval */
m->poll_interval_usec /= 2;
return;
}
}
static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
};
union {
} control;
struct sockaddr_in server_addr;
.msg_iovlen = 1,
.msg_control = &control,
.msg_controllen = sizeof(control),
.msg_name = &server_addr,
.msg_namelen = sizeof(server_addr),
};
bool spike;
int leap_sec;
int r;
log_debug("Server connection returned error. Closing.");
return -ENOTCONN;
}
if (len < 0) {
log_debug("Error receiving message. Disconnecting.");
return -EINVAL;
}
log_debug("Invalid response from server. Disconnecting.");
return -EINVAL;
}
log_debug("Response from unknown server. Disconnecting.");
return -EINVAL;
}
continue;
case SCM_TIMESTAMP:
break;
}
}
if (!recv_time) {
log_debug("Invalid packet timestamp. Disconnecting.");
return -EINVAL;
}
if (!m->pending) {
log_debug("Unexpected reply. Ignoring.");
return 0;
}
/* check our "time cookie" (we just stored nanoseconds in the fraction field) */
log_debug("Invalid reply; not our transmit time. Ignoring.");
return 0;
}
log_debug("Server is not synchronized. Disconnecting.");
return -EINVAL;
}
return -EINVAL;
}
return -EINVAL;
}
/* valid packet */
m->pending = false;
m->retry_interval = 0;
/* announce leap seconds */
leap_sec = 1;
leap_sec = -1;
else
leap_sec = 0;
/*
* "Timestamp Name ID When Generated
* ------------------------------------------------------------
* Originate Timestamp T1 time request sent by client
* Receive Timestamp T2 time request received by server
* Transmit Timestamp T3 time reply sent by server
* Destination Timestamp T4 time reply received by client
*
* The round-trip delay, d, and system clock offset, t, are defined as:
* d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
*/
log_debug("NTP response:\n"
" leap : %u\n"
" version : %u\n"
" mode : %u\n"
" stratum : %u\n"
" precision : %f sec (%d)\n"
" reference : %.4s\n"
" origin : %f\n"
" receive : %f\n"
" transmit : %f\n"
" dest : %f\n"
" offset : %+f sec\n"
" delay : %+f sec\n"
" jitter : %f%s\n"
" poll interval: %llu\n",
m->packet_count,
m->poll_interval_usec / USEC_PER_SEC);
log_info("%4llu %+10f %10f %10f%s",
if (!spike) {
if (r < 0)
log_error("Failed to call clock_adjtime(): %m");
}
r = sntp_arm_timer(m, m->poll_interval_usec);
if (r < 0)
return r;
return 0;
}
_cleanup_free_ char *s = NULL;
assert(m);
assert(m->server_socket >= 0);
if (!s)
return -ENOMEM;
m->server = s;
s = NULL;
zero(m->server_addr);
return sntp_send_request(m);
}
static void sntp_server_disconnect(Manager *m) {
if (!m->server)
return;
if (m->clock_watch_fd > 0)
close(m->clock_watch_fd);
m->clock_watch_fd = -1;
if (m->server_socket > 0)
close(m->server_socket);
m->server_socket = -1;
zero(m->server_addr);
}
static int sntp_listen_setup(Manager *m) {
struct sockaddr_in addr;
const int on = 1;
const int tos = IPTOS_LOWDELAY;
int r;
if (fd < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return -errno;
if (r < 0)
return r;
m->server_socket = fd;
fd = -1;
return 0;
}
int r;
if (!m)
return -ENOMEM;
r = sd_event_default(&m->event);
if (r < 0)
return r;
r = sntp_listen_setup(m);
if (r < 0)
return r;
r = sntp_clock_watch_setup(m);
if (r < 0)
return r;
*ret = m;
m = NULL;
return 0;
}
static void manager_free(Manager *m) {
if (!m)
return;
sd_event_unref(m->event);
free(m);
}
const char *server;
int r;
log_open();
r = manager_new(&m);
if (r < 0)
goto out;
//server = "216.239.32.15"; /* time1.google.com */
//server = "192.53.103.108"; /* ntp1.ptb.de */
sd_notifyf(false,
"READY=1\n"
"STATUS=Connecting to %s", server);
r = sntp_server_connect(m, server);
if (r < 0)
goto out;
r = sd_event_loop(m->event);
if (r < 0)
goto out;
out:
return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}