VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceTimeSync.cpp@ 98709

Last change on this file since 98709 was 98103, checked in by vboxsync, 23 months ago

Copyright year updates by scm.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.3 KB
Line 
1/* $Id: VBoxServiceTimeSync.cpp 98103 2023-01-17 14:15:46Z vboxsync $ */
2/** @file
3 * VBoxService - Guest Additions TimeSync Service.
4 */
5
6/*
7 * Copyright (C) 2007-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/** @page pg_vgsvc_timesync VBoxService - The Time Sync Service
30 *
31 * The time sync subservice synchronizes the guest OS walltime with the host.
32 *
33 * The time sync service plays along with the Time Manager (TM) in the VMM
34 * to keep the guest time accurate using the host machine as a reference.
35 * Communication is facilitated by VMMDev. TM will try its best to make sure
36 * all timer ticks get delivered so that there isn't normally any need to
37 * adjust the guest time.
38 *
39 * There are three normal (= acceptable) cases:
40 * -# When the service starts up. This is because ticks and such might
41 * be lost during VM and OS startup. (Need to figure out exactly why!)
42 * -# When the TM is unable to deliver all the ticks and swallows a
43 * backlog of ticks. The threshold for this is configurable with
44 * a default of 60 seconds.
45 * -# The time is adjusted on the host. This can be caused manually by
46 * the user or by some time sync daemon (NTP, LAN server, etc.).
47 *
48 * There are a number of very odd case where adjusting is needed. Here
49 * are some of them:
50 * -# Timer device emulation inaccuracies (like rounding).
51 * -# Inaccuracies in time source VirtualBox uses.
52 * -# The Guest and/or Host OS doesn't perform proper time keeping. This
53 * can come about as a result of OS and/or hardware issues.
54 *
55 * The TM is our source for the host time and will make adjustments for
56 * current timer delivery lag. The simplistic approach taken by TM is to
57 * adjust the host time by the current guest timer delivery lag, meaning that
58 * if the guest is behind 1 second with PIT/RTC/++ ticks, this should be
59 * reflected in the guest wall time as well.
60 *
61 * Now, there is any amount of trouble we can cause by changing the time.
62 * Most applications probably use the wall time when they need to measure
63 * things. A walltime that is being juggled about every so often, even if just
64 * a little bit, could occasionally upset these measurements by for instance
65 * yielding negative results.
66 *
67 * This bottom line here is that the time sync service isn't really supposed
68 * to do anything and will try avoid having to do anything when possible.
69 *
70 * The implementation uses the latency it takes to query host time as the
71 * absolute maximum precision to avoid messing up under timer tick catchup
72 * and/or heavy host/guest load. (Rationale is that a *lot* of stuff may
73 * happen on our way back from ring-3 and TM/VMMDev since we're taking the
74 * route thru the inner EM loop with its force flag processing.)
75 *
76 * But this latency has to be measured from our perspective, which means it
77 * could just as easily come out as 0. (OS/2 and Windows guests only update
78 * the current time when the timer ticks for instance.) The good thing is
79 * that this isn't really a problem since we won't ever do anything unless
80 * the drift is noticeable.
81 *
82 * It now boils down to these three (configuration) factors:
83 * -# g_cMsTimeSyncMinAdjust - The minimum drift we will ever bother with.
84 * -# g_TimeSyncLatencyFactor - The factor we multiply the latency by to
85 * calculate the dynamic minimum adjust factor.
86 * -# g_cMsTimeSyncMaxLatency - When to start discarding the data as utterly
87 * useless and take a rest (someone is too busy to give us good data).
88 * -# g_TimeSyncSetThreshold - The threshold at which we will just set the time
89 * instead of trying to adjust it (milliseconds).
90 */
91
92
93/*********************************************************************************************************************************
94* Header Files *
95*********************************************************************************************************************************/
96#ifdef RT_OS_WINDOWS
97# include <iprt/win/windows.h>
98#else
99# include <unistd.h>
100# include <errno.h>
101# include <time.h>
102# include <sys/time.h>
103#endif
104
105#include <iprt/assert.h>
106#include <iprt/string.h>
107#include <iprt/semaphore.h>
108#include <iprt/time.h>
109#include <iprt/thread.h>
110#include <VBox/err.h>
111#include <VBox/VBoxGuestLib.h>
112#include "VBoxServiceInternal.h"
113#include "VBoxServiceUtils.h"
114
115
116/*********************************************************************************************************************************
117* Global Variables *
118*********************************************************************************************************************************/
119/** The timesync interval (milliseconds). */
120static uint32_t g_TimeSyncInterval = 0;
121/**
122 * @see pg_vgsvc_timesync
123 *
124 * @remark OS/2: There is either a 1 second resolution on the DosSetDateTime
125 * API or a bug in my settimeofday implementation. Thus, don't
126 * bother unless there is at least a 1 second drift.
127 */
128#ifdef RT_OS_OS2
129static uint32_t g_cMsTimeSyncMinAdjust = 1000;
130#else
131static uint32_t g_cMsTimeSyncMinAdjust = 100;
132#endif
133/** @see pg_vgsvc_timesync */
134static uint32_t g_TimeSyncLatencyFactor = 8;
135/** @see pg_vgsvc_timesync */
136static uint32_t g_cMsTimeSyncMaxLatency = 250;
137/** @see pg_vgsvc_timesync */
138static uint32_t g_TimeSyncSetThreshold = 20*60*1000;
139/** Whether the next adjustment should just set the time instead of trying to
140 * adjust it. This is used to implement --timesync-set-start.
141 * For purposes of setting the kernel timezone, OS/2 always starts with this. */
142#ifdef RT_OS_OS2
143static bool volatile g_fTimeSyncSetOnStart = true;
144#else
145static bool volatile g_fTimeSyncSetOnStart = false;
146#endif
147/** Whether to set the time when the VM was restored. */
148static bool g_fTimeSyncSetOnRestore = true;
149/** The logging verbosity level.
150 * This uses the global verbosity level by default. */
151static uint32_t g_cTimeSyncVerbosity = 0;
152
153/** Current error count. Used to decide when to bitch and when not to. */
154static uint32_t g_cTimeSyncErrors = 0;
155
156/** The semaphore we're blocking on. */
157static RTSEMEVENTMULTI g_TimeSyncEvent = NIL_RTSEMEVENTMULTI;
158
159/** The VM session ID. Changes whenever the VM is restored or reset. */
160static uint64_t g_idTimeSyncSession;
161
162#ifdef RT_OS_WINDOWS
163/** Process token. */
164static HANDLE g_hTokenProcess = NULL;
165/** Old token privileges. */
166static TOKEN_PRIVILEGES g_TkOldPrivileges;
167/** Backup values for time adjustment. */
168static DWORD g_dwWinTimeAdjustment;
169static DWORD g_dwWinTimeIncrement;
170static BOOL g_bWinTimeAdjustmentDisabled;
171#endif
172
173
174/**
175 * @interface_method_impl{VBOXSERVICE,pfnPreInit}
176 */
177static DECLCALLBACK(int) vgsvcTimeSyncPreInit(void)
178{
179 /* Use global verbosity as default. */
180 g_cTimeSyncVerbosity = g_cVerbosity;
181
182#ifdef VBOX_WITH_GUEST_PROPS
183 /** @todo Merge this function with vgsvcTimeSyncOption() to generalize
184 * the "command line args override guest property values" behavior. */
185
186 /*
187 * Read the service options from the VM's guest properties.
188 * Note that these options can be overridden by the command line options later.
189 */
190 uint32_t uGuestPropSvcClientID;
191 int rc = VbglR3GuestPropConnect(&uGuestPropSvcClientID);
192 if (RT_FAILURE(rc))
193 {
194 if (rc == VERR_HGCM_SERVICE_NOT_FOUND) /* Host service is not available. */
195 {
196 VGSvcVerbose(0, "VMInfo: Guest property service is not available, skipping\n");
197 rc = VINF_SUCCESS;
198 }
199 else
200 VGSvcError("Failed to connect to the guest property service! Error: %Rrc\n", rc);
201 }
202 else
203 {
204 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-interval",
205 &g_TimeSyncInterval, 50, UINT32_MAX - 1);
206 if ( RT_SUCCESS(rc)
207 || rc == VERR_NOT_FOUND)
208 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-min-adjust",
209 &g_cMsTimeSyncMinAdjust, 0, 3600000);
210 if ( RT_SUCCESS(rc)
211 || rc == VERR_NOT_FOUND)
212 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-latency-factor",
213 &g_TimeSyncLatencyFactor, 1, 1024);
214 if ( RT_SUCCESS(rc)
215 || rc == VERR_NOT_FOUND)
216 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-max-latency",
217 &g_cMsTimeSyncMaxLatency, 1, 3600000);
218 if ( RT_SUCCESS(rc)
219 || rc == VERR_NOT_FOUND)
220 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-threshold",
221 &g_TimeSyncSetThreshold, 0, 7*24*60*60*1000 /* a week */);
222
223 if (VbglR3GuestPropExist(uGuestPropSvcClientID,
224 "/VirtualBox/GuestAdd/VBoxService/--timesync-set-start"))
225 g_fTimeSyncSetOnStart = true;
226
227 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-no-set-start"))
228 g_fTimeSyncSetOnStart = false;
229
230
231 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-set-on-restore"))
232 g_fTimeSyncSetOnRestore = true;
233
234 if (VbglR3GuestPropExist(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-no-set-on-restore"))
235 g_fTimeSyncSetOnRestore = false;
236
237 uint32_t uValue;
238 rc = VGSvcReadPropUInt32(uGuestPropSvcClientID, "/VirtualBox/GuestAdd/VBoxService/--timesync-verbosity",
239 &uValue, 0 /*uMin*/, 255 /*uMax*/);
240 if (RT_SUCCESS(rc))
241 g_cTimeSyncVerbosity = uValue;
242
243 VbglR3GuestPropDisconnect(uGuestPropSvcClientID);
244 }
245
246 if (rc == VERR_NOT_FOUND) /* If a value is not found, don't be sad! */
247 rc = VINF_SUCCESS;
248 return rc;
249#else
250 /* Nothing to do here yet. */
251 return VINF_SUCCESS;
252#endif
253}
254
255
256/**
257 * Displays a verbose message based on the currently
258 * set timesync verbosity level.
259 *
260 * @param iLevel Minimum log level required to display this message.
261 * @param pszFormat The message text.
262 * @param ... Format arguments.
263 */
264static void vgsvcTimeSyncLog(unsigned iLevel, const char *pszFormat, ...)
265{
266 if (iLevel <= g_cTimeSyncVerbosity)
267 {
268 va_list va;
269 va_start(va, pszFormat);
270 VGSvcLogV(pszFormat, va);
271 va_end(va);
272 }
273}
274
275
276/**
277 * @interface_method_impl{VBOXSERVICE,pfnOption}
278 */
279static DECLCALLBACK(int) vgsvcTimeSyncOption(const char **ppszShort, int argc, char **argv, int *pi)
280{
281 int rc = VINF_SUCCESS;
282 if (ppszShort)
283 rc = -1 ;/* no short options */
284 else if (!strcmp(argv[*pi], "--timesync-interval"))
285 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncInterval, 50, UINT32_MAX - 1);
286 else if (!strcmp(argv[*pi], "--timesync-min-adjust"))
287 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cMsTimeSyncMinAdjust, 0, 3600000);
288 else if (!strcmp(argv[*pi], "--timesync-latency-factor"))
289 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncLatencyFactor, 1, 1024);
290 else if (!strcmp(argv[*pi], "--timesync-max-latency"))
291 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cMsTimeSyncMaxLatency, 1, 3600000);
292 else if (!strcmp(argv[*pi], "--timesync-set-threshold"))
293 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_TimeSyncSetThreshold, 0, 7*24*60*60*1000); /* a week */
294 else if (!strcmp(argv[*pi], "--timesync-set-start"))
295 g_fTimeSyncSetOnStart = true;
296 else if (!strcmp(argv[*pi], "--timesync-no-set-start"))
297 g_fTimeSyncSetOnStart = false;
298 else if (!strcmp(argv[*pi], "--timesync-set-on-restore"))
299 g_fTimeSyncSetOnRestore = true;
300 else if (!strcmp(argv[*pi], "--timesync-no-set-on-restore"))
301 g_fTimeSyncSetOnRestore = false;
302 else if (!strcmp(argv[*pi], "--timesync-verbosity"))
303 rc = VGSvcArgUInt32(argc, argv, "", pi, &g_cTimeSyncVerbosity, 0 /*uMin*/, 255 /*uMax*/);
304 else
305 rc = -1;
306
307 return rc;
308}
309
310
311/**
312 * @interface_method_impl{VBOXSERVICE,pfnInit}
313 */
314static DECLCALLBACK(int) vgsvcTimeSyncInit(void)
315{
316 /*
317 * If not specified, find the right interval default.
318 * Then create the event sem to block on.
319 */
320 if (!g_TimeSyncInterval)
321 g_TimeSyncInterval = g_DefaultInterval * 1000;
322 if (!g_TimeSyncInterval)
323 g_TimeSyncInterval = 10 * 1000;
324
325 VbglR3GetSessionId(&g_idTimeSyncSession);
326 /* The status code is ignored as this information is not available with VBox < 3.2.10. */
327
328 int rc = RTSemEventMultiCreate(&g_TimeSyncEvent);
329 AssertRC(rc);
330#ifdef RT_OS_WINDOWS
331 if (RT_SUCCESS(rc))
332 {
333 /*
334 * Adjust privileges of this process so we can make system time adjustments.
335 */
336 if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &g_hTokenProcess))
337 {
338 TOKEN_PRIVILEGES tkPriv;
339 RT_ZERO(tkPriv);
340 tkPriv.PrivilegeCount = 1;
341 tkPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
342 if (LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkPriv.Privileges[0].Luid))
343 {
344 DWORD cbRet = sizeof(g_TkOldPrivileges);
345 if (AdjustTokenPrivileges(g_hTokenProcess, FALSE, &tkPriv, sizeof(TOKEN_PRIVILEGES), &g_TkOldPrivileges, &cbRet))
346 rc = VINF_SUCCESS;
347 else
348 {
349 DWORD dwErr = GetLastError();
350 rc = RTErrConvertFromWin32(dwErr);
351 VGSvcError("vgsvcTimeSyncInit: Adjusting token privileges (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
352 dwErr, rc);
353 }
354 }
355 else
356 {
357 DWORD dwErr = GetLastError();
358 rc = RTErrConvertFromWin32(dwErr);
359 VGSvcError("vgsvcTimeSyncInit: Looking up token privileges (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
360 dwErr, rc);
361 }
362 if (RT_FAILURE(rc))
363 {
364 CloseHandle(g_hTokenProcess);
365 g_hTokenProcess = NULL;
366 }
367 }
368 else
369 {
370 DWORD dwErr = GetLastError();
371 rc = RTErrConvertFromWin32(dwErr);
372 VGSvcError("vgsvcTimeSyncInit: Opening process token (SE_SYSTEMTIME_NAME) failed with status code %u/%Rrc!\n",
373 dwErr, rc);
374 g_hTokenProcess = NULL;
375 }
376 }
377
378 if (g_pfnGetSystemTimeAdjustment)
379 {
380 if (g_pfnGetSystemTimeAdjustment(&g_dwWinTimeAdjustment, &g_dwWinTimeIncrement, &g_bWinTimeAdjustmentDisabled))
381 vgsvcTimeSyncLog(0, "vgsvcTimeSyncInit: Initially %ld (100ns) units per %ld (100 ns) units interval, disabled=%d\n",
382 g_dwWinTimeAdjustment, g_dwWinTimeIncrement, g_bWinTimeAdjustmentDisabled ? 1 : 0);
383 else
384 {
385 DWORD dwErr = GetLastError();
386 rc = RTErrConvertFromWin32(dwErr);
387 VGSvcError("vgsvcTimeSyncInit: Could not get time adjustment values! Last error: %ld!\n", dwErr);
388 }
389 }
390#endif /* RT_OS_WINDOWS */
391
392 return rc;
393}
394
395
396/**
397 * Try adjusting the time using adjtime or similar.
398 *
399 * @returns true on success, false on failure.
400 *
401 * @param pDrift The time adjustment.
402 */
403static bool vgsvcTimeSyncAdjust(PCRTTIMESPEC pDrift)
404{
405#ifdef RT_OS_WINDOWS
406/** @todo r=bird: g_hTokenProcess cannot be NULL here.
407 * vgsvcTimeSyncInit will fail and the service will not be started with
408 * it being NULL. vgsvcTimeSyncInit OTOH will *NOT* be called until the
409 * service thread has terminated. If anything
410 * else is the case, there is buggy code somewhere.*/
411 if (g_hTokenProcess == NULL) /* Is the token already closed when shutting down? */
412 return false;
413
414 /* The API appeared in NT 3.50. */
415 if ( !g_pfnSetSystemTimeAdjustment
416 || !g_pfnGetSystemTimeAdjustment)
417 return false;
418
419 DWORD dwWinTimeAdjustment, dwWinNewTimeAdjustment, dwWinTimeIncrement;
420 BOOL fWinTimeAdjustmentDisabled;
421 if (g_pfnGetSystemTimeAdjustment(&dwWinTimeAdjustment, &dwWinTimeIncrement, &fWinTimeAdjustmentDisabled))
422 {
423 DWORD dwDiffMax = g_dwWinTimeAdjustment * 0.50;
424 DWORD dwDiffNew = dwWinTimeAdjustment * 0.10;
425
426 if (RTTimeSpecGetMilli(pDrift) > 0)
427 {
428 dwWinNewTimeAdjustment = dwWinTimeAdjustment + dwDiffNew;
429 if (dwWinNewTimeAdjustment > (g_dwWinTimeAdjustment + dwDiffMax))
430 {
431 dwWinNewTimeAdjustment = g_dwWinTimeAdjustment + dwDiffMax;
432 dwDiffNew = dwDiffMax;
433 }
434 }
435 else
436 {
437 dwWinNewTimeAdjustment = dwWinTimeAdjustment - dwDiffNew;
438 if (dwWinNewTimeAdjustment < (g_dwWinTimeAdjustment - dwDiffMax))
439 {
440 dwWinNewTimeAdjustment = g_dwWinTimeAdjustment - dwDiffMax;
441 dwDiffNew = dwDiffMax;
442 }
443 }
444
445 vgsvcTimeSyncLog(3, "vgsvcTimeSyncAdjust: Drift=%lldms\n", RTTimeSpecGetMilli(pDrift));
446 vgsvcTimeSyncLog(3, "vgsvcTimeSyncAdjust: OrgTA=%ld, CurTA=%ld, NewTA=%ld, DiffNew=%ld, DiffMax=%ld\n",
447 g_dwWinTimeAdjustment, dwWinTimeAdjustment, dwWinNewTimeAdjustment, dwDiffNew, dwDiffMax);
448 if (g_pfnSetSystemTimeAdjustment(dwWinNewTimeAdjustment, FALSE /* Periodic adjustments enabled. */))
449 {
450 g_cTimeSyncErrors = 0;
451 return true;
452 }
453
454 if (g_cTimeSyncErrors++ < 10)
455 VGSvcError("vgsvcTimeSyncAdjust: SetSystemTimeAdjustment failed, error=%u\n", GetLastError());
456 }
457 else if (g_cTimeSyncErrors++ < 10)
458 VGSvcError("vgsvcTimeSyncAdjust: GetSystemTimeAdjustment failed, error=%ld\n", GetLastError());
459
460#elif defined(RT_OS_OS2) || defined(RT_OS_HAIKU)
461 /* No API for doing gradual time adjustments. */
462
463#else /* PORTME */
464 /*
465 * Try using adjtime(), most unix-like systems have this.
466 */
467 struct timeval tv;
468 RTTimeSpecGetTimeval(pDrift, &tv);
469 if (adjtime(&tv, NULL) == 0)
470 {
471 vgsvcTimeSyncLog(1, "vgsvcTimeSyncAdjust: adjtime by %RDtimespec\n", pDrift);
472 g_cTimeSyncErrors = 0;
473 return true;
474 }
475#endif
476
477 /* failed */
478 return false;
479}
480
481
482/**
483 * Cancels any pending time adjustment.
484 *
485 * Called when we've caught up and before calls to vgsvcTimeSyncSet.
486 */
487static void vgsvcTimeSyncCancelAdjust(void)
488{
489#ifdef RT_OS_WINDOWS
490/** @todo r=bird: g_hTokenProcess cannot be NULL here. See argumentation in
491 * vgsvcTimeSyncAdjust. */
492 if (g_hTokenProcess == NULL) /* No process token (anymore)? */
493 return;
494 if (!g_pfnSetSystemTimeAdjustment)
495 return;
496 if (g_pfnSetSystemTimeAdjustment(0, TRUE /* Periodic adjustments disabled. */))
497 vgsvcTimeSyncLog(5, "vgsvcTimeSyncCancelAdjust: Windows Time Adjustment is now disabled.\n");
498 else if (g_cTimeSyncErrors++ < 10)
499 VGSvcError("vgsvcTimeSyncCancelAdjust: SetSystemTimeAdjustment(,disable) failed, error=%u\n", GetLastError());
500#endif /* !RT_OS_WINDOWS */
501}
502
503
504/**
505 * Set the wall clock to compensate for drift.
506 *
507 * @returns true on success, false on failure.
508 *
509 * @param pDrift The time adjustment.
510 */
511static void vgsvcTimeSyncSet(PCRTTIMESPEC pDrift)
512{
513 /*
514 * Query the current time, adjust it by adding the drift and set it.
515 */
516 RTTIMESPEC NewGuestTime;
517 int rc = RTTimeSet(RTTimeSpecAdd(RTTimeNow(&NewGuestTime), pDrift));
518 if (RT_SUCCESS(rc))
519 {
520 /* Succeeded - reset the error count and log the change. */
521 g_cTimeSyncErrors = 0;
522
523 if (g_cTimeSyncVerbosity >= 1)
524 {
525 char sz[64];
526 RTTIME Time;
527 vgsvcTimeSyncLog(1, "time set to %s\n", RTTimeToString(RTTimeExplode(&Time, &NewGuestTime), sz, sizeof(sz)));
528#ifdef DEBUG
529 RTTIMESPEC Tmp;
530 vgsvcTimeSyncLog(3, " now %s\n", RTTimeToString(RTTimeExplode(&Time, RTTimeNow(&Tmp)), sz, sizeof(sz)));
531#endif
532 }
533 }
534 else if (g_cTimeSyncErrors++ < 10)
535 VGSvcError("vgsvcTimeSyncSet: RTTimeSet(%RDtimespec) failed: %Rrc\n", &NewGuestTime, rc);
536}
537
538
539/**
540 * @interface_method_impl{VBOXSERVICE,pfnWorker}
541 */
542DECLCALLBACK(int) vgsvcTimeSyncWorker(bool volatile *pfShutdown)
543{
544 RTTIME Time;
545 int rc = VINF_SUCCESS;
546
547 /*
548 * Tell the control thread that it can continue spawning services.
549 */
550 RTThreadUserSignal(RTThreadSelf());
551
552 /*
553 * Initialize the last host and guest times to prevent log message.
554 * We also track whether we set the time in the previous loop.
555 */
556 RTTIMESPEC HostLast;
557 if (RT_FAILURE(VbglR3GetHostTime(&HostLast)))
558 RTTimeSpecSetNano(&HostLast, 0);
559 RTTIMESPEC GuestLast;
560 RTTimeNow(&GuestLast);
561 bool fSetTimeLastLoop = false;
562
563 /*
564 * The Work Loop.
565 */
566 for (;;)
567 {
568 /*
569 * Try to get a reliable time reading.
570 */
571 int cTries = 3;
572 do
573 {
574 /*
575 * Query the session id (first to keep lantency low) and the time.
576 */
577 uint64_t idNewSession = g_idTimeSyncSession;
578 if (g_fTimeSyncSetOnRestore)
579 VbglR3GetSessionId(&idNewSession);
580
581 RTTIMESPEC GuestNow0;
582 RTTimeNow(&GuestNow0);
583
584 RTTIMESPEC HostNow;
585 int rc2 = VbglR3GetHostTime(&HostNow);
586 if (RT_FAILURE(rc2))
587 {
588 if (g_cTimeSyncErrors++ < 10)
589 VGSvcError("vgsvcTimeSyncWorker: VbglR3GetHostTime failed; rc2=%Rrc\n", rc2);
590 break;
591 }
592
593 RTTIMESPEC GuestNow;
594 RTTimeNow(&GuestNow);
595
596 /*
597 * Calc latency and check if it's ok.
598 */
599 RTTIMESPEC GuestElapsed = GuestNow;
600 RTTimeSpecSub(&GuestElapsed, &GuestNow0);
601 if ((uint32_t)RTTimeSpecGetMilli(&GuestElapsed) < g_cMsTimeSyncMaxLatency)
602 {
603 /*
604 * If we were just restored, set the adjustment threshold to zero to force a resync.
605 */
606 uint32_t TimeSyncSetThreshold = g_TimeSyncSetThreshold;
607 if ( g_fTimeSyncSetOnRestore
608 && idNewSession != g_idTimeSyncSession)
609 {
610 vgsvcTimeSyncLog(2, "vgsvcTimeSyncWorker: The VM session ID changed, forcing resync.\n");
611 g_idTimeSyncSession = idNewSession;
612 TimeSyncSetThreshold = 0;
613 }
614
615 /*
616 * Calculate the adjustment threshold and the current drift.
617 */
618 uint32_t MinAdjust = RTTimeSpecGetMilli(&GuestElapsed) * g_TimeSyncLatencyFactor;
619 if (MinAdjust < g_cMsTimeSyncMinAdjust)
620 MinAdjust = g_cMsTimeSyncMinAdjust;
621
622 RTTIMESPEC Drift = HostNow;
623 RTTimeSpecSub(&Drift, &GuestNow);
624 if (RTTimeSpecGetMilli(&Drift) < 0)
625 MinAdjust += g_cMsTimeSyncMinAdjust; /* extra buffer against moving time backwards. */
626
627 RTTIMESPEC AbsDrift = Drift;
628 RTTimeSpecAbsolute(&AbsDrift);
629
630 if (g_cTimeSyncVerbosity >= 4)
631 {
632 char sz1[64];
633 char sz2[64];
634 vgsvcTimeSyncLog(4, "vgsvcTimeSyncWorker: Host: %s (MinAdjust: %RU32 ms), Guest: %s => %RDtimespec drift\n",
635 RTTimeToString(RTTimeExplode(&Time, &HostNow), sz1, sizeof(sz1)), MinAdjust,
636 RTTimeToString(RTTimeExplode(&Time, &GuestNow), sz2, sizeof(sz2)), &Drift);
637 }
638
639 bool fSetTimeInThisLoop = false;
640 uint64_t AbsDriftMilli = RTTimeSpecGetMilli(&AbsDrift);
641 if ( AbsDriftMilli > MinAdjust
642 || g_fTimeSyncSetOnStart)
643 {
644 /*
645 * Ok, the drift is above the threshold.
646 *
647 * Try a gradual adjustment first, if that fails or the drift is
648 * too big, fall back on just setting the time.
649 */
650 if ( AbsDriftMilli > TimeSyncSetThreshold
651 || g_fTimeSyncSetOnStart
652 || !vgsvcTimeSyncAdjust(&Drift))
653 {
654 vgsvcTimeSyncCancelAdjust();
655 vgsvcTimeSyncSet(&Drift);
656 fSetTimeInThisLoop = true;
657 }
658
659 /*
660 * Log radical host time changes.
661 */
662 int64_t cNsHostDelta = RTTimeSpecGetNano(&HostNow) - RTTimeSpecGetNano(&HostLast);
663 if ((uint64_t)RT_ABS(cNsHostDelta) > RT_NS_1HOUR / 2)
664 vgsvcTimeSyncLog(0, "vgsvcTimeSyncWorker: Radical host time change: %'RI64ns (HostNow=%RDtimespec HostLast=%RDtimespec)\n",
665 cNsHostDelta, &HostNow, &HostLast);
666 }
667 else
668 vgsvcTimeSyncCancelAdjust();
669 HostLast = HostNow;
670
671 /*
672 * Log radical guest time changes (we could be the cause of these, mind).
673 * Note! Right now we don't care about an extra log line after we called
674 * vgsvcTimeSyncSet. fSetTimeLastLoop helps show it though.
675 */
676 int64_t cNsGuestDelta = RTTimeSpecGetNano(&GuestNow) - RTTimeSpecGetNano(&GuestLast);
677 if ((uint64_t)RT_ABS(cNsGuestDelta) > RT_NS_1HOUR / 2)
678 vgsvcTimeSyncLog(0, "vgsvcTimeSyncWorker: Radical guest time change: %'RI64ns (GuestNow=%RDtimespec GuestLast=%RDtimespec fSetTimeLastLoop=%RTbool)\n",
679 cNsGuestDelta, &GuestNow, &GuestLast, fSetTimeLastLoop);
680 GuestLast = GuestNow;
681 fSetTimeLastLoop = fSetTimeInThisLoop;
682 break;
683 }
684 vgsvcTimeSyncLog(3, "vgsvcTimeSyncWorker: %RDtimespec: latency too high (%RDtimespec, max %ums) sleeping 1s\n",
685 &GuestNow, &GuestElapsed, g_cMsTimeSyncMaxLatency);
686 RTThreadSleep(1000);
687 } while (--cTries > 0);
688
689 /* Clear the set-next/set-start flag. */
690 g_fTimeSyncSetOnStart = false;
691
692 /*
693 * Block for a while.
694 *
695 * The event semaphore takes care of ignoring interruptions and it
696 * allows us to implement service wakeup later.
697 */
698 if (*pfShutdown)
699 break;
700 int rc2 = RTSemEventMultiWait(g_TimeSyncEvent, g_TimeSyncInterval);
701 if (*pfShutdown)
702 break;
703 if (rc2 != VERR_TIMEOUT && RT_FAILURE(rc2))
704 {
705 VGSvcError("vgsvcTimeSyncWorker: RTSemEventMultiWait failed; rc2=%Rrc\n", rc2);
706 rc = rc2;
707 break;
708 }
709 }
710
711 vgsvcTimeSyncCancelAdjust();
712 return rc;
713}
714
715
716/**
717 * @interface_method_impl{VBOXSERVICE,pfnStop}
718 */
719static DECLCALLBACK(void) vgsvcTimeSyncStop(void)
720{
721 if (g_TimeSyncEvent != NIL_RTSEMEVENTMULTI)
722 RTSemEventMultiSignal(g_TimeSyncEvent);
723}
724
725
726/**
727 * @interface_method_impl{VBOXSERVICE,pfnTerm}
728 */
729static DECLCALLBACK(void) vgsvcTimeSyncTerm(void)
730{
731#ifdef RT_OS_WINDOWS
732 /*
733 * Restore the SE_SYSTEMTIME_NAME token privileges (if init succeeded).
734 */
735 if (g_hTokenProcess)
736 {
737 if (!AdjustTokenPrivileges(g_hTokenProcess, FALSE, &g_TkOldPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
738 {
739 DWORD dwErr = GetLastError();
740 VGSvcError("vgsvcTimeSyncTerm: Restoring token privileges (SE_SYSTEMTIME_NAME) failed with code %u!\n", dwErr);
741 }
742 CloseHandle(g_hTokenProcess);
743 g_hTokenProcess = NULL;
744 }
745#endif /* !RT_OS_WINDOWS */
746
747 if (g_TimeSyncEvent != NIL_RTSEMEVENTMULTI)
748 {
749 RTSemEventMultiDestroy(g_TimeSyncEvent);
750 g_TimeSyncEvent = NIL_RTSEMEVENTMULTI;
751 }
752}
753
754
755/**
756 * The 'timesync' service description.
757 */
758VBOXSERVICE g_TimeSync =
759{
760 /* pszName. */
761 "timesync",
762 /* pszDescription. */
763 "Time synchronization",
764 /* pszUsage. */
765 " [--timesync-interval <ms>] [--timesync-min-adjust <ms>]\n"
766 " [--timesync-latency-factor <x>] [--timesync-max-latency <ms>]\n"
767 " [--timesync-set-threshold <ms>]\n"
768 " [--timesync-set-start|--timesync-no-set-start]\n"
769 " [--timesync-set-on-restore|--timesync-no-set-on-restore]\n"
770 " [--timesync-verbosity <level>]"
771 ,
772 /* pszOptions. */
773 " --timesync-interval Specifies the interval at which to synchronize the\n"
774 " time with the host. The default is 10000 ms.\n"
775 " --timesync-min-adjust The minimum absolute drift value measured in\n"
776 " milliseconds to make adjustments for.\n"
777 " The default is 1000 ms on OS/2 and 100 ms elsewhere.\n"
778 " --timesync-latency-factor\n"
779 " The factor to multiply the time query latency with\n"
780 " to calculate the dynamic minimum adjust time.\n"
781 " The default is 8 times.\n"
782 " --timesync-max-latency The max host timer query latency to accept.\n"
783 " The default is 250 ms.\n"
784 " --timesync-set-threshold\n"
785 " The absolute drift threshold, given as milliseconds,\n"
786 " where to start setting the time instead of trying to\n"
787 " adjust it. The default is 20 min.\n"
788 " --timesync-set-start, --timesync-no-set-start \n"
789 " Set the time when starting the time sync service.\n"
790#ifdef RT_OS_OS2
791 " Default: --timesync-set-start\n"
792#else
793 " Default: --timesync-no-set-start\n"
794#endif
795 " --timesync-set-on-restore, --timesync-no-set-on-restore\n"
796 " Whether to immediately set the time when the VM is\n"
797 " restored or not. Default: --timesync-set-on-restore\n"
798 " --timesync-verbosity Sets the verbosity level. Defaults to service wide\n"
799 " verbosity level.\n"
800 ,
801 /* methods */
802 vgsvcTimeSyncPreInit,
803 vgsvcTimeSyncOption,
804 vgsvcTimeSyncInit,
805 vgsvcTimeSyncWorker,
806 vgsvcTimeSyncStop,
807 vgsvcTimeSyncTerm
808};
809
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette